首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用Tornado、Python的同步API调用

使用Tornado、Python的同步API调用
EN

Stack Overflow用户
提问于 2020-04-10 05:12:11
回答 1查看 279关注 0票数 0

在Tornado5发布后,我们无法在IOLoop运行时使用同步HTTPClient。我们将不得不改用AsyncHTTPClient。

因此,有没有人可以帮助我,向我展示如何在Tornado(Python web框架)中使用AsyncHTTPClient进行同步API调用,它使用异步和等待,而不是旧的传统方法。

我试着以这种方式实现它,并且得到了多个错误。

代码语言:javascript
运行
复制
class IndexHandler(tornado.web.RequestHandler):
    async def get_result(self, query):
        client = tornado.httpclient.AsyncHTTPClient()
        return await client.fetch("https://pokeapi.co/api/v2/pokemon/" + urllib.parse.urlencode(query))

    def get(self):
        q = self.get_argument('q')
        query = {'q': q}

        loop = asyncio.get_event_loop()
        response = loop.run_until_complete(self.get_result(query))
        loop.close()

        #response = client.fetch("https://pokeapi.co/api/v2/pokemon/" + urllib.parse.urlencode(query))
        #self.on_response(response)
        if response == "Not Found":
            self.write("Invalid Input")
            response_data = json.loads(response.body)
            pikachu_name = response_data['name']
            pikachu_order = response_data['order']
            self.write("""
                Pickachu Name: %s <br>
                Pickachu Order: %d <br>
                """ %(pikachu_name, pikachu_order))

但不幸的是,我收到了很多错误。

代码语言:javascript
运行
复制
[E 200410 02:40:48 web:1792] Uncaught exception GET /?q=pikachu (::1)
    HTTPServerRequest(protocol='http', host='localhost:8000', method='GET', uri='/?q=pikachu', version='HTTP/1.1', remote_ip='::1')
    Traceback (most recent call last):
      File "C:\Python\Python37\lib\site-packages\tornado\web.py", line 1701, in _execute
        result = method(*self.path_args, **self.path_kwargs)
      File "C:\Users\Bagga\Documents\tornado\Tweet Rate\handlers.py", line 25, in get
        response = loop.run_until_complete(self.get_result(query))
      File "C:\Python\Python37\lib\asyncio\base_events.py", line 571, in run_until_complete
        self.run_forever()
      File "C:\Python\Python37\lib\asyncio\base_events.py", line 526, in run_forever
        raise RuntimeError('This event loop is already running')
    RuntimeError: This event loop is already running
[E 200410 02:40:48 web:2250] 500 GET /?q=pikachu (::1) 3.33ms
[E 200410 02:40:49 base_events:1608] Task exception was never retrieved
    future: <Task finished coro=<IndexHandler.get_result() done, defined at C:\Users\Bagga\Documents\tornado\Tweet Rate\handlers.py:16> exception=HTTP 404: Not Found>
    Traceback (most recent call last):
      File "C:\Users\Bagga\Documents\tornado\Tweet Rate\handlers.py", line 18, in get_result
        return await client.fetch("https://pokeapi.co/api/v2/pokemon/" + urllib.parse.urlencode(query))
    tornado.httpclient.HTTPClientError: HTTP 404: Not Found
EN

回答 1

Stack Overflow用户

发布于 2020-04-10 17:27:34

我认为对于什么是synchronous请求有一些混淆;同步请求在程序执行之前执行(因此整个IOLoop),然后它才能return一个结果;这通常是,而不是你想要的。

asynchronous请求在完成之前返回;它返回占位符对象(Futures),这些对象通常使用awaityield关键字转换为其结果。

我认为你正在寻找的是一种等待的方法,等待的请求完成,如上所述,这是通过等待或放弃来完成的。

代码语言:javascript
运行
复制
class IndexHandler(tornado.web.RequestHandler):
    async def get_result(self, query):
        client = tornado.httpclient.AsyncHTTPClient()
        response = await client.fetch("https://pokeapi.co/api/v2/pokemon/" + urllib.parse.urlencode(query))
        return response.body

    async def get(self):
        q = self.get_argument('q')
        query = {'q': q}
        response = await self.get_result(query)
        if response == b"Not Found":
            self.write("Invalid Input")
        else:
            response_data = json.loads(response.body)
            pikachu_name = response_data['name']
            ...

请注意

代码语言:javascript
运行
复制
async def get(self):

代码语言:javascript
运行
复制
response = await self.get_result(query)

比特。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61130270

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档