一个最小的应用
from flask import Flask #导入了 Flask 类。该类的实例将会成为我们的 WSGI 应用
app = Flask(__name__) #__name__ 是一个适用于大多数情况的快捷方式。有了这个参数, Flask 才能知道在哪里可以找到模板和静态文件等东西
@app.route("/") # route() 装饰器来告诉 Flask 触发函数 的 URL
def hello_world():
return "<p>Hello, World!</p>"
把它保存为 hello.py ,如何用flask命令运行改文件
linux:
export FLASK_APP=hello
flask run
windows:
set FLASK_APP=hello
flask run
Flask类
import_name ( str ) – 应用程序包的名称
static_url_path (可选[ str ] ) – 可用于为网络上的静态文件指定不同的路径。默认为static_folder文件夹的名称。
static_folder (可选[ Union [ str , os.PathLike ] ] ) – 提供静态文件的文件夹 static_url_path。相对于应用程序root_path 或绝对路径。默认为'static'.
static_host (可选[ str ] ) – 添加静态路由时要使用的主机。默认为无。host_matching=True 与配置一起使用时static_folder需要。
host_matching ( bool ) – 设置url_map.host_matching属性。默认为假。
subdomain_matching ( bool ) – SERVER_NAME在匹配路由时考虑相对于子域。默认为假。
template_folder (可选[ str ] ) – 包含应用程序应使用的模板的文件夹。默认为 'templates'应用程序根路径中的文件夹。
instance_path ( Optional [ str ] ) -- 应用程序的替代实例路径。默认情况'instance'下,包或模块旁边的文件夹被假定为实例路径。
instance_relative_config ( bool ) – 如果设置True为加载配置的相对文件名,则假定是相对于实例路径而不是应用程序根目录。
root_path (可选[ str ] ) – 应用程序文件根目录的路径。这应该仅在无法自动检测到时手动设置,例如命名空间包。
工厂函数
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
Blueprint(蓝图)
该功能实现对不同模块分别建立自己的文件路径
新建一个蓝图flaskr/auth.py
bp = Blueprint('auth', __name__, url_prefix='/auth')
#和应用对象一样, 蓝图需要知道是在哪里定义的,因此把 __name__ 作为函数的第二个参数。 url_prefix 会添加到所有与该蓝图关联的 URL 前面
蓝图通过app.register_blueprint()方法注册
def create_app():
app = ...
# existing code omitted
from . import auth
app.register_blueprint(auth.bp)
return app
注册后可编写对应蓝图的逻辑并返回响应页面
@bp.route('/register', methods=('GET', 'POST'))
#@bp.route关联了 URL /register 和 register 视图函数。当 Flask 收到一个指向 /auth/register 的请求时就会调用 register 视图并把其返回值作为响应。
def register():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
db = get_db()
error = None
if not username:
error = 'Username is required.'
elif not password:
error = 'Password is required.'
if error is None:
try:
db.execute(
"INSERT INTO user (username, password) VALUES (?, ?)",
(username, generate_password_hash(password)),
)
db.commit()
except db.IntegrityError:
error = f"User {username} is already registered."
else:
return redirect(url_for("auth.login"))
flash(error)
return render_template('auth/register.html')