flask_restful 写个删除接口
时间: 2023-08-03 10:03:46 浏览: 142
好的,以下是一个使用 Flask-RESTful 编写的删除接口的示例代码:
```python
from flask import Flask
from flask_restful import Api, Resource, reqparse
app = Flask(__name__)
api = Api(app)
# 假设我们要删除的资源是一个 todo
todos = {
'todo1': {'task': 'build an API'},
'todo2': {'task': '?????'},
'todo3': {'task': 'profit!'},
}
# 定义一个请求参数解析器
parser = reqparse.RequestParser()
parser.add_argument('task', type=str, help='Task to be deleted is required', required=True)
# 定义一个 Todo 类,继承自 Resource 类
class Todo(Resource):
def delete(self, todo_id):
args = parser.parse_args()
task = args['task']
del todos[todo_id]
return {task: 'deleted successfully'}, 204
# 将 Todo 类绑定到 /todos/<string:todo_id> 路由上
api.add_resource(Todo, '/todos/<string:todo_id>')
if __name__ == '__main__':
app.run(debug=True)
```
这个接口将在访问 /todos/<string:todo_id> 路由时删除一个 todo 资源,并返回一个 HTTP 204 No Content 响应。请求参数中需要指定待删除任务的描述,例如:
```
DELETE /todos/todo1?task=build an API HTTP/1.1
```
阅读全文