在Tornado5发布后,我们无法在IOLoop运行时使用同步HTTPClient。我们将不得不改用AsyncHTTPClient。
因此,有没有人可以帮助我,向我展示如何在Tornado(Python web框架)中使用AsyncHTTPClient进行同步API调用,它使用异步和等待,而不是旧的传统方法。
我试着以这种方式实现它,并且得到了多个错误。
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))
但不幸的是,我收到了很多错误。
[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
发布于 2020-04-10 17:27:34
我认为对于什么是synchronous
请求有一些混淆;同步请求在程序执行之前执行(因此整个IOLoop
),然后它才能return
一个结果;这通常是,而不是你想要的。
asynchronous
请求在完成之前返回;它返回占位符对象(Futures
),这些对象通常使用await
或yield
关键字转换为其结果。
我认为你正在寻找的是一种等待的方法,等待的请求完成,如上所述,这是通过等待或放弃来完成的。
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']
...
请注意
async def get(self):
和
response = await self.get_result(query)
比特。
https://stackoverflow.com/questions/61130270
复制相似问题