【问题标题】:Flask/http- tell the client that the request needs some more time to completeFlask/http - 告诉客户端请求需要更多时间才能完成
【发布时间】:2017-02-27 17:14:17
【问题描述】:

我有一个 Web 服务 (REST),其中一个请求可能需要 30 秒才能返回答案(大量计算)。存在风险,即在计算过程中,客户端 Web 浏览器会中止(?)现有连接并重试。这是服务器端的控制台输出:

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

我想到的一个选项是以某种方式通知客户端“我还活着,但请求仍需要更多时间”,或者以某种方式在服务器端设置超时。有哪些可能性?

【问题讨论】:

    标签: python rest http flask


    【解决方案1】:

    在您已经返回一些数据之后,很难在 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())
    

    【讨论】:

    • 嗯,听起来很合理。虽然我得到一个 TypeError: 'generator' object is not callable。有什么想法吗?
    • 尝试返回Response(generator_that_does_the_calculation())
    • 谢谢,这样就可以了。请更新您的原始答案:)
    猜你喜欢
    • 2020-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-19
    • 2019-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多