gpt4 book ai didi

python - 发出请求时,x-auth-token 未在 header 中传递

转载 作者:行者123 更新时间:2023-11-30 22:55:57 25 4
gpt4 key购买 nike

headers = {'x-auth-token': token,'Content-type':'application/json'}  
url2="http://192.168.56.1:8081/whitelist"
print "HEaders",headers
re=requests.get(url2,headers=headers)
print re.content
r = requests.post(url2, data=json.dumps(file_as_inp))
print r
print "code:"+ str(r.status_code)
print "******************"
print "headers:"+ str(r.headers)
print "******************"
print "content:"+ str(r.content)

我正在编写一个脚本,以便将数据发布到网络服务。我在 header 中传递身份验证 token 和内容类型,并将 json 值列表作为有效负载传递。file_as_inp 包含 json 值列表,如

[{'ip': '10.1.2.3'}, {'ip': '10.3.4.5'}, {'ip': '10.8.9.A'}, {'ip': '0'}, {'ip':'00'}, {'ip': 'null'}, {'ip': '10.9.4.5'}, {'ip': '10.7.6.2'}]

header 包含:

{'Content-type': 'application/json', 'x-auth-token': u'313e95e7-ce08-46bf-8891-6d68fc615170'}  

我正在一个命令提示符上运行我的服务,并在另一个命令提示符上运行此脚本。我得到的响应为 200。当我打印 r.headers 时,我得到一些输出为

headers:{'Content-Length': '57', 'Access-Control-Allow-Headers': 'Content-Type', 'Access-Control-Max-Age': '21600', 'Server': 'Werkzeug/0.11.9 Python/2.7', 'Date': 'Fri, 13 May 2016 04:47:52 GMT', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'HEAD, GET, POST, OPTIONS', 'Content-Type': 'text/html;charset=utf-8'}

但是,当我打印 r.content 时,我会打印以下行:

content:x-auth-token not passed in header, please pass the token.

谁能告诉我哪里错了?为什么我得到上面的行作为输出?将数据发布到网络服务后,我需要执行验证并检查 IP 是否有效。但是,我被困在这里了。

最佳答案

调用 POST 请求时,您没有设置 header 值。您可以将代码更改为:

r = requests.post(url, data=json.dumps(file_as_inp), headers=headers)

或者推荐的方法是使用 Session对象。

The Session object allows you to persist certain parameters across requests. Sessions can also be used to provide default data to the request methods. This is done by providing data to the properties on a Session object:

x-auth-token 将添加到您使用 Session 对象发出的每个请求的 header 中。您的代码应该如下所示:

sess = requests.Session()
sess.headers.update({'x-auth-token': token,'Content-type':'application/json'} )
url = "http://192.168.56.1:8081/whitelist"

resp = sess.get(url, headers=headers)
print resp.content

resp = sess.post(url, data=json.dumps(file_as_inp))
print resp.content

关于python - 发出请求时,x-auth-token 未在 header 中传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37201591/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com