首页 > 解决方案 > Multiple Flask Application in single uwsgi

问题描述

I have a flask application with uwsgi configuration. This flask process requests such as addition, subtraction and multiplication. Now in my project structure i have a single app and this app is called in uwsgi config. But now i need to have separate flask application for each operation i.e flask1 for processing addition and flask2 for processing subtraction and so on. I am totally a beginner and have no idea how to achieve this through uwsgi.

I have heard about uwsgi emperor mode but doesn' have idea on it

My app file :

from myapp import app

if __name__ == __main__:
  app.run()

wsgi config

module = wsgi:app

标签: python-3.xnginxflaskuwsgi

解决方案


您可以使用 Werkzeug 的Dispatcher Middleware来做到这一点。

使用这样的示例应用程序:

# application.py

from flask import Flask

def create_app_root():
    app = Flask(__name__)
    @app.route('/')
    def index():
        return 'I am the root app'
    return app

def create_app_1():
    app = Flask(__name__)
    @app.route('/')
    def index():
        return 'I am app 1'
    return app

def create_app_2():
    app = Flask(__name__)
    @app.route('/')
    def index():
        return 'I am app 2'
    return app

from werkzeug.middleware.dispatcher import DispatcherMiddleware

dispatcher_app = DispatcherMiddleware(create_app_root(), {
    '/1': create_app_1(),
    '/2': create_app_2(),
})

然后你可以用 gunicorn 运行它:

gunicorn --bind 0.0.0.0:5000 application:dispatcher_app

并用 curl 测试:

$ curl -L http://localhost:5000/
I am the root app%

$ curl -L http://localhost:5000/1
I am app 1%

$ curl -L http://localhost:5000/2
I am app 2%                    

这似乎通过发出重定向来起作用,这就是-L此处标志的原因。


推荐阅读