使用 tornado.httpclient.AsyncHTTPClient 时如何修复 "RuntimeWarning: Enable tracemalloc to get the object allocation traceback"?

How to fix "RuntimeWarning: Enable tracemalloc to get the object allocation traceback" when using tornado.httpclient.AsyncHTTPClient?

我在我的 tornado 网络应用程序的 headler 中使用 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

我该怎么办?

Function 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("")