构建 Flask 应用通常包括定义路由、编写视图函数、处理表单、与数据库交互等步骤。以下是一个简单的 Flask 应用的示例,展示了这些基本概念。

1. 创建 Flask 应用

首先,确保你已经按照前面的说明设置了 Flask 环境。创建一个新的 Python 文件,比如 app.py,并在其中编写你的 Flask 应用:
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
    return 'Hello, World!'

if __name__ == '__main__':
    app.run(debug=True)

2. 添加路由和视图函数

在 Flask 中,路由通过装饰器 @app.route() 来定义。下面是一个更复杂的示例,包括两个路由和两个对应的视图函数:
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
    return 'Home Page'

@app.route('/about')
def about():
    return 'About Page'

if __name__ == '__main__':
    app.run(debug=True)

3. 使用模板渲染页面

Flask 集成了 Jinja2 模板引擎,使得在应用中生成动态内容变得非常容易。创建一个名为 templates 的文件夹,并在其中添加一个 HTML 模板,比如 index.html:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flask App</title>
</head>
<body>
    <h1>{{ title }}</h1>
    <p>Welcome to my Flask App!</p>
</body>
</html>

然后修改 Flask 应用中的视图函数,以使用这个模板:
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('index.html', title='Home Page')

@app.route('/about')
def about():
    return render_template('index.html', title='About Page')

if __name__ == '__main__':
    app.run(debug=True)

4. 表单处理

Flask 可以轻松处理表单提交。首先,确保你已经安装了 Flask-WTF(Web Forms for Flask):
pip install Flask-WTF

然后,创建一个表单,例如 forms.py:
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField

class MyForm(FlaskForm):
    name = StringField('Name')
    submit = SubmitField('Submit')

修改你的 Flask 应用文件,以使用这个表单:
from flask import Flask, render_template
from forms import MyForm

app = Flask(__name__)
app.config['SECRET_KEY'] = 'mysecretkey'

@app.route('/', methods=['GET', 'POST'])
def home():
    form = MyForm()
    if form.validate_on_submit():
        # 处理表单提交
        name = form.name.data
        return f'Hello, {name}!'
    return render_template('index.html', title='Home Page', form=form)

@app.route('/about')
def about():
    return render_template('index.html', title='About Page')

if __name__ == '__main__':
    app.run(debug=True)

5. 数据库交互

如果你的应用需要与数据库交互,可以使用 Flask-SQLAlchemy。首先,安装 Flask-SQLAlchemy:
pip install Flask-SQLAlchemy

然后,定义一个模型类并配置 SQLAlchemy:
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20), unique=True, nullable=False)

@app.route('/')
def home():
    users = User.query.all()
    return render_template('index.html', title='Home Page', users=users)

# 其他路由和视图函数

if __name__ == '__main__':
    app.run(debug=True)

这是一个简单的示例,展示了如何构建一个基本的 Flask 应用,包括路由、视图函数、模板、表单处理和数据库交互。根据你的项目需求,你可能会添加更多功能和复杂性。Flask 的文档是学习和参考的好资源,它提供了深入的教程和示例代码。


转载请注明出处:http://www.pingtaimeng.com/article/detail/7298/Flask