It seems I am encountering an unexpected issue where the write_file tool is not being recognized, despite being listed as available. This is preventing me from directly creating the markdown file.
To fulfill your request of writing an article titled “Python Flask Web Development Quick Guide”, I will provide the full content of the article here in markdown format. You can then copy and save it as a .md file if you wish.
Python Flask Web Development 快速指南
Flask 是一个轻量级的 Python Web 框架,以其简洁、灵活和易于上手而闻名。它被称为“微框架”,因为它不强制使用特定的工具或库,允许开发者根据项目需求自由选择。本指南将带你快速入门 Flask Web 开发。
1. 为什么选择 Flask?
- 轻量级和模块化: Flask 核心精简,易于理解和扩展。
- 灵活性: 不像 Django 那样提供“大而全”的解决方案,Flask 允许你自由选择数据库、模板引擎等组件。
- 易于上手: 对于初学者来说,Flask 的概念和 API 都比较简单,学习曲线平缓。
- 强大的社区和扩展: 拥有活跃的社区和丰富的第三方扩展,可以轻松添加各种功能。
2. 环境设置
在开始之前,强烈建议为每个项目创建一个独立的 Python 虚拟环境,以避免包冲突。
-
创建并激活虚拟环境:
“`bash
python -m venv venvWindows
.\venv\Scripts\activate
macOS/Linux
source venv/bin/activate
“` -
安装 Flask:
bash
pip install Flask
3. 第一个 Flask 应用 (Hello World)
创建一个名为 app.py 的文件,并添加以下代码:
“`python
from flask import Flask
创建 Flask 应用实例
app = Flask(name)
定义路由和视图函数
@app.route(‘/’)
def hello_world():
return ‘Hello, World!’
运行应用
if name == ‘main‘:
app.run(debug=True)
“`
运行应用:
在终端中,确保虚拟环境已激活,然后运行:
bash
python app.py
你会在终端看到类似 Running on http://127.0.0.1:5000/ 的输出。在浏览器中访问 http://127.0.0.1:5000/,你将看到 “Hello, World!”。
debug=True 会在代码修改后自动重新加载应用,并在出现错误时提供详细的调试信息。但在生产环境中,应将其设置为 False。
4. 路由 (Routing)
路由是将 URL 映射到 Python 函数的过程。Flask 使用 @app.route() 装饰器来定义路由。
带变量的路由:
你可以定义带有变量的路由,变量会作为参数传递给视图函数。
“`python
from flask import Flask
app = Flask(name)
@app.route(‘/user/
def show_user_profile(username):
# show the user profile for that user
return f’User: {username}’
@app.route(‘/post/
def show_post(post_id):
# show the post with the given id, the id is an integer
return f’Post ID: {post_id}’
if name == ‘main‘:
app.run(debug=True)
“`
访问 http://127.0.0.1:5000/user/alice 将显示 “User: alice”,访问 http://127.0.0.1:5000/post/123 将显示 “Post ID: 123″。
5. 模板 (Templates)
对于更复杂的 HTML 页面,我们使用模板。Flask 默认使用 Jinja2 模板引擎。模板文件通常存放在项目根目录下的 templates 文件夹中。
-
创建
templates文件夹:.
├── app.py
└── templates/
└── index.html -
templates/index.html内容:html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ title }}</title>
</head>
<body>
<h1>Hello, {{ name }}!</h1>
<p>This is a Flask template example.</p>
</body>
</html> -
修改
app.py:“`python
from flask import Flask, render_templateapp = Flask(name)
@app.route(‘/’)
def index():
return render_template(‘index.html’, title=’Home Page’, name=’World’)@app.route(‘/greet/
‘)
def greet(name):
return render_template(‘index.html’, title=f’Hello {name}’, name=name)if name == ‘main‘:
app.run(debug=True)
“`
访问 http://127.0.0.1:5000/ 将显示 “Hello, World!”,访问 http://127.0.0.1:5000/greet/Alice 将显示 “Hello, Alice!”。
6. 静态文件 (Static Files)
CSS、JavaScript 和图片等静态文件通常放在项目根目录下的 static 文件夹中。
-
创建
static文件夹:.
├── app.py
├── static/
│ └── style.css
└── templates/
└── index.html -
static/style.css内容:css
body {
font-family: sans-serif;
background-color: #f4f4f4;
color: #333;
margin: 20px;
}
h1 {
color: #0056b3;
} -
修改
templates/index.html以引用 CSS:html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ title }}</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
<h1>Hello, {{ name }}!</h1>
<p>This is a Flask template example with static files.</p>
</body>
</html>
url_for('static', filename='style.css') 是 Flask 提供的函数,用于生成静态文件的 URL。
7. 请求和表单 (Requests and Forms)
Flask 可以轻松处理 HTTP 请求数据,例如表单提交。
“`python
from flask import Flask, render_template, request, redirect, url_for
app = Flask(name)
@app.route(‘/login’, methods=[‘GET’, ‘POST’])
def login():
if request.method == ‘POST’:
username = request.form[‘username’]
password = request.form[‘password’]
# 这里可以添加用户认证逻辑
if username == ‘admin’ and password == ‘password’:
return redirect(url_for(‘dashboard’, user=username))
else:
return ‘Invalid Credentials’
return render_template(‘login.html’)
@app.route(‘/dashboard/
def dashboard(user):
return f’Welcome to the dashboard, {user}!’
if name == ‘main‘:
app.run(debug=True)
“`
templates/login.html 内容:
“`html
Login
“`
访问 http://127.0.0.1:5000/login,你可以尝试提交表单。request.form 用于访问表单数据。redirect() 和 url_for() 用于重定向到其他路由。
8. 数据库集成 (Database Integration – 示例 SQLAlchemy)
Flask 本身不提供数据库抽象层,但可以轻松与 SQLAlchemy 等 ORM(对象关系映射)库集成。这里我们以 SQLite 为例,结合 Flask-SQLAlchemy 扩展。
-
安装 Flask-SQLAlchemy:
bash
pip install Flask-SQLAlchemy -
修改
app.py:“`python
from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemyapp = Flask(name)
app.config[‘SQLALCHEMY_DATABASE_URI’] = ‘sqlite:///site.db’ # 使用 SQLite 数据库
app.config[‘SQLALCHEMY_TRACK_MODIFICATIONS’] = False # 禁用跟踪对象修改的信号
db = SQLAlchemy(app)定义模型 (Table)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)def __repr__(self): return f'<User {self.username}>'在应用上下文外部创建数据库表 (运行一次即可)
with app.app_context():
db.create_all()@app.route(‘/add_user’, methods=[‘GET’, ‘POST’])
def add_user():
if request.method == ‘POST’:
username = request.form[‘username’]
email = request.form[’email’]
new_user = User(username=username, email=email)
db.session.add(new_user)
db.session.commit()
return redirect(url_for(‘list_users’))
return render_template(‘add_user.html’)@app.route(‘/users’)
def list_users():
users = User.query.all()
return render_template(‘users.html’, users=users)if name == ‘main‘:
app.run(debug=True)
“` -
templates/add_user.html内容:html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Add User</title>
</head>
<body>
<h1>Add New User</h1>
<form method="POST">
<label for="username">Username:</label><br>
<input type="text" id="username" name="username" required><br>
<label for="email">Email:</label><br>
<input type="email" id="email" name="email" required><br><br>
<input type="submit" value="Add User">
</form>
<p><a href="{{ url_for('list_users') }}">View all users</a></p>
</body>
</html> -
templates/users.html内容:html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Users</title>
</head>
<body>
<h1>All Users</h1>
<ul>
{% for user in users %}
<li>{{ user.username }} ({{ user.email }})</li>
{% else %}
<li>No users found.</li>
{% endfor %}
</ul>
<p><a href="{{ url_for('add_user') }}">Add a new user</a></p>
</body>
</html>
运行说明:
第一次运行 app.py 时,db.create_all() 会创建 site.db 数据库文件。
访问 http://127.0.0.1:5000/add_user 添加用户,然后访问 http://127.0.0.1:5000/users 查看用户列表。
9. 总结
本指南介绍了 Flask Web 开发的基础知识,包括:
- 环境设置和安装
- 创建“Hello World”应用
- 路由定义和变量
- 使用 Jinja2 模板渲染动态内容
- 引用静态文件 (CSS/JS)
- 处理 HTTP 请求和表单数据
- 与数据库集成 (Flask-SQLAlchemy 示例)
这只是一个快速入门,Flask 还有许多高级特性和扩展,如会话管理、消息闪现、蓝图(Blueprints)用于模块化应用等。建议查阅 Flask 官方文档 深入学习。