如何在GAE应用程序中执行异步api请求?

时间:2018-12-11 07:03:38

标签: python python-2.7 google-app-engine google-cloud-platform python-requests

我正在开发一个基于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.*

为此,我尝试了asynciogrequestsrequestssimple-requests之类的库,它们似乎不起作用,因为它们都不兼容与GAEpython 2.7.13一起使用。 有人可以帮我吗?

1 个答案:

答案 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,则可以使用threadingsynchronized Queue来读取结果来手动并行化请求。

相关问题