如何在GAE应用程序中执行异步api请求? [英] How to do async api requests in a GAE application?
问题描述
我正在开发一个基于GAE和python 2.7.13的应用程序.我想做的是在处理程序中进行一堆异步API调用.像这样:
I am working on an application which is based on GAE with python 2.7.13. What I want to do is that to make a bunch of async API calls inside a handler. Something like that:
class MakeRequests(webapp2.RequestHandler):
def post(self, *v, **kv):
*do an async api call#1*
*do an async api call#2*
*do an async api call#3*
*wait for response from all of above api requests*
*make response in a way like if call#1 failes, make it's expected*
*attributes in response as None, if call#2 succeeds add it's*
*attributes in response etc. This is just an example.*
为此,我尝试了asyncio
,grequests
,requests
和simple-requests
之类的库,它们似乎不起作用,因为它们与GAE
或python 2.7.13
.
有人可以在这里帮助我吗?
For that purpose, I have tried libraries like asyncio
, grequests
, requests
and simple-requests
, they don't seems to be working because either they are not compatible with with GAE
or with python 2.7.13
.
Can anyone help me here?
推荐答案
Urlfetch, which is bundled by default with GAE has a way of making asynchronous calls:
from google.appengine.api import urlfetch
def post(self, *v, **kv):
rpcs = []
for url in urls:
rpc = urlfetch.create_rpc()
urlfetch.make_fetch_call(rpc, url)
rpcs.append(rpc)
results = [rpc.get_result() for rpc in rpcs]
# do stuff with results
如果由于某种原因您不想使用urlfetch,则可以使用同步队列阅读结果.
If, for some reason you don't want to use urlfetch you can parallelize the requests manually by using threading and a synchronized Queue to read the results.
这篇关于如何在GAE应用程序中执行异步api请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!