我正在开发一个基于 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
and simple-requests
,它们似乎不起作用,因为它们与GAE
或与python 2.7.13
。
有人能帮我一下吗?
Urlfetch,默认与 GAE 捆绑在一起有一种进行异步调用的方法 https://cloud.google.com/appengine/docs/standard/python/issue-requests?csw=1#issuing_an_asynchronous_request:
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,您可以使用以下命令手动并行化请求线程 https://docs.python.org/2/library/threading.html#thread-objects and a 同步队列 https://docs.python.org/2/library/queue.html读取结果。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)