2017-03-28 29 views
0

我使用的URLFetch從谷歌AppEngine上,我添加了最後期限參數,以強制期限要短(3秒),如下所示:AppEngine上的網址抓取,如何強制超時被尊重

try: 
    urlfetch.set_default_fetch_deadline(3) 
    return urlfetch.fetch(url='http://www.example.com', method=urlfetch.GET, deadline=3) 
except google.appengine.runtime.apiproxy_errors.DeadlineExceededError: 
    pass 
except google.appengine.api.urlfetch_errors.DeadlineExceededError: 
    pass 

return None 

但無論如何,我的線程持續60秒(Appengine上的http請求的最大執行時間),然後在DeadlineException(「線程在請求​​後運行」)失敗。

有沒有辦法確保上面的查詢將在3秒內嚴格停止?

+0

你確定這個異常不是真的引發,而是被你的代碼捕獲和忽略嗎?也許嘗試用'logging'調用替換'pass'語句來檢查? –

+0

我相信'set_default_fetch_deadline()'是用於使用'rpc'和'urlfetch.make_fetch_call()'的。你的'urlfetch.fetch(... deadline = 3)'應該就足夠了。嘗試添加一個通用的'except:'並且在裏面以及另一個'excepts'裏登錄。 – GAEfan

+0

沒有明顯的截止日期參數已經被完全移除,現在需要使用'set_default_fetch_deadline'。請參閱文檔:https://cloud.google.com/appengine/docs/standard/python/issue-requests?csw=1 –

回答

1

我可以分享我目前在我的一個生產項目中運行的一些代碼。在這個例子中,我使用了0.5秒的截止日期。上次我檢查,它仍然工作:

t_rpc = urlfetch.create_rpc(deadline=0.5) 
urlfetch.make_fetch_call(t_rpc, url) 
# and then later... 
try: 
    result = t_rpc.get_result() 
except: 
    # handle errors... 
    pass 

# use the result... 

這實際上是使用API​​的異步版本,因此您可以在技術上在呼喚make_fetch_callget_result之間做的事情。否則,你可以連續調用它們,它的功能與同步API相同。

+0

謝謝你的代碼,我會試試看。我打算使用異步方法調用urls,我不介意得到結果。如果我從來沒有調用'rpc.get_result()',你認爲沒關係嗎?或者這會導致一些內存泄漏? –

+0

你的代碼工作得很好,我的原代碼也是。問題出在Sentry,一種跟蹤錯誤的服務,這是造成這個問題的原因! –