1. Flask 简介
Flask 是一个轻量级的 Python Web 应用框架,被称为"微框架"(micro-framework)。它基于 Werkzeug WSGI 工具包和 Jinja2 模板引擎,提供了 Web 开发所需的核心功能,同时保持了高度的灵活性和扩展性。
1.1 Flask 的特点
轻量级: 核心简单但是扩展性强
灵活性: 不强制特定的项目布局或依赖
容易上手: 简单的 API 设计,清晰的文档
强大的扩展生态: 丰富的第三方扩展支持
活跃的社区: 持续的维护和更新
pip install flask
2. Flask 基础2.1 第一个 Flask 应用from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run(debug=True)
2.2 路由系统2.2.1 基本路由@app.route('/user')
def user_page():
return 'User Page'
2.2.2 动态路由@app.route('/user/ ')
def show_user_profile(username):
return f'User {username}'
@app.route('/post/ ')
def show_post(post_id):
return f'Post {post_id}'
2.2.3 HTTP 方法@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
return 'Processing login...'
return 'Please login'
3. 模板引擎(Jinja2)3.1 基本用法from flask import render_template
@app.route('/hello/ ')
def hello(name):
return render_template('hello.html', name=name)
模板文件hello.html
:
3.2 模板语法3.2.1 变量html> Hello Page title> head>
Hello {{ name }}! h1> body> html>
{{ variable }}
3.2.2 控制结构{% if user %}
Hello, {{ user }}!
{% else %}
Hello, Stranger!
{% endif %}
{% for item in items %}
{{ item }} li> {% endfor %}
- 4. 表单处理4.1 基本表单
from flask import request
@app.route('/submit', methods=['GET', 'POST'])
def submit():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
return f'Received: {username}'
return ''' '''
4.2 Flask-WTF 表单from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import DataRequired
class LoginForm(FlaskForm):
username = StringField('Username', validators=[DataRequired()])
password = PasswordField('Password', validators=[DataRequired()])
submit = SubmitField('Login')
5. 数据库集成5.1 Flask-SQLAlchemyfrom flask_sqlalchemy import SQLAlchemy
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db = SQLAlchemy(app)
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)
6. 用户认证6.1 Flask-Loginfrom flask_login import LoginManager, UserMixin, login_user, login_required
login_manager = LoginManager()
login_manager.init_app(app)
class User(UserMixin, db.Model):
# 用户模型定义
pass
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
@app.route('/protected')
@login_required
def protected():
return 'Protected area'
7. RESTful API 开发7.1 基本 REST API@app.route('/api/users', methods=['GET'])
def get_users():
users = User.query.all()
return jsonify([{'id': user.id, 'username': user.username} for user in users])
@app.route('/api/users/ ', methods=['GET'])
def get_user(user_id):
user = User.query.get_or_404(user_id)
return jsonify({'id': user.id, 'username': user.username})
7.2 Flask-RESTfulfrom flask_restful import Resource, Api
api = Api(app)
class UserResource(Resource):
def get(self, user_id):
user = User.query.get_or_404(user_id)
return {'id': user.id, 'username': user.username}
api.add_resource(UserResource, '/api/users/ ' )
8. 项目结构推荐的项目结构:
myproject/
├── app/
│ ├── __init__.py
│ ├── models.py
│ ├── routes.py
│ └── templates/
├── config.py
├── requirements.txt
└── run.py
9. 部署9.1 生产环境配置# config.py
class ProductionConfig:
DEBUG = False
SQLALCHEMY_DATABASE_URI = 'postgresql://user:password@localhost/dbname'
SECRET_KEY = 'your-secret-key'
9.2 使用 Gunicorn 部署pip install gunicorn
gunicorn -w 4 -b 127.0.0.1:8000 run:app
10. 最佳实践10.1 错误处理@app.errorhandler(404)
def not_found_error(error):
return render_template('404.html'), 404
@app.errorhandler(500)
def internal_error(error):
db.session.rollback()
return render_template('500.html'), 500
10.2 日志配置import logging
from logging.handlers import RotatingFileHandler
if not app.debug:
file_handler = RotatingFileHandler('logs/myapp.log', maxBytes=10240, backupCount=10)
file_handler.setFormatter(logging.Formatter(
'%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'
))
file_handler.setLevel(logging.INFO)
app.logger.addHandler(file_handler)
11. 进阶主题11.1 蓝图(Blueprints)from flask import Blueprint
admin = Blueprint('admin', __name__)
@admin.route('/dashboard')
@login_required
def dashboard():
return render_template('admin/dashboard.html')
11.2 Flask 信号from flask import signals
def handle_user_login(sender, user):
app.logger.info(f'User {user.username} logged in')
user_logged_in.connect(handle_user_login)
12. 调试与测试12.1 调试模式app.run(debug=True)
12.2 单元测试import unittest
class TestCase(unittest.TestCase):
def setUp(self):
self.app = create_app('testing')
self.client = self.app.test_client()
def test_home_page(self):
response = self.client.get('/')
self.assertEqual(response.status_code, 200)
总结Flask 是一个强大而灵活的 Web 框架,适合各种规模的项目开发。通过本教程,我们覆盖了从基础到高级的主要开发概念和实践。要成为一个优秀的 Flask 开发者,建议:
深入理解 Flask 的核心概念
熟练掌握常用扩展
遵循最佳实践
注重代码质量和测试
持续学习和实践
特别声明:以上内容(如有图片或视频亦包括在内)为自媒体平台“网易号”用户上传并发布,本平台仅提供信息存储服务。
Notice: The content above (including the pictures and videos if any) is uploaded and posted by a user of NetEase Hao, which is a social media platform and only provides information storage services.