我有一个Web服务(REST),其中一个请求可能需要30秒才能返回答案(大量计算)。存在风险,在计算期间,客户端webbrowser中止(?)现有连接和重试。这是服务器端的控制台输出:
Exception happened during processing of request from ('127.0.0.1', 53209)
Traceback (most recent call last):
File "C:\Users\tmx\Anaconda2\lib\SocketServer.py", line 290, in _handle_request_noblock
self.process_request(request, client_address)
File "C:\Users\tmx\Anaconda2\lib\SocketServer.py", line 318, in process_request
self.finish_request(request, client_address)
File "C:\Users\tmx\Anaconda2\lib\SocketServer.py", line 331, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "C:\Users\tmx\Anaconda2\lib\SocketServer.py", line 654, in __init__
self.finish()
File "C:\Users\tmx\Anaconda2\lib\SocketServer.py", line 713, in finish
self.wfile.close()
File "C:\Users\tmx\Anaconda2\lib\socket.py", line 283, in close
self.flush()
File "C:\Users\tmx\Anaconda2\lib\socket.py", line 307, in flush
self._sock.sendall(view[write_offset:write_offset+buffer_size])
error: [Errno 10053] An established connection was aborted by the software in your host machine
我想到的一个选项是以某种方式通知客户端“我还活着,但请求仍然需要更多时间”,或以某种方式设置服务器端的超时。有什么可能性?
答案 0 :(得分:0)
在您返回一些数据后,很难在Flask中运行代码。您可以选择使用类似任务队列(请参阅Celery),或者在多个部分中提供回复。
Flask中的视图可以返回字符串,但它们也可以返回包含字符串的迭代。因此,您可以返回"abc"
,["abc"]
或将生成"abc"
的生成器。如果您在收益之间进行处理,则在请求仍在运行时,数据将被发送到客户端。
看看下面的例子:
def generator_that_does_the_calculation():
sleep(1)
yield "I'm alive, but I need some time\n"
sleep(1)
yield "Still alive here\n"
sleep(1)
yield "Done\n"
@app.route('/calculate')
def calculate():
return Response(generator_that_does_the_calculation())