我正在开发一个基于GAE和python 2.7.13的应用程序。我想做的是在处理程序中进行一堆异步API调用。像这样:
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
一起使用。
有人可以帮我吗?
答案 0 :(得分:2)
Urlfetch,默认情况下与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,则可以使用threading和synchronized Queue来读取结果来手动并行化请求。