【PythonWeb开发】Flask-RESTful视图类基础知识

flask_restful 是一个扩展库,它为 Flask 提供了快速构建 RESTful API 的功能。使用 flask_restful 可以简化 RESTful API 的开发过程,减少样板代码,并且提供了一些高级特性,如 HTTP 方法的映射、资源路由的定义等。

flask_restful中,类视图是构建RESTful API的主要方法之一。下面是一些关键的知识点:

(1)定义资源类

这个资源类其实就是,视图类。资源类继承自flask_resetful.Resource类。每个资源类代表一个RESTful资源。

python 复制代码
from flask import Flask, jsonify
from flask_restful import Resource

class HelloWorld(Resource):
    
    def get(self):
        return jsonify({"hello": "world"})

(2)添加资源到API

使用flask_restful.Api类来创建一个API实例,并将资源添加到API中。API实例负责路由的设置和资源的注册。

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


app = Flask(__name__)
api = Api(app)   # 可以直接将app传入的方式来绑定API插件

class HelloWorld(Resource):
    def get(self):
        return {"hello": "world"}

# 将HelloWorld资源类绑定到'/hello'路径
api.add_resource(HelloWorld, '/hello')

(3)处理HTTP方法

资源类中的方法对应HTTP方法。常见的HTTP方法包括GET,POST,PUT,DELETE等。

python 复制代码
class UserResource(Resource):
    def get(self, user_id):
        # 查询用户信息
        # 从请求路径中获取 user_id
        return {'user': user_id}, 200   # 第二个参数是状态码

    def post(self):
        # 创建用户
        # 获取 JSON 请求体中的数据
        data = request.get_json()
        return {'data': data}, 201   # 创建成功

    def put(self, user_id):
        # 更新用户信息
        pass

    def delete(self, user_id):
        # 删除用户
        pass

# 注册资源(定义路由)
api.add_resource(User, '/users/<int:user_id>')
相关推荐
默_笙2 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
qq_426003962 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫2 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
长沙三为智能科技2 天前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
伞伞悦读2 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
只睡四小时2 天前
Canvas 弹道联机实战:700 行 + 固定时间步长
python·websocket·html5·游戏开发·canvas
奇思妙想聪明勤奋的小羊2 天前
DeepAgents第5章:子Agent 与上下文隔离—让 Agent学会委派
人工智能·python·学习·语言模型
lpfasd1232 天前
2026年第38周GitHub趋势周报
python·科技·github
IZero072 天前
Jev 与 Laya
python·语言模型