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

时间:2018-09-23 19:56:59

标签: python rest basic-authentication

我正在尝试获取与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时,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"}]' 

2 个答案:

答案 0 :(得分:1)

从请求 2.4.2 (https://pypi.python.org/pypi/requests) 开始,支持“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)

答案 1 :(得分:0)

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

您可以尝试:

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)

HTH。

相关问题