您已经声明了Flask 的两个实例,一个在__init__.py 中,另一个在run.py 中。
Flask官方文档在how to breakdown a larger application in multiple modules上有教程。
我已更新您的代码、文件名和文件夹结构。
文件夹结构:
├── application
│ ├── __init__.py
│ └── views.py
├── requirements.txt
└── run_application.py
run_application.py:
from flask import Flask
from gevent.pywsgi import WSGIServer
from application import app
http_server = WSGIServer(('', 5000), app)
http_server.serve_forever()
application/__init__.py:
from flask import Flask
app = Flask(__name__)
import application.views
application/views.py:
from application import app
@app.route('/')
def index():
return 'Home route.'
@app.route('/hello')
def hello():
return 'Hello World!'
requirements.txt:
Click==7.0
Flask==1.0.2
gevent==1.4.0
greenlet==0.4.15
itsdangerous==1.1.0
Jinja2==2.10.1
MarkupSafe==1.1.1
Werkzeug==0.15.2
运行命令:
python run_application.py
输出:
- 回家路线
http://localhost:5000/
- 你好路由
http://localhost:5000/hello
更新
根据Flask documentation on Blueprints,
Flask 使用蓝图的概念来制作应用程序组件
并支持应用程序内或跨应用程序的常见模式
应用程序。
更新代码方便blueprints。
更新的目录结构:
├── application1
│ ├── __init__.py
│ └── routes.py
├── application2
│ ├── __init__.py
│ └── routes.py
├── apps.py
└── requirements.txt
apps.py:
from flask import Flask
from gevent.pywsgi import WSGIServer
from application1.routes import application1_blueprint
from application2.routes import application2_blueprint
app = Flask(__name__)
app.register_blueprint(application1_blueprint)
app.register_blueprint(application2_blueprint)
http_server = WSGIServer(('', 5000), app)
http_server.serve_forever()
application1/__init__.py: 空白文件
application1/routes.py:
from flask import Blueprint
application1_blueprint = Blueprint('application1', __name__)
@application1_blueprint.route('/app1')
def application1_index():
return 'Home route for application1'
@application1_blueprint.route('/hello1')
def hello1():
return 'Hello World from application1!'
application2/__init__.py: 空白文件
application2/routes.py:
from flask import Blueprint
application2_blueprint = Blueprint('application2', __name__)
@application2_blueprint.route('/app2')
def application2_index():
return 'Home route for application2'
@application2_blueprint.route('/hello2')
def hello2():
return 'Hello World from application2!'
输出:
/app1 路由来自application1:
/app2 路由来自application2: