gpt4 book ai didi

python - 如何使用 WSGI 实现 Flask 应用按路径调度?

转载 作者:太空宇宙 更新时间:2023-11-03 13:41:06 24 4
gpt4 key购买 nike

我想使用一个域作为多个 flask 应用程序的暂存环境,这些应用程序最终将在它们自己的域上运行。

类似于:

  • example_staging.com/app1
  • example_staging.com/app2
  • example_staging.com/app3

哪里:

  • example_staging.com/app1 与 app1.example_staging.com 相同
  • example_staging.com/app2 与 app2.example_staging.com 相同
  • example_staging.com/app3 与 app3.example_staging.com 相同

或:

  • example_staging.com/app1 与 app1.com 相同
  • example_staging.com/app2 与 app2.com 相同
  • example_staging.com/app3 与 app3.com 相同

入门应用:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
return 'Hello from Flask!'

WSGI 入门配置文件:

import sys

project_home = u'/home/path/sample1'

if project_home not in sys.path:
sys.path = [project_home] + sys.path

from app import app as application

引用:

http://flask.pocoo.org/docs/0.10/patterns/appdispatch/

我不知道在哪里添加文档中给出的示例代码以及 create_app、default_app、get_user_for_prefix 应该是什么样子。

注意:使用 PythonAnywhere

解决方案

Glenns 输入后的 WSGI 配置文件:

import sys

# add your project directory to the sys.path
project_home = u'/home/path/app1'
if project_home not in sys.path:
sys.path = [project_home] + sys.path

from werkzeug.wsgi import DispatcherMiddleware
from app import app as app1
from app2.app import app as app2
from app3.app import app as app3

application = DispatcherMiddleware(app1, {
'/app2': app2,
'/app3': app3
})

文件夹结构:

app1 folder
app2 folder
app3 folder

最佳答案

这对我有用:

文件夹结构

DISPATCHER (folder)
dispatcher.py

app1 (folder)
__init__.py

app2 (folder)
__init__.py

app3 (folder)
__init__.py

dispatcher.py

from flask import Flask
from werkzeug.wsgi import DispatcherMiddleware #use the commented version below for Werkzeug >= v.1.0
#from werkzeug.middleware.dispatcher import DispatcherMiddleware
from werkzeug.exceptions import NotFound

from app1 import app as app1
from app2 import app as app2
from app3 import app as app3

app = Flask(__name__)

app.wsgi_app = DispatcherMiddleware(NotFound(), {
"/app1": app1,
'/app2': app2,
'/app3': app3
})

if __name__ == "__main__":
app.run()

app1 到 app3 init.py

from flask import Flask

app = Flask(__name__)

@app.route("/")
def index_one():
return "Hi im 1 or 2 or 3"

if __name__ == "__main__":
app.run()

工作

python dispatcher.py

localhost:5000/app1 "Hi im one"
localhost:5000/app2 "Hi im two"
localhost:5000/app3 "Hi im three"

另一种配置

您可以导入另一个应用程序,例如 app0 并向应用程序添加菜单,使用 NotFound() 更改此设置

这有帮助

Application Dispatching

关于python - 如何使用 WSGI 实现 Flask 应用按路径调度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30906489/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com