2016-09-20 31 views
0

我正在使用python Klein http://klein.readthedocs.io/en/latest/來設置Web服務。我已經檢查了文檔,但我仍然不知道如何設置服務的超時時間。任何熟悉工具的人都可以看到如何將超時設置爲15秒?謝謝!如何在python Klein中設置服務器超時?

+0

你想暫停什麼?會話,請求,....? –

+0

請求超時我相信?所以當服務器接收到一個呼叫,並且無法在固定的時間範圍(可能是10秒)內響應它時,它會將時間返回給客戶端。 – JLTChiu

+0

好的。你可以在下一次有'klien'問題時向標籤添加''twisted''嗎?這種扭曲的開發者也可以找到你的問題。 –

回答

1

您可以撥打Request.loseConnection()在設置的超時間隔後將請求連接刪除到客戶端。下面是一個簡單的例子:

from twisted.internet import reactor, task, defer 
from klein import Klein 

app = Klein() 
request_timeout = 10 # seconds 

@app.route('/delayed/<int:n>') 
@defer.inlineCallbacks 
def timeoutRequest(request, n): 
    work = serverTask(n)  # work that might take too long 

    drop = reactor.callLater(
     request_timeout, # drop request connection after n seconds 
     dropRequest,  # function to drop request connection 
      request,  # pass request obj into dropRequest() 
      work)   # pass worker deferred obj to dropRequest() 

    try: 
     result = yield work  # work has completed, get result 
     drop.cancel()   # cancel the task to drop the request connection 
    except: 
     result = 'Request dropped' 

    defer.returnValue(result) 

def serverTask(n): 
    """ 
    A simulation of a task that takes n number of seconds to complete. 
    """ 
    d = task.deferLater(reactor, n, lambda: 'delayed for %d seconds' % (n)) 
    return d 

def dropRequest(request, deferred): 
    """ 
    Drop the request connection and cancel any deferreds 
    """ 
    request.loseConnection() 
    deferred.cancel() 

app.run('localhost', 9000) 

要嘗試了這一點,去http://localhost:9000/delayed/2然後http://localhost:9000/delayed/20測試的方案時,任務未能按時完成。不要忘記取消與此請求相關的所有任務,延期,線程等,否則可能會浪費大量內存。

代碼說明

服務器端任務:客戶機轉到/delayed/<n>端點與指定的延遲值。服務器端任務(serverTask())啓動,爲簡單起見並模擬繁忙任務,deferLater用於在n秒後返回字符串。

請求超時:使用callLater功能,request_timeout間隔之後,調用dropRequest功能,並通過request和需要的所有工作deferreds被取消(在這種情況下,只有work)。當request_timeout通過後,請求連接將被關閉(request.loseConnection()),並且延期將被取消(deferred.cancel)。

收率服務器任務結果:在try/except塊,結果將被產生時的值是可用的,或者如果超時已通過並連接被刪除,會發生錯誤,並且Request dropped訊息會回。

替代

這確實似乎不是一個理想的情況下,應儘可能避免,但我可以看到需要這種功能。此外,儘管罕見,但請記住loseConnection並不總是完全關閉連接(這是由於TCP實現不是Twisted)。更好的解決方案是在客戶端斷開連接時取消服務器端任務(這可能會更容易被捕獲)。這可以通過將addErrback附加到Request.notifyFinish()來完成。這裏是一個使用Twisted的例子(http://twistedmatrix.com/documents/current/web/howto/web-in-60/interrupted.html)。

相關問題