我在龙卷风Web应用程序的标题中使用tornado.httpclient.AsyncHTTPClient
。
这是我的代码
class CustomTornadoHandler(tornado.web.RequestHandler):
def set_default_headers(self):
self.set_header("Access-Control-Allow-Origin", "*")
self.set_header("Access-Control-Allow-Headers", "x-requested-with,application/x-www-form-urlencoded")
self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PATCH, DELETE, PUT')
def initialize(self, *args, **kwargs):
self.db_session = db_session()
def on_finish(self):
db_session.remove()
class AdminUploadAlignerParagraphTaskHandler(CustomTornadoHandler):
executor = concurrent.futures.ThreadPoolExecutor()
@run_on_executor
def post(self):
async def f():
http_client = tornado.httpclient.AsyncHTTPClient()
try:
response = await http_client.fetch("http://www.google.com")
except Exception as e:
print("Error: %s" % e)
else:
logging.info(response.body)
...
self.write("")
f()
我在https://www.tornadoweb.org/en/stable/httpclient.html中得到了示例。 但这不起作用:
RuntimeWarning: coroutine 'AdminUploadAlignerParagraphTaskHandler.post.<locals>.f' was never awaited
f()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
我该怎么办?
答案 0 :(得分:0)
函数f()
是一个协程,您只是在不等待的情况下调用它。您需要使用await f()
来调用它。为此,您还需要将post
方法转换为协程。
您不必要地使post
方法复杂化。我不明白为什么要在单独的线程上运行它。
这是我要重写的方式:
# no need to run on separate thread
async def post():
http_client = tornado.httpclient.AsyncHTTPClient()
try:
response = await http_client.fetch("http://www.google.com")
except Exception as e:
print("Error: %s" % e)
else:
logging.info(response.body)
...
self.write("")