python - 为 API 调用创建基本响应

标签 python django django-rest-framework

我想使用 django-rest-framework 创建一个 API。到目前为止,我已经设法设置了 API 的一个端点并设法获取了所有项目。一个基本的响应(没有后面描述的 BaseResponse 类)看起来像这样:

[
    {
        "uuid": "1db6a08d-ec63-4beb-8b41-9b042c53ab83",
        "created_at": "2018-03-12T19:25:07.073620Z",
        "updated_at": "2018-03-12T19:25:37.904350Z",
        "deleted_at": null,
        "random_name": "random name"
    }
]

我想要达到的结果是这样的:

[
    "success": true
    "message": "Some exception message",
    "data" :{
        "uuid": "1db6a08d-ec63-4beb-8b41-9b042c53ab83",
        "created_at": "2018-03-12T19:25:07.073620Z",
        "updated_at": "2018-03-12T19:25:37.904350Z",
        "deleted_at": null,
        "random_name": "random name"
    }
]

我设法通过创建一个 BaseReponse 类来实现这一点,并且在 View 中我只是返回 BaseResponse.to_dict() (我在类内部创建的一个方法)。

class BaseResponse(object):

    data = None
    success = False
    message = None

    def __init__(self, data, exception):
        self.data = data
        self.message = str(exception) if exception is not None else None
        self.success = exception is None

    def to_dict(self):
        return {
            'success': self.success,
            'message': self.message,
            'data': self.data,
        }

查看:

class RandomModelList(APIView):

    def get(self, request, format=None):
        exception = None
        models = None
        try:
            models = RandomModel.objects.all()
        except Exception as e:
            exception = e
        serializer = RandomModelSerializer(models, many=True)

        base_response = BaseResponse(data=serializer.data, exception=exception)

        return Response(base_response.to_dict())

我想说的是,使用当前代码,一切都按预期工作,但我对代码有很大的双重看法(我只是觉得我重新发明了轮子)。有人可以告诉我这是否是解决我的问题的最佳解决方案,如果不是,我应该更改/使用什么?

最佳答案

您可以改为创建自定义渲染器。有点像

class CustomRenderer(JSONRenderer):

    def render(self, data, accepted_media_type=None, renderer_context=None):
        resp = {
        'data': data
        }
        return super(CustomRenderer, self).render(resp, accepted_media_type, renderer_context)

然后像这样创建一个中间件

class CustomResponseMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        response.data.update({'success': is_client_error(response.status_code) or is_server_error(response.status_code)})
    return response

关于python - 为 API 调用创建基本响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49287205/

相关文章:

Django/Ajax 发送 'none' 值查看

Mysql 不被识别为内部或外部命令

python - 如何使 rest_framework 序列化程序不允许多余的字段?

python - 将列表转换为查询集

python - Django REST Framework - 序列化可选字段

python - 更改 rPython 中的 python 版本?

python - 使用 Python 进行计算和编程介绍

python - 从与索引对齐的两个 pandas 系列中获取非空字符串值的有效方法

Python struct.Struct.size 返回意外值

python - 为什么我在插入 MySQL 数据库时会收到此 UnicodeEncodeError?