2012-12-05 36 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 

这应该创建一个相册的标题album title则返回的字符串是如何代替要求张贴到imgur

{ 
    "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" 
    } 
} 

没有人有使用设定请求专辑标题的解决方案?

这里是对imgur API文档http://api.imgur.com/resources_auth

回答

2

您还没有发布JSON数据的链接;相反,它会转换为URL编码的数据。 requests不提供自动JSON编码,即使您将内容类型设置为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'} 

如果您正在使用2.4.2 requests或更新的版本,你可以离开:

import json 

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

您可以使用http://httpbin/post POST echo service时看到此编码到库;只需将有效载荷作为json关键字参数传入;顺带也将设置正确的Content-Type头在这种情况下:

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

编码的有效载荷只是URL没有任何区别,它应该工作,但它并不 –

+0

@lab_notes:有可能是*其他*问题也是,但不正确编码JSON是其中的第一个。 –