创建工作目录flask_demo,添加__init__.py 文件(也可以用别的文件名)。
flask_demo/__init__.py
from flask import Flask
def create_app(test_config=None):
# create and configure the app
app = Flask(__name__, instance_relative_config=True)
app.config.from_mapping(
SECRET_KEY='dev',
DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),
)
if test_config is None:
# load the instance config, if it exists, when not testing
app.config.from_pyfile('config.py', silent=True)
else:
# load the test config if passed in
app.config.from_mapping(test_config)
# a simple page that says hello
@app.route('/hello')
def hello():
return 'Hello, World!'
return app
在Linux上运行:
$ export FLASK_APP=flask_demo
$ export FLASK_ENV=development
$ flask run 或者 flask run --host 0.0.0.0
在浏览器中访问 http://127.0.0.1:5000/hello
后续如果有需要,可以添加支持MongoDB数据库、用MVC 方式扩展服务。比如:
flask_demo/ # V 可以用html或者其他前端框架代替,比如vue
__init__.py # 定义了create_app(),入口
api/ # C, 定义了一些M的行为
users.py
builds.py
models/ # M, 数据模型
users.py
builds.py
config.py # 定义了一些配置,比如MongoDB数据库的配置
auth.py
db.py
Flask 官方文档: https://flask.palletsprojects.com/en/1.1.x/tutorial/factory/