我有一个在支持 POST 请求的本地主机上运行的 julia 服务器。我正在尝试从 python 向 julia 服务器发送请求,但似乎 python 无法 ping 本地主机。结果出现 403 错误
当我尝试使用 PostMan 时,POST 请求有效,并且我能够看到预期的结果(Json 文件),但使用 python 则不行。 Julia 服务器不需要任何身份验证。
我厌倦了向
requests.post()
添加代理和不同的用户代理,但没有得到我需要的结果。当我添加 {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}
时,我得到响应 200 但它正在废弃网站(404 页面,正如预期的,因为这不是一个网站)而不请求实际的服务器(我会知道它何时实际请求 Julia 服务器,因为它打印其服务器上的结果)。我请求了本地 jupyter 实验室 url,它说是 false,但我能够打开 jupyter 实验室,所以我猜测 python 无法从本地服务器发送请求。
这是示例代码:
import requests
from urllib import request
def internet_on(): ## this is where I tested to ping jupyter lab, result: False
try:
request.urlopen('http://127.0.0.1:7000', timeout=1)
return True
except request.URLError as err:
return False
internet_on()
proxies = {"http" : "proxy_address"}
data = {"key": "value"}
r = requests.post('http://127.0.0.1:7000', proxies=proxies, json = data)
>>> r
>>> 403
如果我使用标题:
headers = {'Content-type': 'application/JSON', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}
r = requests.post('http://127.0.0.1:7000', headers=headers, proxies=proxies, json = data)
>>> r
>>> 200 ## but r.contents is the 404 page details not the json file
类似问题:https://github.com/psf/requests/issues/879
将此添加到代码中以使其正常工作。
NO_PROXY = {
'no': 'pass',
}
r = requests.post(uri, proxies=NO_PROXY)
如果您想添加通用配置,还有其他方法:
import os
os.environ['NO_PROXY'] = '127.0.0.1'
编辑:我在此处发布问题后立即找到了解决方案。不滥用系统。在我发布问题之前,我已经被这个问题困扰了 2 天