flask 框架 前端和后端请求超时问题

部署模式

flask + Gunicorn + nginx 

为什么要用Gunicorn + nginx ?

请看知乎大神们的回答:https://www.zhihu.com/question/38528616

场景

有一项业务,前端给后端发送ajax请求后,后端需要执行大约4分钟的时间才会给前端返回结果,而这时前端已经没有任何反应了.

原因

1. gunicorn超时

2.nginx proxy 超时

解决方法:

1.gunicorn需要配置超时时间,如果不配置,默认为30秒.

意思就是如果后端程序执行时间超过30秒没有结束, 就不会继续执行了,也不会返回值给前端,  后端也没有任何报错.

增加参数 timeout

from flask_script import Command, Option


class GunicornServer(Command):
    description = 'Run the app within Gunicorn'

    def __init__(self, host='127.0.0.1', port=5001, workers=50,
                 worker_class="sync", daemon=False):
        self.port = port
        self.host = host
        self.workers = workers
        self.worker_class = worker_class
        self.daemon = daemon

    def get_options(self):
        return (
            Option('-H', '--host',
                   dest='host',
                   default=self.host),

            Option('-p', '--port',
                   dest='port',
                   type=int,
                   default=self.port),

            Option('-w', '--workers',
                   dest='workers',
                   type=int,
                   default=self.workers),

            Option("-c", "--worker_class",
                   dest='worker_class',
                   type=str,
                   default=self.worker_class),

            Option("-d", "--daemon",
                   dest="daemon",
                   type=bool,
                   default=self.daemon)
        )

    def handle(self, app, host, port, workers, worker_class, daemon):

        from gunicorn import version_info

        timeout = 1800

        if version_info < (0, 9, 0):
            from gunicorn.arbiter import Arbiter
            from gunicorn.config import Config

            arbiter = Arbiter(Config({'bind': "%s:%d" % (host, int(port)),
                                      'workers': workers,
                                      'worker_class': worker_class,
                                      'daemon': daemon,
                                      'timeout': timeout}), app)
            arbiter.run()
        else:
            from gunicorn.app.base import Application

            class FlaskApplication(Application):
                def init(self, parser, opts, args):
                    return {
                        'bind': '{0}:{1}'.format(host, port),
                        'workers': workers,
                        'worker_class': worker_class,
                        'daemon': daemon,
                        'timeout': timeout
                    }

                def load(self):
                    return app

            FlaskApplication().run()

 

2.修改nginx proxy超时时间,如果不配置,默认60秒

proxy_read_timeout
语法 proxy_read_timeout time 
默认值 60s
上下文 http server location
说明 该指令设置与代理服务器的读超时时间。它决定了nginx会等待多长时间来获得请求的响应。这个时间不是获得整个response的时间,而是两次reading操作的时间。

proxy_send_timeout
语法 proxy_send_timeout time 
默认值 60s
上下文 http server location
说明 这个指定设置了发送请求给upstream服务器的超时时间。超时设置不是为了整个发送期间,而是在两次write操作期间。如果超时后,upstream没有收到新的数据,nginx会关闭连接

根据需要修改时间

[root@locolhost ~]# cat /etc/nginx/nginx.conf
# For more information on configuration, see:
#   * Official English Documentation: http://nginx.org/en/docs/
#   * Official Russian Documentation: http://nginx.org/ru/docs/

user              nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log;
#error_log  /var/log/nginx/error.log  notice;
#error_log  /var/log/nginx/error.log  info;

pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    proxy_buffer_size   128k;
    proxy_buffers   4 256k;
    proxy_busy_buffers_size   256k;
    proxy_read_timeout 1800;
    proxy_send_timeout 1800;
    fastcgi_read_timeout 1800;
    fastcgi_send_timeout 1800;

    #gzip  on;
    
    # Load config files from the /etc/nginx/conf.d directory
    # The default server is in conf.d/default.conf
    include /etc/nginx/conf.d/*.conf;

}

  

原文地址:https://www.cnblogs.com/terrycy/p/7097977.html