当前位置: 代码迷 >> python >> 具有基本身份验证的 Python REST POST
  详细解决方案

具有基本身份验证的 Python REST POST

热度:82   发布时间:2023-06-21 10:59:59.0

我正在尝试使用 Python 3 获取 POST 请求,该请求会将 json 有效负载提交到使用基本身份验证的平台。 我收到 405 状态错误,并相信这可能是由于我的有效负载的格式造成的。 我正在学习 Python,但仍然不确定何时使用“vs”、对象 vs 数组以及某些请求的语法。搜索,我无法找到类似的问题,发布具有基本身份验证的数组。这是什么我现在有:

import requests
import json

url = 'https://sampleurl.com'
payload = [{'value': '100','utcRectime': '09/23/2018 11:59:00 PM','comment': "test",'correctionValue': '0.0','unit': 'C'}]
headers = {'content-type': 'application/json'}

r = requests.post(url, auth=('username','password'), data=json.dumps(payload), headers=headers)


print (r)

在 API swagger 中测试,CURL 包含以下格式:

curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '[{"value": "100","utcRectime": "9/23/2018 11:59:00 PM","comment": "test","correctionValue": "0.0","unit": "C"}]' 

我认为您不想将列表dump为字符串。 requests会将 python 数据结构击败到正确的有效负载中。 如果您指定json关键字参数,则requests库也足够智能以生成正确的标头。

你可以试试:

r = requests.post(url, auth=('username','password'), json=payload)

此外,有时站点会阻止未知的用户代理。 您可以尝试通过执行以下操作来假装您是浏览器:

headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
r = requests.post(url, auth=('username','password'), json=payload, headers=headers)

哈。

从请求 2.4.2 ( ) 开始,支持“json”参数。 无需指定“内容类型”。 所以较短的版本:

requests.post('https://sampleurl.com', auth=(username, password), json={'value': '100','utcRectime': '09/23/2018 11:59:00 PM','comment': "test",'correctionValue': '0.0','unit': 'C'})

细节:

import requests
import json

username = "enter_username"
password = "enter_password"

url = "https://sampleurl.com"
data = open('test.json', 'rb')

r = requests.post(url, auth=(username, password), data=data)

print(r.status_code) 
print(r.text)
  相关解决方案