python - Pastebin api为python中的requests.post返回 "Bad API request, use POST request, not GET"?

标签 python pastebin

我正在尝试使用发送 post 请求的 requests.post 从 python 使用 patebin api,我的代码是

# 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 发布请求适用于我的 api key ,我得到了粘贴 url。
但我收到 错误的 API 请求,使用 POST 请求,而不是 GET 上面python代码的输出是否有人有任何建议

最佳答案

正如@LeventeKovács 指出的那样,简单的解决方法是将 URL 中的请求类型从“http”更改为“https”。这就是为什么 Requests 库没有按照您当前的 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 Moved Permanently If the 301 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued. Note: When automatically redirecting a POST request after receiving a 301 status code, some existing HTTP/1.0 user agents will erroneously change it into a GET request.


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

关于python - Pastebin api为python中的requests.post返回 "Bad API request, use POST request, not GET"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66890004/

相关文章:

python - dask 性能随着使用调度程序 ='processes' 传递到 dask.compute 的延迟对象数量的增加而降低

python - 如何在 X-Y 平面上绘制标签之间的欧氏距离

python - 相当于 float128

mysql - 这个 MySQL 查询中的索引定义有什么问题?

javascript - 使用 Mechanize for Python 模拟简单的 javascript (location.href=)

python - 平均获胜

http - 通过 API 编辑现有的 Pastebin 文档

c# - pastebin API : Bad API request, 错误 api_paste_format 无效

php - 删除从数据库检索的 TIME 函数前面的零?

javascript - "Bad API request, invalid or expired api_user_key"