gpt4 book ai didi

python - 请求发布到 imgur

转载 作者:可可西里 更新时间:2023-11-01 17:11:07 28 4
gpt4 key购买 nike

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 而不是返回字符串

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

最佳答案

您没有发布 JSON 数据;相反,它将被转换为 URL 编码的数据。 requests 不提供自动 JSON 编码,即使您将内容类型设置为 application/json

使用json模块进行编码:

import json

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

您可以在使用 http://httpbin/post POST echo service 时看到这一点:

>>> 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 或更高版本,您可以将编码留给库;只需将有效负载作为 json 关键字参数传递即可;顺便说一下,在这种情况下它还会设置正确的 Content-Type header :

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

关于python - 请求发布到 imgur,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13727132/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com