因为当我尝试通过localhost URL调用函数时,是否会导致超时错误?
示例代码:
import tornado.ioloop
import tornado.web
import requests
import os
from threading import Timer, Thread
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, world")
class TestTornado(tornado.web.RequestHandler):
def get(self):
url = "http://localhost:8888"
requests.get(url, timeout=5)
self.write("OK!")
def make_app():
return tornado.web.Application([
(r"/", MainHandler),
(r"/test", TestTornado),
])
if __name__ == "__main__":
app = make_app()
app.listen(8888)
tornado.ioloop.IOLoop.current().start()
我尝试致电 http://127.0.0.1:8888/test ,但是会生成此错误:
`
Traceback (most recent call last):
File "/home/mpimentel/envtornado/lib/python3.6/site-packages/tornado/web.py", line 1590, in _execute
result = method(*self.path_args, **self.path_kwargs)
File "server.py", line 14, in get
requests.get(url, timeout=5)
File "/home/mpimentel/envtornado/lib/python3.6/site-packages/requests/api.py", line 75, in get
return request('get', url, params=params, **kwargs)
File "/home/mpimentel/envtornado/lib/python3.6/site-packages/requests/api.py", line 60, in request
return session.request(method=method, url=url, **kwargs)
File "/home/mpimentel/envtornado/lib/python3.6/site-packages/requests/sessions.py", line 524, in request
resp = self.send(prep, **send_kwargs)
File "/home/mpimentel/envtornado/lib/python3.6/site-packages/requests/sessions.py", line 637, in send
r = adapter.send(request, **kwargs)
File "/home/mpimentel/envtornado/lib/python3.6/site-packages/requests/adapters.py", line 529, in send
raise ReadTimeout(e, request=request)
requests.exceptions.ReadTimeout: HTTPConnectionPool(host='localhost', port=8888): Read timed out. (read timeout=5)
`
拨打电话的正确方法是什么?
答案 0 :(得分:1)
gcc -Wall -Wextra
是一个同步库,但是Tornado是一个异步框架。您不应从Tornado requests
线程中调用诸如requests.get()
之类的阻塞同步函数。您必须将IOLoop
用作协程,然后从线程池中调用get()
:
requests.get()
或将async def get(self):
resp = await IOLoop.current().run_in_executor(None, lambda: requests.get(...))
的使用替换为Tornado的requests
等无阻塞等效项:
AsyncHTTPClient
答案 1 :(得分:0)
这是一个请求错误。
将此代码粘贴到您的程序中:
从request.packages.urllib3.exceptions导入InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning)