如何使用WSGI通过Path实现Flask应用程序调度?

时间:2015-06-18 04:31:03

标签: python path flask wsgi dispatch

我想将单个域用作多个烧瓶应用程序的临时环境,这些应用程序最终将在自己的域上运行。

类似的东西:

  • 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 Starter配置文件:

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

2 个答案:

答案 0 :(得分:5)

这里要注意的关键是,您实际上有4个应用程序(3个应用程序和1个组合应用程序)。这忽略了暂存/现场区别,因为暂存和实时只是不同目录中彼此的副本。

创建每个单独的应用并让他们在各个域上做出响应。然后创建一个新应用,从单个应用中导入application变量,并使用DispatcherMiddleware组合它们,例如标题" Combining Applications"在您链接到的文档页面上。

答案 1 :(得分:1)

这对我有用:

文件夹结构

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
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 app.py

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

另一种配置

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

这有帮助

Application Dispatching