简体   繁体   中英

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

I use tornado.httpclient.AsyncHTTPClient in my tornado web application' headler.

Here is my code

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

I get the example in https://www.tornadoweb.org/en/stable/httpclient.html . But it doesn't work:

RuntimeWarning: coroutine 'AdminUploadAlignerParagraphTaskHandler.post.<locals>.f' was never awaited
  f()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

What should I do?

Function f() is a coroutine, and you're just calling it without awaiting. You'll need to use await f() to call it. For that to work, you'll also need to convert the post method to a coroutine.


You're unnecessarily complicating the post method. I don't see why you're running it on a separate thread.

Here's how I'd rewrite it:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM