十五天Python系统学习教程第十三天

Day 13 详细学习计划:Python Web开发基础与实战

学习目标
✅ 掌握Flask框架核心组件(对比Java的Spring Boot)
✅ 实现路由、模板渲染与表单处理
✅ 集成数据库与REST API开发
✅ 完成博客系统Web层开发实战


一、Web框架核心对比(Java vs Python)

功能 Java(Spring Boot) Python(Flask) 核心差异
路由定义 @GetMapping注解 @app.route装饰器 Python更简洁
模板引擎 Thymeleaf/JSP Jinja2 语法类似但更灵活
依赖注入 @Autowired 无原生DI,需手动或第三方库 Python更显式
启动方式 内嵌Tomcat/Jar包 开发服务器(flask run Python更适合快速原型开发

二、Flask基础组件(1小时)

2.1 最小应用(对比Spring Boot启动类)

from flask import Flask  
app = Flask(__name__)  

@app.route("/")  
def home():  
    return "欢迎来到Python博客系统!"  

if __name__ == "__main__":  
    app.run(debug=True)  # 类似Spring的DevTools  
2.2 配置管理(对比application.properties)

# config.py  
class Config:  
    SECRET_KEY = "your-secret-key"  
    SQLALCHEMY_DATABASE_URI = "sqlite:///blog.db"  

# 初始化配置  
app.config.from_object(Config)  

三、模板与表单处理(1.5小时)

3.1 Jinja2模板(对比Thymeleaf)
  
  
  
{{ title }}  
  
  

{{ title }}

{% for post in posts %}

{{ post.title }}

{{ post.content | truncate(100) }}

{% endfor %}
 
  

路由渲染模板

@app.route("/posts")  
def list_posts():  
    posts = Post.query.all()  # 使用SQLAlchemy查询  
    return render_template("index.html", title="所有文章", posts=posts)  
3.2 表单处理(对比Spring MVC Form)

from flask_wtf import FlaskForm  
from wtforms import StringField, TextAreaField  
from wtforms.validators import DataRequired  

class PostForm(FlaskForm):  
    title = StringField("标题", validators=[DataRequired()])  
    content = TextAreaField("内容")  

@app.route("/create", methods=["GET", "POST"])  
def create_post():  
    form = PostForm()  
    if form.validate_on_submit():  
        new_post = Post(title=form.title.data, content=form.content.data)  
        db.session.add(new_post)  
        db.session.commit()  
        return redirect(url_for("list_posts"))  
    return render_template("create.html", form=form)

四、数据库集成(1小时)

4.1 Flask-SQLAlchemy(对比Spring Data JPA)

from flask_sqlalchemy import SQLAlchemy  

db = SQLAlchemy(app)  

class Post(db.Model):  
    id = db.Column(db.Integer, primary_key=True)  
    title = db.Column(db.String(100), nullable=False)  
    content = db.Column(db.Text)  

# 初始化数据库(类似JPA的DDL生成)  
with app.app_context():  
    db.create_all()  
4.2 数据库迁移(对比Flyway/Liquibase)

pip install Flask-Migrate  
flask db init          # 初始化迁移目录  
flask db migrate       # 生成迁移脚本  
flask db upgrade       # 执行迁移  

五、REST API开发(1小时)

5.1 基础API(对比Spring @RestController)

from flask import jsonify  

@app.route("/api/posts")  
def api_posts():  
    posts = Post.query.all()  
    return jsonify([{"id": p.id, "title": p.title} for p in posts])  
5.2 使用Flask-RESTful(对比Spring HATEOAS)

from flask_restful import Resource, Api  

api = Api(app)  

class PostResource(Resource):  
    def get(self, post_id):  
        post = Post.query.get_or_404(post_id)  
        return {"id": post.id, "title": post.title}  

api.add_resource(PostResource, "/api/posts/")  

六、实战项目:博客系统Web层(1.5小时)

6.1 功能需求
  • 用户认证(注册/登录)

  • 文章发布与管理(CRUD)

  • 标签分类与搜索

  • Markdown内容支持

6.2 核心代码实现

用户认证(对比Spring Security)

from werkzeug.security import generate_password_hash, check_password_hash  

class User(db.Model):  
    # ...  
    password_hash = db.Column(db.String(128))  

    @property  
    def password(self):  
        raise AttributeError("密码不可读")  

    @password.setter  
    def password(self, password):  
        self.password_hash = generate_password_hash(password)  

    def verify_password(self, password):  
        return check_password_hash(self.password_hash, password)  

Markdown支持

import markdown  

@app.template_filter("markdown")  
def markdown_filter(text):  
    return markdown.markdown(text)  

  
{{ post.content | markdown | safe }}

七、Java开发者注意事项

  1. 线程局部变量

    • Flask的request对象基于线程局部(类似Java的ThreadLocal)

    • 异步环境下需使用copy_current_request_context

  2. 依赖管理差异

    • Python无类似Spring的自动扫描,需显式导入路由

    # 手动注册蓝图  
    from .auth import auth_bp  
    app.register_blueprint(auth_bp)  

  3. 性能优化

    • 生产环境需使用Gunicorn或uWSGI(类似Tomcat部署)

    
    gunicorn -w 4 "app:app"  # 启动4个Worker进程  


八、扩展练习

  1. 添加缓存支持

    from flask_caching import Cache  
    cache = Cache(config={"CACHE_TYPE": "RedisCache"})  
    @app.route("/posts")  
    @cache.cached(timeout=60)  
    def list_posts():  
        # ...  

  2. 实现OAuth登录

    from authlib.integrations.flask_client import OAuth  
    oauth = OAuth(app)  
    github = oauth.register("github", client_id="...", client_secret="...")  

  3. 容器化部署

    FROM python:3.10  
    COPY requirements.txt .  
    RUN pip install -r requirements.txt  
    COPY . .  
    CMD ["gunicorn", "-b", "0.0.0.0:5000", "app:app"]  


通过第十三天学习,您将掌握:
1️⃣ Python Web开发的核心模式与Java的差异
2️⃣ Flask框架的完整开发流程
3️⃣ 数据库集成与REST API设计技巧
4️⃣ 生产级Web应用的部署与优化策略

本篇的分享就到这里了,感谢观看,如果对你有帮助,别忘了点赞+收藏+关注。

你可能感兴趣的:(python学习,python,java,学习,开发语言)