curl或者python脚本请求127.0.0.1返回504错误

本地起了一个测试服务,浏览器可以正常访问,curl或者python请求返回504错误。

问题描述

1. 本地读了一个简单的java服务,用浏览器请求,正常返回。

2. 一些复杂的请求,需要postman或者python脚本来完成,用postman尝试,也正常访问。

3. 用python的requests模块请求时,总是返回504错误。

import time
import requests


def test():
    start_time = time.time()
    res = requests.get("http://127.0.0.1:8088/user/index", headers=headers)
    print(res.ok)
    print(res.text)
    print('query_history cost time: {} ms'.format(int((time.time() - start_time) * 1000)/1000.0))


if __name__ == "__main__":
    test()

4. 在iTerm2下,用curl命令也是504错误。

$curl -I --connect-timeout 1000 "http://127.0.0.1:8088/user/index"
HTTP/1.1 504 Gateway Time-out
Server: squid/2.7.STABLE9
Date: Sun, 17 Jan 2021 09:12:03 GMT
Content-Type: text/html
Content-Length: 958
X-Squid-Error: ERR_CONNECT_FAIL 111
X-Cache: MISS from SZ-SQUIDWEB-46
X-Cache-Lookup: MISS from SZ-SQUIDWEB-46:8080
Connection: close 

尝试解决

1. 针对http 504错误常见原因,curl和python脚本设置超时时间等,不生效。

2. 将python脚本设置headers,修改成与浏览器或者postman完全一样,也不生效。

import time
import requests


def test():
    start_time = time.time()
    headers = {
        'Content-Type': 'application/json',
        'User-Agent': 'PostmanRuntime/7.26.8',
        'Accept': '*/*',
        'Accept-Encoding': 'gzip, deflate, br',
        'Connection': 'keep-alive',
    }
    res = requests.get("http://127.0.0.1:8088/user/index", headers=headers)
    print(res.ok)
    print(res.text)


if __name__ == "__main__":
    test()

 问题原因

通过上面的描述和分析,大概猜测是本地代理导致,可以用export或者echo $no_proxy,查看$no_proxy,看看有不有设置,或者设置有没有问题,解决办法就是是访问本地时禁用代理。

解决方案

方案1:用shell命令

清除no_proxy环境变量前,先将echo $no_proxy的值保留一份。

用unset清除no_proxy环境变量,试试效果,返回504错误。

(base) leonlai@LEONLAI-MB0 test % unset no_proxy
(base) leonlai@LEONLAI-MB0 test % curl -I --connect-timeout 1000  "http://127.0.0.1:8088/user/index"
HTTP/1.1 504 Gateway Time-out
Server: squid/2.7.STABLE9
Date: Mon, 18 Jan 2021 02:32:49 GMT
Content-Type: text/html
Content-Length: 958
X-Squid-Error: ERR_CONNECT_FAIL 111
X-Cache: MISS from SZ-SQUIDWEB-27
X-Cache-Lookup: MISS from SZ-SQUIDWEB-27:8080
Connection: close

再设置no_proxy环境变量,试试效果,返回200错误

(base) leonlai@LEONLAI-MB0 test % export no_proxy=127.0.0.1
(base) leonlai@LEONLAI-MB0 test % echo $no_proxy
127.0.0.1
(base) leonlai@LEONLAI-MB0 test % curl -I --connect-timeout 1000  "http://127.0.0.1:8088/user/index"
HTTP/1.1 200
Content-Type: application/json
Content-Length: 35
Date: Mon, 18 Jan 2021 02:37:09 GMT

方案2:在python设置

在python脚本中,访问时127.0.0.1禁用代理,问题代码如下

import time
import requests

import os
os.environ['NO_PROXY'] = '127.0.0.1'


def test():
    start_time = time.time()
    res = requests.get("http://127.0.0.1:8088/user/index", headers=headers)
    print(res.ok)
    print(res.text)


if __name__ == "__main__":
    test()

 只要设置一次,再把上面红色代码部分去掉,后面curl和python脚本也都可以正常访问了!

 


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部