第三十五章: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)
```html <!– templates/hello.html –> <!DOCTYPE html>
Hello, {{ name }}!
{% if name == 'admin' %}Welcome, administrator!
{% endif %} ```本章练习
1. 创建RESTful API 2. 实现用户登录系统 3. 连接数据库