The Way to Flask 项目解析:构建简单的 REST 服务
什么是 REST 服务
在现代 Web 开发中,REST (Representational State Transfer) 已经成为构建 API 的主流架构风格。REST 服务通过 HTTP 协议提供轻量级的接口,使客户端和服务器能够以标准化的方式进行数据交换。
REST 服务的核心特点包括:
- 无状态性:每个请求都包含处理所需的所有信息
- 资源导向:通过 URI 标识资源
- 统一接口:使用标准的 HTTP 方法 (GET, POST, PUT, DELETE 等)
- 可缓存性:响应可以明确标记为可缓存或不可缓存
从简单 Flask 应用到 REST 服务
在 The Way to Flask 项目中,作者展示了如何将一个简单的返回 "Hello World" 的 Flask 应用改造为功能完整的 REST 服务。让我们深入分析这个转换过程的关键步骤。
基础改造:返回 JSON 数据
最初的 Flask 应用返回简单的字符串:
@app.route('/')
def index():
return "Hello World!"
改造为返回 JSON 数据时,初学者可能会直接使用 Python 的 json 模块:
import json
@app.route('/')
def index():
return json.dumps({'name': 'tyrael', 'email': 'liqianglau@outlook.com'})
问题发现:虽然返回了 JSON 格式的数据,但响应头仍然是 text/html,这可能导致客户端解析问题。
解决方案:使用 Flask 提供的 jsonify 函数:
from flask import jsonify
@app.route('/')
def index():
return jsonify({'name': 'tyrael', 'email': 'liqianglau@outlook.com'})
jsonify 不仅会自动设置正确的 Content-Type 头 (application/json),还会对 JSON 数据进行格式化,使输出更易读。
支持多种 HTTP 方法
完整的 REST 服务需要支持多种 HTTP 方法来实现 CRUD (Create, Read, Update, Delete) 操作:
@app.route('/', methods=['GET']) # 查询
@app.route('/', methods=['PUT']) # 创建
@app.route('/', methods=['POST']) # 更新
@app.route('/', methods=['DELETE']) # 删除
每种方法对应不同的业务逻辑:
- GET - 查询数据
- PUT - 创建新记录
- POST - 更新现有记录
- DELETE - 删除记录
请求数据处理
Flask 提供了 request 对象来处理客户端发送的数据:
-
GET 请求参数:通过
request.args获取 URL 查询参数name = request.args.get('name') -
请求体数据:通过
request.data获取请求体内容record = json.loads(request.data)
完整实现解析
项目中使用文件作为临时数据存储,实现了完整的 CRUD 操作:
查询数据 (GET)
@app.route('/', methods=['GET'])
def query_records():
name = request.args.get('name')
with open('/tmp/data.txt', 'r') as f:
data = f.read()
records = json.loads(data)
for record in records:
if record['name'] == name:
return jsonify(record)
return jsonify({'error': 'data not found'})
创建数据 (PUT)
@app.route('/', methods=['PUT'])
def create_record():
record = json.loads(request.data)
with open('/tmp/data.txt', 'r') as f:
data = f.read()
records = json.loads(data) if data else []
records.append(record)
with open('/tmp/data.txt', 'w') as f:
f.write(json.dumps(records, indent=2))
return jsonify(record)
更新数据 (POST)
@app.route('/', methods=['POST'])
def update_record():
record = json.loads(request.data)
new_records = []
with open('/tmp/data.txt', 'r') as f:
records = json.loads(f.read())
for r in records:
if r['name'] == record['name']:
r['email'] = record['email']
new_records.append(r)
with open('/tmp/data.txt', 'w') as f:
f.write(json.dumps(new_records, indent=2))
return jsonify(record)
删除数据 (DELETE)
@app.route('/', methods=['DELETE'])
def delte_record():
record = json.loads(request.data)
with open('/tmp/data.txt', 'r') as f:
records = json.loads(f.read())
new_records = [r for r in records if r['name'] != record['name']]
with open('/tmp/data.txt', 'w') as f:
f.write(json.dumps(new_records, indent=2))
return jsonify(record)
实际开发建议
虽然这个示例使用文件存储数据,但在实际项目中:
- 使用数据库:考虑使用 SQLite、MySQL 或 MongoDB 等数据库系统
- 错误处理:添加更完善的错误处理机制
- 数据验证:验证输入数据的格式和有效性
- 身份验证:添加 API 访问权限控制
- 分页:对于大量数据实现分页查询
总结
The Way to Flask 项目通过这个简单的 REST 服务示例,清晰地展示了:
- 如何正确处理 JSON 响应
- 如何支持多种 HTTP 方法
- 如何获取不同类型的请求数据
- 实现完整 CRUD 操作的思路
这个示例为学习 Flask 和 REST API 开发提供了很好的起点,开发者可以在此基础上继续扩展更复杂的功能。
atomcodeClaude Code 的开源替代方案。连接任意大模型,编辑代码,运行命令,自动验证 — 全自动执行。用 Rust 构建,极致性能。 | An open-source alternative to Claude Code. Connect any LLM, edit code, run commands, and verify changes — autonomously. Built in Rust for speed. Get StartedRust0217
cann-learning-hubCANN 学习中心仓,支持在线互动运行、边学边练,提供教程、示例与优化方案,一站式助力昇腾开发者快速上手。Jupyter Notebook0139
uni-appA cross-platform framework using Vue.jsJavaScript09
GLM-5.2智谱开源 GLM-5.2,这是针对长文本任务的最新旗舰模型。相较于前代产品 GLM-5.1,它在长文本任务处理能力上实现了显著飞跃,并且首次在稳定的 100 万 token 上下文中提供这一能力。Jinja00
SwanLab⚡️SwanLab - an open-source, modern-design AI training tracking and visualization tool. Supports Cloud / Self-hosted use. Integrated with PyTorch / Transformers / LLaMA Factory / veRL/ Swift / Ultralytics / MMEngine / Keras etc.Python00
tiny-universe《大模型白盒子构建指南》:一个全手搓的Tiny-UniverseJupyter Notebook03