前言:
我的笔记持续在notion更新,欢迎观看交流,求star~
https://www.notion.so/FLASK-STUDY-NOTE-897db25a787a4f85a05034a54a7925d3
项目基础布局
flaskr/
,一个包含应用代码和文件的 Python 包。tests/
,一个包含测试模块的文件夹。venv/
,一个 Python 虚拟环境,用于安装 Flask 和其他依赖的包。- 告诉 Python 如何安装项目的安装文件。
- 版本控制配置,如 git 。不管项目大小,应当养成使用版本控制的习惯。
- 项目需要的其他文件。
最后得到的布局:
/home/user/Projects/flask-tutorial
├── flaskr/
│ ├── __init__.py
│ ├── db.py
│ ├── schema.sql
│ ├── auth.py
│ ├── blog.py
│ ├── templates/
│ │ ├── base.html
│ │ ├── auth/
│ │ │ ├── login.html
│ │ │ └── register.html
│ │ └── blog/
│ │ ├── create.html
│ │ ├── index.html
│ │ └── update.html
│ └── static/
│ └── style.css
├── tests/
│ ├── conftest.py
│ ├── data.sql
│ ├── test_factory.py
│ ├── test_db.py
│ ├── test_auth.py
│ └── test_blog.py
├── venv/
├── setup.py
└── MANIFEST.in
应用设置
-
在主文件夹内创建
flaskr
文件夹并且文件夹内添加__init__.py
文件。__init__.py
有两个作用:一是包含应用工厂;二是 告诉 Python
flaskr
文件夹应当视作为一个包。 -
在
__init__.py
中添加相应的代码之后,在cmd键入:
set FLASK_APP=flaskr
set FLASK_ENV=development
flask run
- 此时就可以看到 “Hello, World!” 信息。恭喜你, Flask 网络应用成功运行了!
import os
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)
# ensure the instance folder exists
try:
os.makedirs(app.instance_path)
except OSError:
pass
# a simple page that says hello
@app.route('/hello')
def hello():
return 'Hello, World!'
return app
一个hello world示例。