Patebin api在python中返回"Bad API request, use POST request, not GET" requests.post?



我正试图使用requests.post从python中使用patebin-api,它发送一个post请求,我的代码是

# importing the requests library
import requests
# defining the api-endpoint
API_ENDPOINT = "http://pastebin.com/api/api_post.php"
# your API key here
API_KEY = "my api key"
# your source code here
source_code = '''
print("Hello, world!")
a = 1
b = 2
print(a + b)
'''
# data to be sent to api
data = {'api_dev_key':API_KEY,
'api_option':'paste',
'api_paste_code':source_code,
'api_paste_format':'python'}
# sending post request and saving response as response object
r = requests.post(url = API_ENDPOINT, data = data)
# extracting response text
pastebin_url = r.text
print("The pastebin URL is:%s"%pastebin_url)

文档中给出的curl post请求适用于我的api密钥,我得到了粘贴url。

但我得到了错误的API请求,使用POST请求,而不是GET以上python代码的输出是否有人有任何建议

正如@LeventeKovács所指出的,简单的修复方法是将URL中的请求类型从"更改为";http";至";https";。这就是为什么请求库不能对您当前的URL执行您想要/期望的操作。。。

您正在对HTTPS端点执行HTTP请求。这需要从HTTP重定向到HTTPS。在处理此重定向时,请求库将POST更改为GET,代码为:

# Second, if a POST is responded to with a 301, turn it into a GET.
# This bizarre behaviour is explained in Issue 1704.
if response.status_code == codes.moved and method == 'POST':
method = 'GET'

这里有一个链接,在评论中提到的问题与此代码相关:

https://github.com/psf/requests/issues/1704

该问题引用了HTTP规范的这一部分:

301永久移动如果收到301状态代码作为响应对于GET或HEAD以外的请求,用户代理不得自动重定向请求,除非可以由用户,因为这可能会更改请求的条件已发布。注意:在之后自动重定向POST请求时接收到301状态代码,一些现有的HTTP/1.0用户代理将错误地将其更改为GET请求。

然后似乎继续通过说请求库应该做大多数/所有浏览器当前所做的事情来合理化代码的行为,即将POST更改为GET并在新地址重试。

我遇到了与您描述的相同的问题。我在API链接中使用https而不是http解决了这个问题。

我的建议是:API_ENDPOINT=";https://pastebin.com/api/api_post.php">

最新更新