如何在GAE应用程序中执行异步api请求? [英] How to do async api requests in a GAE application?

查看:73
本文介绍了如何在GAE应用程序中执行异步api请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

为此,我尝试了asynciogrequestsrequestssimple-requests之类的库,它们似乎不起作用,因为它们与GAEpython 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,默认情况下它与GAE

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆