使用Google App Engine进行异步提取请求

时间:2012-06-19 19:16:48

标签: python google-app-engine

我正在阅读GAE中asynchronous fetch requests的文档。 Python不是我的第一语言,所以我很难找到最适合我的情况。我真的不需要或不关心请求的响应,我只需要它发送请求并忘记它并继续执行其他任务。

所以我尝试了文档中的代码:

from google.appengine.api import urlfetch

rpc = urlfetch.create_rpc()
urlfetch.make_fetch_call(rpc, "http://www.google.com/")

# ... do other things ...

try:
    result = rpc.get_result()
    if result.status_code == 200:
        text = result.content
        # ...
except urlfetch.DownloadError:
    # Request timed out or failed.
    # ...

但是除非我包含try:except,否则此代码无法使用,我真的不在乎。省略该部分会使请求无法通过。

创建获取请求的最佳选择是什么,我不关心响应,因此它只是开始请求,然后转移到其他任何任务,并且永远不会回头?

2 个答案:

答案 0 :(得分:4)

只需在

处执行任务即可
# ... do other things ...

评论是。完成后,请致电rpc.wait()。请注意,try/except不是get_result(),而是wait()调用。这可以替换为from google.appengine.api import urlfetch rpc = urlfetch.create_rpc() urlfetch.make_fetch_call(rpc, "http://www.google.com/") # ... do other things ... << YOUR CODE HERE rpc.wait()

所以你的代码看起来像这样:

{{1}}

答案 1 :(得分:4)

如果您不关心响应,响应可能需要一段时间,并且您不希望处理程序在将响应返回给用户之前等待它完成,您可能需要考虑启动task queue任务发出请求而不是在面向用户的处理程序中执行。