【问题标题】:How to pass url arguments to Flask behind Nginx proxy_pass with unix socket如何使用unix套接字将url参数传递给Nginx proxy_pass后面的Flask
【发布时间】:2023-03-18 14:45:01
【问题描述】:

我有一个使用 bjoern 作为 python 服务器的 Flask 应用程序。我有一个示例网址是这样的:

http://example.com/store/junihh
http://example.com/store/junihh/product-name

“junihh”和“product-name”是我需要传递给 python 的参数。

在阅读了有关 TCP/IP 调用的性能后,我尝试使用 unix 套接字。但现在我在浏览器上收到 502 错误。

这是我的 conf 的 sn-p:

upstream backend {
    # server localhost:1234;
    # server unix:/run/app_stores.sock weight=10 max_fails=3 fail_timeout=30s;
    server unix:/run/app_stores.sock;
}

server {
    listen                      80 default_server;
    listen                      [::]:80 default_server;
    server_name                 example.com www.example.com; 
    root                        /path/to/my/public;

    location ~ ^/store/(.*)$ {
        include                 /etc/nginx/conf.d/jh-proxy-pass.conf;
        include                 /etc/nginx/conf.d/jh-custom-headers.conf;

        proxy_pass              http://backend/$1;
    }
}

如何通过 Nginx proxy_pass 和 unix socket 将 url 参数传递给 Flask?

感谢您的帮助。

【问题讨论】:

    标签: python nginx flask unix-socket


    【解决方案1】:

    这是我的 conf,它可以工作。 502是因为找不到到上游服务器的路由(即将http://127.0.0.1:5000/$1改为http://localhost:5000/$1)会导致502。

    nginx.conf

    http {
        server {
            listen       80; 
            server_name  localhost;
    
            location ~ ^/store/(.*)$ {
                proxy_pass http://127.0.0.1:5000/$1;
            }   
        }   
    }
    

    烧瓶 app.py

    #!/usr/bin/env python3
    
    from flask import Flask
    
    app = Flask(__name__)
    
    @app.route('/')
    def world():
        return 'world'
    
    @app.route('/<name>/<pro>')
    def shop(name, pro):
        return 'name: ' + name + ', prod: ' + pro
    
    if __name__ == '__main__':
        app.run(debug=True)
    

    更新

    或者你可以像这样使用 unix socket,但是在 uwsgi 上中继。

    nginx.conf

    http {
        server {
            listen       80; 
    
            location /store {
                rewrite /store/(.+) $1 break;
                include uwsgi_params;
                uwsgi_pass unix:/tmp/store.sock;
            }   
        }   
    }
    

    烧瓶 app.py

    如上,不变

    uwsgi 配置

    [uwsgi]
    module=app:app
    plugins=python3
    master=true
    processes=1
    socket=/tmp/store.sock
    
    uid=nobody
    gid=nobody
    
    vaccum=true
    die-on-term=true
    

    另存为config.ini,然后运行uwsgi config.ini

    nginx重新加载后,你可以访问你的页面;-)

    【讨论】:

    • 我更喜欢像以前一样使用 TCP / IP 编写代码,与您的示例非常相似。毕竟,在使用 unix 套接字“调情”之前,它对我有用。
    猜你喜欢
    • 1970-01-01
    • 2020-10-20
    • 1970-01-01
    • 1970-01-01
    • 2012-11-11
    • 2021-11-16
    • 2017-05-05
    • 1970-01-01
    • 2014-04-05
    相关资源
    最近更新 更多