我的代码有问题,我不知道还能做些什么来解决这个问题,或者更确切地说找到原因。
我已经开始更改 Tumblr Python API Pytumblr (https://github.com/tumblr/pytumblr) 以支持 Tumblr (https://www.tumblr.com/) 的 Neue Post 格式 (NPF)文档/npf)。 所以我想将草稿照片帖子发布到我的 Tumblr 帐户。总而言之,它做了它应该做的事情......但它确实发布了两次。它在我的草稿中创建了两次相同的帖子,我不知道为什么。
从这里开始:
tumblr_client.create_photo("my blog name", state="draft", tags=["my", "tags"], format="markdown", content=["URL to my photo"])
在另一个模块中,我的内容被创建为 JSON 对象 (content_json),如下所示:
{
"content": [
{
"type": "image",
"media": [
{
"url": "my url"
}
]
}
],
"state": "draft",
"tags": "my,tags",
"format": "markdown"}
现在我们进入请求模块。
我的OAUTH和HTTP请求头配置:
def __init__(self, consumer_key, consumer_secret="", oauth_token="", oauth_secret="", host="https://api.tumblr.com"):
self.host = host
self.oauth = OAuth1(
consumer_key,
client_secret=consumer_secret,
resource_owner_key=oauth_token,
resource_owner_secret=oauth_secret,
signature_type='auth_header'
)
self.consumer_key = consumer_key
self.headers = {
"User-Agent": "pytumblr/" + self.__version,
"Content-Type": "application/json"
}
这是POST函数。
def post(self, content_json, url, params={}, files=[]):
"""
Issues a POST request against the API, allows for multipart data uploads
:param url: a string, the url you are requesting
:param params: a dict, the key-value of all the parameters needed
in the request
:param files: a list, the list of tuples of files
:returns: a dict parsed of the JSON response
"""
url = self.host + url
try:
if files:
return self.post_multipart(content_json, url, params, files)
else:
#data = urllib.parse.urlencode(params)
#if not PY3:
# data = str(data)
resp = requests.post(url, data=content_json, headers=self.headers, auth=self.oauth)
return self.json_parse(resp)
except HTTPError as e:
return self.json_parse(e.response)
一旦程序开始
resp = requests.post(url, data=content_json, headers=self.headers, auth=self.oauth)
它做了两个草稿帖子。
如果我使用 Postman 发送我的内容,它只会发送一篇文章 - 就像它应该的那样。
您能给我一个提示,问题可能出在哪里吗?您需要更多代码吗?
谢谢你:)
可以自己解决! :)
我实现了一个请求会话处理,如此处所述,这达到了目的。 https://requests.readthedocs.io/en/master/user/advanced/
正如@IceTim所说,将其放在请求文档中,遵循以下步骤:
首先定义一个callback_function:
def print_url(r, *args, **kwargs): 打印(r.url)
您在帖子请求中使用它:
requests.get('https://httpbin.org/', hooks={'response': print_url})