来自视图的标准化 JSON 响应

发布于 2024-11-18 21:08:12 字数 949 浏览 0 评论 0原文

当我的页面将表单发布到我的 Django 视图时,该视图返回包含一些数据的响应,但很快我就遇到了我的视图以不同格式和不同信息集返回数据的问题。我考虑过使用 JSON 作为标准格式来返回我的数据。

有两种类型的状态:成功失败。当 POST 成功时,它只返回 success 但当失败时,它会返回一个名为 errors 的子组,其中包含一个字段和该字段的错误。

这是一个失败响应示例:

{"failure": {
    "errors":[
        {"fieldname": "<fieldname>", 
         "fielderror": "<fielderror>"
        },
        {"fieldname": "<fieldname>", 
         "fielderror": "<fielderror>"
        }]
}}

这是一个成功响应示例:(

{"success": {
    "data":[
        {"fieldname": "<fieldname>", 
         "fielddata": "<fielddata>"
        },
        {"fieldname": "<fieldname>", 
         "fielddata": "<fielddata>"
        }]
}}

成功响应具有数据字段,因为您经常希望返回一些数据,即新创建的数据库记录的键。 )

这就是我想出的,但是有很多人使用 Django,我想知道是否有一个标准的方法/更强大的方法或一些模块来帮助解决这个问题。

谢谢。

When my page POSTs a form to my Django view, the view returns a response with some data but soon I ran into the issue that my views returned data in different formats and different sets of information. I've thought of using JSON as a standard format to return my data.

There are two types of statuses, success and failure. When the POST was successful, it just returns success but when it has failed, it returns a sub group called errors which contains a of fields and that field's error.

Here's a sample failure response:

{"failure": {
    "errors":[
        {"fieldname": "<fieldname>", 
         "fielderror": "<fielderror>"
        },
        {"fieldname": "<fieldname>", 
         "fielderror": "<fielderror>"
        }]
}}

Here's a sample success response:

{"success": {
    "data":[
        {"fieldname": "<fieldname>", 
         "fielddata": "<fielddata>"
        },
        {"fieldname": "<fieldname>", 
         "fielddata": "<fielddata>"
        }]
}}

(The success response has data fields because quite often you like to return some data i.e. key of newly created DB record.)

This is what I've come up with but so many people using Django out there, I'm wondering whether there is a standard way/more robust of doing this or some module to help with this.

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

樱花细雨 2024-11-25 21:08:12

去过那里。我自己编写了解决方案(因为它很简单。我不知道是否有一个模块可以解决这个问题)。这只是一个 json 响应包装器

from django.utils import simplejson
from django.http import HttpResponse

class JsonResponse(HttpResponse):
    def __init__(self, data):
        content = simplejson.dumps(data)
        super(JsonResponse, self).__init__(content=content,
                                           mimetype='application/json')

class Success(JsonResponse):
    def __init__(self, something):
        x = something # set your data here
        content = {'success': {'data': x}}
        super(Success, self).__init__(content)


class Failure(JsonResponse):
    def __init__(self, something):
        x = something # set your data
        content = {'failures': {'errors': x}}
        super(Failure, self).__init__(content)

之类的东西。就我而言,我使 SuccessFailure 接受字符串和字典作为参数(例如 Success(data)),以使其更加容易

如果您的结构非常复杂(或者您太懒而无法手动编写它们),请为该复杂结构编写您自己的包装器(这样您就可以用更少的打字创建响应),并使成功/失败接受它作为参数。

been there. I wrote the solution my own (since it's simple. I dont know if theres a module out there for this). This is just a json response wrapper

from django.utils import simplejson
from django.http import HttpResponse

class JsonResponse(HttpResponse):
    def __init__(self, data):
        content = simplejson.dumps(data)
        super(JsonResponse, self).__init__(content=content,
                                           mimetype='application/json')

class Success(JsonResponse):
    def __init__(self, something):
        x = something # set your data here
        content = {'success': {'data': x}}
        super(Success, self).__init__(content)


class Failure(JsonResponse):
    def __init__(self, something):
        x = something # set your data
        content = {'failures': {'errors': x}}
        super(Failure, self).__init__(content)

something like that. In my case, I make Success and Failure accept a string and a dictionary for arguments (like Success(data)) to make it even easier

If your structure is quite complex (or youre too lazy too write them manually), write your own wrapper for that complicated structure (so you can create the response with even less typing), and make the Success/Failure accepts that as argument.

酒与心事 2024-11-25 21:08:12

你知道如何使用Python字典吗?如果是这样,那么有一些库可以将 Python 字典转换为有效的 JSON。例如,Django 的内置是 simplejson。这里有一个例子:

from django.utils import simplejson

def my_view(request):
   ....
   my_json = simplejson.dumps(my_dict) #dumps a JSON string from a dict
   my_dict_again = simplejson.loads(my_json) #loads a Python dict from a JSON string

   return HttpResponse(json, mimetype="application/json")

Do you know how to use Python dicts? If so then there are libraries which convert your Python dict into valid JSON. Django's built-in is for example is simplejson. Here an example:

from django.utils import simplejson

def my_view(request):
   ....
   my_json = simplejson.dumps(my_dict) #dumps a JSON string from a dict
   my_dict_again = simplejson.loads(my_json) #loads a Python dict from a JSON string

   return HttpResponse(json, mimetype="application/json")
白云不回头 2024-11-25 21:08:12

好吧,我不知道这对你有多大帮助,但 Python 确实有一个模块 json

>>> import json
>>> json.dumps({'a':'b', 'c':'d'})
'{"a": "b", "c": "d"}'

Well, I don't know how much this will help you out, but Python does have a module json.

>>> import json
>>> json.dumps({'a':'b', 'c':'d'})
'{"a": "b", "c": "d"}'
撞了怀 2024-11-25 21:08:12

我认为前端将会为你应该如何格式化你的数据提供一个更有力的案例,然后是一些“标准”,不同的客户端框架期望不同的东西,并更好或更差地适应与期望的差异。

我试图让自己的生活更轻松的一种方法是让响应的“形状”始终大致相同,例如,响应将始终具有“状态”属性,该属性始终具有“错误”属性,并且如果没有错误,则 result.status.errors 的值为 null。如果出现错误,它将是一个字符串列表,解释出了什么问题。即使出现错误,也会有一个“value”属性,如果无法处理请求,则该属性将为 null;如果可以,则为请求的资源。

I think the front end is going to make a stronger case for how you should format your data then some "standard", Different client side frameworks expect different things, and adapt to differences from that expectations better or worse than that.

One way I try to make my own life easier is to have the 'shape' of the response always roughly the same, for example, the response will always have a 'status' property, which always has an 'errors' property, and if there were no errors, then the value of result.status.errors is null. If there were errors, it'd be a list of strings explaining what went wrong. even if there were errors, there'd be a 'value' property, which would be either null if the request couldn't be serviced, or the requested resource if it could.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文