python-3.x - 带有 gaiohttp 工作线程的 Gunicorn 总是使用 Flask 应用程序返回 404

标签 python-3.x nginx flask gunicorn aiohttp

我正在 nginx 代理后面使用 Gunicorn 运行 Flask 应用程序,并试图让 gaiohttp 工作线程正常工作。当选择 gaiohttp 工作线程时,应用程序只会为所有 URL 返回 404

当使用同步或 gevent 工作人员时,一切正常。也不直接运行到gunicorn和gaiohttp,即不使用nginx,它工作得很好。

我已经阅读了我能找到的所有内容。

我错过了什么吗? gaiohttp 工作线程在 nginx 代理后面运行时有效吗?

我的 nginx 配置:

location /app {
    proxy_pass http://127.0.0.1:9002;
    rewrite    /app(.*) /$1  break;
    proxy_redirect     off;
    proxy_buffering on;
    proxy_pass_header Server;
    proxy_set_header X-Scheme $scheme;
    proxy_set_header   Host             $host;
    proxy_set_header   X-Real-IP        $remote_addr;
    proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
    proxy_set_header   X-Forwarded-Host $server_name;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Script-Name /app;
    }

unicorn :

/usr/bin/gunicorn --workers 2 -k gaiohttp -b 127.0.0.1:9002 app:app

使用最新版本的gunicorn等

最佳答案

我设法解决了这个问题。

此处的行导致了 nginx 配置中的问题:

重写/app(.*)/$1 中断;

我的 Flask 应用程序中需要一个代理中间件来正确处理反向代理。

class ReverseProxied(object):
'''Wrap the application in this middleware and configure the
front-end server to add these headers, to let you quietly bind
this to a URL other than / and to an HTTP scheme that is
different than what is used locally.

In nginx:
location /myprefix {
    proxy_pass http://192.168.0.1:5001;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Scheme $scheme;
    proxy_set_header X-Script-Name /myprefix;
    }

:param app: the WSGI application
'''
def __init__(self, app):
    self.app = app

def __call__(self, environ, start_response):
    script_name = environ.get('HTTP_X_SCRIPT_NAME', '')
    if script_name:
        server = environ.get('HTTP_X_FORWARDED_SERVER', '')
        if server:
            environ['HTTP_HOST'] = server
        environ['SCRIPT_NAME'] = script_name
        path_info = environ['PATH_INFO']
        if path_info.startswith(script_name):
            environ['PATH_INFO'] = path_info[len(script_name):]

    scheme = environ.get('HTTP_X_SCHEME', '')
    if scheme:
        environ['wsgi.url_scheme'] = scheme
    return self.app(environ, start_response)

在应用程序的__init__.py中:app.wsgi_app = ReverseProxied(app.wsgi_app)

关于python-3.x - 带有 gaiohttp 工作线程的 Gunicorn 总是使用 Flask 应用程序返回 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36258506/

相关文章:

python - PyQt5 keyPressEvent 的工作原理

python - 将 TextInput 绑定(bind)到 .kv 文件中的标签

python - 使用电子邮件模块(PYTHON)解析来自 poplib 的电子邮件内容

python - Flask SQLAlchemy 关系

python - 如何更新odoo中所有产品的字段中的不同记录?

html - NGINX删除.html扩展名

nginx - 将 Nginx 修补到 ip_hash 4 个八位字节而不是 3 个

ruby-on-rails - Phusion乘客 :Why passenger still kills rails process after set passenger_min_instances = 1?

python - Docker - 无法获取用户网络摄像头 : getUserMedia() no longer works on insecure origins

python - Flask 工厂模式和 Flask CLI 命令