Flask 是一个轻量级的 Web 应用框架,它使用 Python 语言编写。本教程将带你了解 Flask 的基本用法和高级特性。

安装 Flask

首先,你需要安装 Flask。你可以使用 pip 来安装:

pip install flask

创建一个简单的 Flask 应用

以下是一个简单的 Flask 应用示例:

from flask import Flask

app = Flask(__name__)

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

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

运行上述代码后,访问 http://127.0.0.1:5000/,你将看到 "Hello, World!"。

路由和视图函数

Flask 使用路由和视图函数来处理请求。下面是一个包含两个路由的示例:

@app.route('/')
def index():
    return 'Welcome to the homepage!'

@app.route('/hello/<name>')
def hello(name):
    return f'Hello, {name}!'

你可以通过访问 http://127.0.0.1:5000/hello/YourName 来测试这个路由。

使用模板

Flask 使用 Jinja2 作为模板引擎。以下是一个简单的模板示例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{ title }}</title>
</head>
<body>
    <h1>{{ message }}</h1>
</body>
</html>

你可以将这个模板保存为 templates/index.html,并在视图函数中渲染它:

from flask import render_template

@app.route('/')
def index():
    return render_template('index.html', title='Welcome', message='Welcome to the homepage!')

扩展阅读

想要了解更多 Flask 的信息,请访问我们的官方文档:Flask 官方文档

Flask Logo