使用python请求的顺序请求

使用python请求的顺序请求,python,for-loop,timeout,request,sequential,Python,For Loop,Timeout,Request,Sequential,现在我正在使用Flask,在尝试使用python请求模块执行多个GET请求时遇到了问题 如果我尝试发送一系列请求,第一个请求会成功完成,但其他请求会引发超时异常 以下是视图代码的一部分: import requests sess = requests.Session() site_url = 'http://www.example.com/api/' steps = ['first_step', 'second_step', 'third_step'] step_responses = dic

现在我正在使用Flask,在尝试使用python请求模块执行多个GET请求时遇到了问题

如果我尝试发送一系列请求,第一个请求会成功完成,但其他请求会引发超时异常

以下是视图代码的一部分:

import requests

sess = requests.Session()
site_url = 'http://www.example.com/api/'
steps = ['first_step', 'second_step', 'third_step']
step_responses = dict()
for s in steps:
    try:
        req = sess.get(site_url + s, timeout=5))
    except requests.exceptions.Timeout:
        return jsonify({'result':False, 'error':'timeout'})
    except requests.exceptions.ConnectionError:
        return jsonify({'result':False, 'error':'connection_error'})
else:
        step_responses[s] = True
如果我将此部分提取到一个独立的.py文件中,它将成功完成

import requests

sess = requests.Session()
site_url = 'http://www.example.com/api/'
steps = ['first_step', 'second_step', 'third_step']
step_responses = dict()
for s in steps:
    try:
        req = sess.get(site_url + s, timeout=5)
    except requests.exceptions.Timeout:
        step_responses[s] = 'timeout'
    except requests.exceptions.ConnectionError:
        step_responses[s] = 'conn_error'
    else:
        step_responses[s] = 'ok'
print step_responses

对我有用。您可能需要检查第二步和第三步

import requests

sess = requests.Session()
def module():
site_url = 'http://stackoverflow.com/'
steps = ['users', 'questions', 'tags']
step_responses = dict()
for s in steps:
    try:
        req = sess.get(site_url + s, timeout=5)
    except requests.exceptions.Timeout:
        return jsonify({'result':False, 'error':'timeout'})
    except requests.exceptions.ConnectionError:
        return jsonify({'result':False, 'error':'connection_error'})
else:
        step_responses[s] = True

您可能希望确保从req对象读取所有值。 我认为您可能需要req.text和req.status\u代码或req.content

检查页面的中间部分:他们讨论会话参数的地方 类请求.adapters.HTTPAdapter(池连接=10,池最大大小=10,最大重试次数=0,池块=False)

我根本不知道如何使用连接池等等,但是文档中确实说了()(寻找Keep-Alive)


“请注意,只有在读取了所有主体数据后,连接才会释放回池以供重用;请确保将stream设置为False或读取响应对象的content属性。”

为什么要精心使用内部对象?为什么不在这里使用sess.get(site\u url+s)?谢谢你的回答。我试过了,但结果是一样的:第二步和第三步抛出超时异常。我没有说这是一个答案,只是对您如何使用API的观察。我在你的Python代码中没有看到任何导致超时的东西。看起来,服务器自己在做这一切。在第一个代码示例中有一个无关的参数