2016-09-20 34 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)。

相关问题