Flask 是一个轻量级的 Python Web 框架,非常适合快速开发小型到中型 Web 应用程序。以下是一个简单的 Flask 入门教程,帮助你快速上手。
首先,你需要安装 Flask。你可以使用 pip
来安装:
pip install Flask
创建一个新的 Python 文件,例如 app.py
,并在其中编写以下代码:
from flask import Flask
# 创建一个 Flask 应用实例
app = Flask(__name__)
# 定义一个路由和视图函数
@app.route('/')
def home():
return "Hello, Flask!"
# 运行应用
if __name__ == '__main__':
app.run(debug=True)
在终端中运行你的 Flask 应用:
python app.py
你应该会看到类似以下的输出:
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 123-456-789
打开浏览器并访问 http://127.0.0.1:5000/
,你应该会看到页面上显示 “Hello, Flask!”。
你可以通过添加更多的路由来扩展你的应用。例如:
@app.route('/about')
def about():
return "This is the about page."
访问 http://127.0.0.1:5000/about
,你会看到 “This is the about page.”。
Flask 支持使用 Jinja2 模板引擎来渲染 HTML 页面。首先,创建一个 templates
文件夹,并在其中创建一个 index.html
文件:
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hometitle>
head>
<body>
<h1>{{ message }}h1>
body>
html>
然后,修改 app.py
中的 home
视图函数:
from flask import render_template
@app.route('/')
def home():
return render_template('index.html', message="Hello, Flask with Templates!")
现在,访问 http://127.0.0.1:5000/
,你会看到渲染后的 HTML 页面。
Flask 可以轻松处理表单数据。首先,创建一个简单的表单页面 form.html
:
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Formtitle>
head>
<body>
<form action="/submit" method="post">
<label for="name">Name:label>
<input type="text" id="name" name="name">
<button type="submit">Submitbutton>
form>
body>
html>
然后,在 app.py
中添加处理表单的路由:
from flask import request, redirect, url_for
@app.route('/form')
def form():
return render_template('form.html')
@app.route('/submit', methods=['POST'])
def submit():
name = request.form['name']
return f"Hello, {name}!"
访问 http://127.0.0.1:5000/form
,填写表单并提交,你会看到提交后的结果。
Flask 允许你使用静态文件(如 CSS、JavaScript 和图片)。创建一个 static
文件夹,并在其中放置你的静态文件。例如,创建一个 style.css
文件:
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
}
然后在 index.html
中引用它:
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
当你准备好将应用部署到生产环境时,可以使用 gunicorn
或 uWSGI
等 WSGI 服务器。例如,使用 gunicorn
:
pip install gunicorn
gunicorn -w 4 app:app
这将启动一个生产环境的服务器,监听在 http://127.0.0.1:8000/
。
Flask 是一个非常灵活的框架,支持许多扩展和功能。你可以进一步学习以下内容:
希望这个入门教程能帮助你快速上手 Flask 编程!如果有任何问题,欢迎随时提问。