英文:
post requests in python
问题
我想在Python中进行带有基本身份验证和令牌的POST请求。我已经在Postman中测试过这个POST请求,它可以正常工作,但在Python中,我总是得到403状态码。
对于这个API,我需要执行以下步骤:
- 首先,使用GET请求从标头中获取令牌。
- 在POST请求的标头中使用此令牌。
auth = HTTPBasicAuth('用户名', '密码')
token = requests.get(URL_token, auth=auth, headers={"x-csrf-token":"FETCH"}).headers['x-csrf-token']
requests.post(POST_url, data=json.dumps(test_data), headers={"x-csrf-token":token}, auth=auth)
test_data是一个列表类型,在Postman中可以正常工作。
在POST请求中是否有什么我做错了?
英文:
I want to do a post request in python with basic authentication AND token. I have already tested the post in postman and it worked but with python I always get status code 403.
For this API I have to do...
- first fetch a token from the header with a GET request
- use this token in header for POST request
auth = HTTPBasicAuth('User', 'Password')
token = requests.get(URL_token, auth=auth, headers={"x-csrf-token":"FETCH"}).headers['x-csrf-token']
requests.post(POST_url, data=json.dumps(test_data), headers={"x-csrf-token":token}, auth=auth)
The test_data are type of a list and again, in postman it works.
Is there something which I am doing wrong in the POST?
答案1
得分: 0
在Postman中,您的JSON负载作为请求体,但您正在传递它作为data
,该参数通常用于表单数据。
因此,尝试更改此行:
requests.post(POST_url, data=json.dumps(test_data), headers={"x-csrf-token": token}, auth=auth)
为:
requests.post(POST_url, json=test_data, headers={"x-csrf-token": token}, auth=auth)
英文:
In Postman, your JSON payload as the body, but you're passing it data
which is used for form data.
Therefore, try changing this line
requests.post(POST_url, data=json.dumps(test_data), headers={"x-csrf-token":token}, auth=auth)
to
requests.post(POST_url, json=test_data, headers={"x-csrf-token":token}, auth=auth)
答案2
得分: 0
你需要在一个 requests.Session()
内执行每一步:
s = requests.Session()
token = s.get(get_test_token, auth=auth, headers={"x-csrf-token":"FETCH"}).headers['x-csrf-token']
s.post(get_test_token, json=test_data, headers={"x-csrf-token":token}, auth=auth)
英文:
You have to do every step within a requests.Session()
:
s = requests.Session()
token = s.get(get_test_token, auth=auth, headers={"x-csrf-token":"FETCH"}).headers['x-csrf-token']
s.post(get_test_token, json=test_data, headers={"x-csrf-token":token}, auth=auth)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论