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
相关推荐
java1234_小锋10 分钟前
【NLP舆情分析】基于python微博舆情分析可视化系统(flask+pandas+echarts) 视频教程 - 热词数量分析日期统计功能实现
python·自然语言处理·flask
山烛26 分钟前
KNN 算法中的各种距离:从原理到应用
人工智能·python·算法·机器学习·knn·k近邻算法·距离公式
guozhetao39 分钟前
【ST表、倍增】P7167 [eJOI 2020] Fountain (Day1)
java·c++·python·算法·leetcode·深度优先·图论
墨染点香1 小时前
第七章 Pytorch构建模型详解【构建CIFAR10模型结构】
人工智能·pytorch·python
阿什么名字不会重复呢1 小时前
在线工具+网页平台来学习和操作Python与Excel相关技能
python·数据分析
Vertira2 小时前
python 阿里云 安装 dashscope的简介、安装
开发语言·python
gc_22993 小时前
学习Python中Selenium模块的基本用法(1:简介)
python·selenium
先做个垃圾出来………3 小时前
2116. 判断一个括号字符串是否有效
python
兮℡檬,4 小时前
房价预测|Pytorch
人工智能·pytorch·python
im_AMBER7 小时前
学习日志19 python
python·学习