文章目录
- 使用Flask实现基本HTTP谓词操作
- 1 目标
- 2 代码
使用Flask实现基本HTTP谓词操作
1 目标
使用Flask实现基本HTTP谓词操作。
| HTTP 谓词 | 功能 | 用途 | 示例 |
|---|---|---|---|
| GET | 获取资源 | 从服务器检索数据,不会对服务器上的数据产生任何影响 | 获取所有项目:GET /items 获取指定ID的项目:GET /items/1 |
| POST | 创建资源 | 向服务器发送数据,并在服务器上创建新的资源 | 添加新项目:POST /items 请求体:{ “name”: “New Item”, “description”: “New Description” } |
| PUT | 更新资源(替换整个资源) | 替换服务器上的现有资源 | 更新项目:PUT /items/1 请求体:{ “name”: “Updated Item”, “description”: “Updated Description” } |
| PATCH | 更新资源(部分更新资源) | 更新服务器上的现有资源的部分内容 | 部分更新项目:PATCH /items/1 请求体:{ “description”: “Partially Updated Description” } |
| DELETE | 删除资源 | 从服务器上删除指定资源 | 删除项目:DELETE /items/1 |
2 代码
from flask import Flask, request, jsonify
app = Flask(__name__)
port = 3000
# 示例数据
items = [
{ "id": 1, "name": "Item 1", "description": "Description 1" },
{ "id": 2, "name": "Item 2", "description": "Description 2" },
]
# GET 请求:获取所有项目
@app.route('/items', methods=['GET'])
def get_items():
return jsonify(items)
# GET 请求:根据ID获取项目
@app.route('/items/<int:id>', methods=['GET'])
def get_item(id):
item = next((i for i in items if i['id'] == id), None)
if item is None:
return 'Item not found', 404
return jsonify(item)
# POST 请求:添加新项目
@app.route('/items', methods=['POST'])
def add_item():
new_item = {
"id": len(items) + 1,
"name": request.json.get('name'),
"description": request.json.get('description'),
}
items.append(new_item)
return jsonify(new_item), 201
# PUT 请求:更新项目(替换整个项目)
@app.route('/items/<int:id>', methods=['PUT'])
def update_item(id):
item_index = next((index for index, item in enumerate(items) if item['id'] == id), -1)
if item_index == -1:
return 'Item not found', 404
updated_item = {
"id": id, # 保留原有ID
"name": request.json.get('name'),
"description": request.json.get('description'),
}
items[item_index] = updated_item
return jsonify(updated_item)
# PATCH 请求:部分更新项目
@app.route('/items/<int:id>', methods=['PATCH'])
def patch_item(id):
item = next((i for i in items if i['id'] == id), None)
if item is None:
return 'Item not found', 404
if 'name' in request.json:
item['name'] = request.json['name']
if 'description' in request.json:
item['description'] = request.json['description']
return jsonify(item)
# DELETE 请求:删除项目
@app.route('/items/<int:id>', methods=['DELETE'])
def delete_item(id):
item_index = next((index for index, item in enumerate(items) if item['id'] == id), -1)
if item_index == -1:
return 'Item not found', 404
deleted_item = items.pop(item_index)
return jsonify(deleted_item)
if __name__ == '__main__':
app.run(port=port)
2万+

被折叠的 条评论
为什么被折叠?



