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

2024-09-28 21:32:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我在tornado 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中得到了一个例子。 但它不起作用:

^{pr2}$

我该怎么办?在


Tags: selfwebhttpdbaccesssessiondefwww
1条回答
网友
1楼 · 发布于 2024-09-28 21:32:06

函数f()是一个协同程序,您只需调用它而不必等待。您需要使用await f()来调用它。为了实现这一点,您还需要将post方法转换为协同例程。在


{cd3>这是不必要的方法。我不明白你为什么要在另一个线程上运行它。在

我是这样改写的:

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

相关问题 更多 >