第三十五章:Flask Web开发
本章目标
完成本章学习后,你将能够:
- 创建Flask应用
- 定义路由和视图
- 处理请求和响应
- 使用模板
快速开始
from flask import Flask, jsonify, request, render_template app = Flask(__name__) @app.route('/') def hello(): return 'Hello, World!' @app.route('/user/<name>') def user(name): return f'Hello, {name}!' @app.route('/api/data', methods=['GET', 'POST']) def data(): if request.method == 'POST': data = request.json return jsonify({'received': data}), 201 return jsonify({'message': 'GET request'}) if __name__ == '__main__': app.run(debug=True)
模板渲染
from flask import render_template @app.route('/hello/<name>') def hello_template(name): return render_template('hello.html', name=name)
- snippet.html
<!-- templates/hello.html --> <!DOCTYPE html> <html> <head><title>Hello</title></head> <body> <h1>Hello, {{ name }}!</h1> {% if name == 'admin' %} <p>Welcome, administrator!</p> {% endif %} </body> </html>
本章练习
- 创建RESTful API
- 实现用户登录系统
- 连接数据库