2012-12-05 4 views
1
from oauth_hook import OAuthHook 
import requests, json 
OAuthHook.consumer_key = "KEYHERE" 
OAuthHook.consumer_secret = "SECRET HERE" 
oauth_hook = OAuthHook("TOKEN_KEY_HERE", "TOKEN_SECRET_HERE", header_auth=True) 
headers = {'content-type': 'application/json'} 
client = requests.session(hooks={'pre_request': oauth_hook}, headers=headers) 
payload = {"title":"album title"} 
r = client.post("http://api.imgur.com/2/account/albums.json",payload) 
print r.text 

이를 imgur에 게시요청이 반환 문자열이 얼마나 타이틀 대신 <code>album title</code>와 앨범을 만들어야합니다

{ 
    "albums": { 
     "id": "IMGURID", 
     "title": "", 
     "description": "", 
     "privacy": "public", 
     "cover": "", 
     "order": 0, 
     "layout": "blog", 
     "datetime": "2012-12-05 15:48:21", 
     "link": "IMGUR LINK", 
     "anonymous_link": "ANONYLINK" 
    } 
} 

사람이 요청을 사용하여 앨범 제목을 설정하기위한 솔루션이 있습니까? 여기

당신은 JSON 데이터를 게시하지 않은 imgur의 API 문서 http://api.imgur.com/resources_auth

답변

2

에 대한 링크입니다; 대신 URL 인코딩 된 데이터로 변환됩니다. requests은 콘텐트 유형을 application/json으로 설정하더라도 자동 JSON 인코딩을 제공하지 않습니다.

>>> import json, requests, pprint 
>>> headers = {'content-type': 'application/json'} 
>>> payload = {"title":"album title"} 
>>> pprint.pprint(requests.post('http://httpbin.org/post', payload, headers=headers).json) 
{u'args': {}, 
u'data': u'title=album+title', 
u'files': {}, 
u'form': {}, 
u'headers': {u'Accept': u'*/*', 
       u'Accept-Encoding': u'gzip, deflate, compress', 
       u'Connection': u'keep-alive', 
       u'Content-Length': u'17', 
       u'Content-Type': u'application/json', 
       u'Host': u'httpbin.org', 
       u'User-Agent': u'python-requests/0.14.2 CPython/2.7.3 Darwin/11.4.2'}, 
u'json': None, 
u'origin': u'xx.xx.xx.xx', 
u'url': u'http://httpbin.org/post'} 
>>> pprint.pprint(requests.post('http://httpbin.org/post', json.dumps(payload), headers=headers).json) 
{u'args': {}, 
u'data': u'{"title": "album title"}', 
u'files': {}, 
u'form': {}, 
u'headers': {u'Accept': u'*/*', 
       u'Accept-Encoding': u'gzip, deflate, compress', 
       u'Connection': u'keep-alive', 
       u'Content-Length': u'24', 
       u'Content-Type': u'application/json', 
       u'Host': u'httpbin.org', 
       u'User-Agent': u'python-requests/0.14.2 CPython/2.7.3 Darwin/11.4.2'}, 
u'json': {u'title': u'album title'}, 
u'origin': u'xx.xx.xx.xx', 
u'url': u'http://httpbin.org/post'} 

당신이 requests 버전 2.4.2 이상을 사용하는 경우, 당신은을 남길 수 있습니다 : (가) http://httpbin/post POST echo service 사용하는 경우

import json 

r = client.post("http://api.imgur.com/2/account/albums.json", json.dumps(payload)) 

당신이 볼 수

인코딩하는 json 모듈을 사용하여 라이브러리에 인코딩; 단순히 페이로드에서 json 키워드 인수로 전달하십시오. 우연히 또한이 경우 올바른 컨텐츠 유형 헤더를 설정합니다 :

이 가
r = client.post("http://api.imgur.com/2/account/albums.json", json=payload) 
페이로드를 암호화하는
+0

그냥 URL이 어떤 차이를 만들기 위해 실패 , 그것은 작동해야하지만하지 –

+0

@lab_notes을 수행 다른 *가있을 수 있습니다 * 문제도 있지만 JSON을 제대로 인코딩하지 않으면 그 중 첫 번째 문제입니다. –