Flask RESTful 示例

目录

下面创建一个简单的Flask RESTful API示例。首先,我们需要创建环境,安装必要的依赖,然后修改main.py文件来实现一个基本的RESTful API。

1. 环境准备

bash 复制代码
uv init 
uv venv
source .venv/bin/activate

2. 安装依赖

python 复制代码
uv pip install flask flask-restful

3. 修改main.py

现在,让我们修改main.py文件,创建一个简单的RESTful API:

python 复制代码
from flask import Flask, request
from flask_restful import Resource, Api, reqparse

app = Flask(__name__)
api = Api(app)

# 内存中的任务列表
tasks = {
    1: {"task": "学习Flask", "done": False},
    2: {"task": "学习RESTful API", "done": False},
    3: {"task": "构建项目", "done": False}
}

# 任务计数器
task_id_counter = 3

# 创建请求解析器
task_parser = reqparse.RequestParser()
task_parser.add_argument('task', type=str, required=True, help='任务内容不能为空')
task_parser.add_argument('done', type=bool, default=False)

# 处理单个任务的资源
class Task(Resource):
    def get(self, task_id):
        if task_id not in tasks:
            return {"error": "任务不存在"}, 404
        return tasks[task_id]
    
    def delete(self, task_id):
        if task_id not in tasks:
            return {"error": "任务不存在"}, 404
        del tasks[task_id]
        return {"message": f"任务 {task_id} 已删除"}, 200
    
    def put(self, task_id):
        if task_id not in tasks:
            return {"error": "任务不存在"}, 404
        args = task_parser.parse_args()
        tasks[task_id] = {"task": args["task"], "done": args["done"]}
        return tasks[task_id], 200

# 处理任务列表的资源
class TaskList(Resource):
    def get(self):
        return tasks
    
    def post(self):
        global task_id_counter
        args = task_parser.parse_args()
        task_id_counter += 1
        task_id = task_id_counter
        tasks[task_id] = {"task": args["task"], "done": args["done"]}
        return tasks[task_id], 201

# 注册API路由
api.add_resource(TaskList, '/tasks')
api.add_resource(Task, '/tasks/<int:task_id>')

# 主函数
def main():
    print("启动Flask RESTful API服务器...")
    app.run(debug=True)

if __name__ == "__main__":
    main()

4. 运行应用

现在您可以运行应用:

bash 复制代码
uv run main.py

5. API使用示例

获取所有任务

bash 复制代码
curl http://127.0.0.1:5000/tasks

获取单个任务

bash 复制代码
curl http://127.0.0.1:5000/tasks/1

创建新任务

bash 复制代码
curl -X POST http://127.0.0.1:5000/tasks -H "Content-Type: application/json" -d "{\"task\": \"新任务\", \"done\": false}"

更新任务

bash 复制代码
curl -X PUT http://127.0.0.1:5000/tasks/1 -H "Content-Type: application/json" -d "{\"task\": \"更新的任务\", \"done\": true}"

删除任务

bash 复制代码
curl -X DELETE http://127.0.0.1:5000/tasks/1

中文乱码问题:

将原文件中的flask_restful\representations\json.py

python 复制代码
from __future__ import absolute_import
from flask import make_response, current_app
from flask_restful.utils import PY3
from json import dumps


def output_json(data, code, headers=None):
    """Makes a Flask response with a JSON encoded body"""

    settings = current_app.config.get('RESTFUL_JSON', {})

    # If we're in debug mode, and the indent is not set, we set it to a
    # reasonable value here.  Note that this won't override any existing value
    # that was set.  We also set the "sort_keys" value.
    if current_app.debug:
        settings.setdefault('indent', 4)
        settings.setdefault('sort_keys', not PY3)

    # always end the json dumps with a new line
    # see https://github.com/mitsuhiko/flask/pull/1262
    dumped = dumps(data, **settings) + "\n"

    resp = make_response(dumped, code)
    resp.headers.extend(headers or {})
    return resp

改为

python 复制代码
from __future__ import absolute_import
from flask import make_response, current_app
from flask_restful.utils import PY3
import json

def output_json(data, code, headers=None):
    """Makes a Flask response with a JSON encoded body"""

    settings = current_app.config.get('RESTFUL_JSON', {})
    
    # 确保不使用ASCII编码中文字符
    settings.setdefault('ensure_ascii', False)

    # 如果在调试模式下,设置缩进和排序键
    if current_app.debug:
        settings.setdefault('indent', 4)
        settings.setdefault('sort_keys', True)

    # 总是以换行符结束JSON输出
    # 参见 https://github.com/mitsuhiko/flask/pull/1262
    dumped = json.dumps(data, **settings) + "\n"

    resp = make_response(dumped, code)
    resp.headers.extend(headers or {})
    # 明确设置内容类型为JSON,并指定UTF-8编码
    resp.headers['Content-Type'] = 'application/json; charset=utf-8'
    return resp
相关推荐
孟健12 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞14 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽17 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程21 小时前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪21 小时前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook1 天前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
花酒锄作田1 天前
使用 pkgutil 实现动态插件系统
python
前端付豪2 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽2 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战2 天前
Pydantic配置管理最佳实践(一)
python