Django REST框架:非模型序列化程序 [英] Django REST framework: non-model serializer

查看:268
本文介绍了Django REST框架:非模型序列化程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Django REST框架的初学者,需要你的建议。我正在开发Web服务。该服务必须向其他服务提供REST接口。我需要实现的REST界面不能直接使用我的模型(我的意思是get,put,post,delete操作)。相反,它为其他服务提供了一些计算结果。根据请求,我的服务进行一些计算,只是返回结果(不将结果存储在其自己的数据库中)。



以下是我对如何实现REST界面的理解。纠正我,如果我错了


  1. 创建进行计算的类。将其命名为CalcClass。 CalcClass在其工作中使用模型。


    • 计算所需的参数传递给构造函数。

    • 实施calc操作。它将结果返回为ResultClass。


  2. 创建ResultClass。


    • 派生自对象。

    • 它只包含包含calc结果的属性。

    • 计算结果的一部分表示为元组的元组。据了解,对于进一步的序列化,将更好地为这些结果实现一个单独的类,并将此类对象的列表添加到ResultClass。


  3. 为ResultClass创建Serializer。


    • 从串行化器派生。 。

    • calc结果是只读的,因此大部分Field类用于字段,而不是专门的类,例如IntegerField。

    • 我不应该在ResultClass和Serializer上都没有保存()方法,因为我不会存储结果(我只想根据请求返回)。

    • 嵌套结果的Impl序列化(记住上面提到的元组元组)。


  4. 创建视图以返回计算结果。


    • 派生自APIView 。

    • 只需要get()。在get()中,通过从请求中获取的params创建CalcClass,调用其calc(),获取ResultClass,创建Serializer并将ResultClass传递给它,返回Response(serializer.data)。


  5. 网址


    • 在我的情况下没有api根。我应该只有URL获得各种计算结果(用diff参数计算)。

    • 添加调用format_suffix_patterns进行api浏览。


我错过了什么吗?该方法一般是正确的吗?

解决方案

Django-rest-framework甚至没有把它绑定到一个模型上也能运行良好。你的方法听起来不错,但我相信你可以修剪一些步骤来使一切正常。



例如,休息框架附带一些内置的渲染器。开箱即用可以将JSON和XML返回给API消费者。您也可以通过安装所需的python模块来启用YAML。 Django-rest-framework将输出任何基本对象,如dict,list和tuple,而不需要任何额外的工作。



所以基本上你只需要创建函数或类它接受参数,执行所有必需的计算,并将其结果返回到REST api视图的元组中。如果JSON和/或XML符合您的需求,django-rest-framework将会为您处理序列化。



在这种情况下,您可以跳过步骤2和3,并且只需使用一个类进行计算,一个用于向API消费者演示。



以下是一些片段可能会帮助您:



请注意,我还没有测试过。这只是一个例子,但它应该可以工作:)



CalcClass:

  class CalcClass(object):

def __init __(self,* args,** kw):
#从输入中初始化所需的任何变量


def do_work(self):
#在这里做一些计算
#返回一个元组((1,2,3,),(4, 5,6))
result =((1,2,3,),(4,5,6,))#最终结果
返回结果

REST视图:

  from rest_framework。视图导入APIView 
from rest_framework.response import Response
from rest_framework import status

from MyProject.MyApp import CalcClass


class MyRESTView( APIView):

def get(self,request,* args,** kw):
#处理任何可能需要的参数
#如果不需要要处理获取参数,
#你可以跳过这个部分
get_arg1 = request.GET.get('arg1',无)
get_arg2 = request.GET.get('arg2',无)

#任何URL参数获取传入** kw
myClass = CalcClass(get_arg1,get_arg2,* args,** kw)
result = myClass.do_work()
response = Response(result,status = status.HTTP_200_OK )
返回响应

您的urls.py:


$来自MyProject.MyApp.views的b $ b

 导入MyRESTView 
from django.conf.urls.defaults import *

urlpatterns = patterns(' ',
#此URL将** kw中的resource_id传递给MyRESTView
url(r'^ api / v1.0 / resource /(?P< resource_id> \d +)[/]?$ ,login_required(MyRESTView.as_view()),name ='my_rest_view'),
url(r'^ api / v1.0 / resource [/]?$',login_required(MyRESTView.as_view() ='my_rest_view'),

此代码应输出列表,当您访问 http://example.com/api/v1.0/resource/?format=json 。如果使用后缀,您可以用 .json 替换?format = json 。您还可以通过添加Content-typeAccept指定要返回的编码标题。

  [
[
1,
2,
3
],
[
4,
5,
6
]
]
pre>

希望这有助于您。


I am beginner in Django REST framework and need your advice. I am developing a web service. The service has to provide REST interface to other services. The REST interface, which I need to implement, is not working with my models directly (I mean the get, put, post, delete operations). Instead, it provides other services with some calculation results. On a request my service makes some calculations and just returns the results back (doesn't store the results in its own database).

Below is my understanding of how that REST interface could be implemented. Correct me, if I am wrong.

  1. Create class which makes the calculations. Name it 'CalcClass'. CalcClass uses the models in its work.
    • Params necessary for the calculations are passed to the constructor.
    • Implement the calc operation. It returns results as 'ResultClass'.
  2. Create ResultClass.
    • Derived from object.
    • It just only has attributes containing the calc results.
    • One part of the calc results is represented as tuple of tuples. As I understand, it would be better for further serialization to implement a separate class for those results and add list of such objects to ResultClass.
  3. Create Serializer for ResultClass.
    • Derive from serializers.Serializer.
    • The calc results are read-only, so use mostly Field class for fields, instead of specialized classes, such as IntegerField.
    • I should not impl save() method neither on ResultClass, nor on Serializer, because I am not going to store the results (I just want to return them on request).
    • Impl serializer for nested results (remember tuple of tuples mentioned above).
  4. Create View to return calculation results.
    • Derive from APIView.
    • Need just get().
    • In get() create CalcClass with params retrieved from the request, call its calc(), get ResultClass, create Serializer and pass the ResultClass to it, return Response(serializer.data).
  5. URLs
    • There is no api root in my case. I should just have URLs to get various calc results (calc with diff params).
    • Add calling format_suffix_patterns for api browsing.

Did I miss something? Is the approach is correct in general?

解决方案

Django-rest-framework works well even without tying it to a model. Your approach sounds ok, but I believe you can trim some of the steps to get everything working.

For example, rest framework comes with a few built-in renderers. Out of the box it can return JSON and XML to the API consumer. You can also enable YAML by just installing the required python module. Django-rest-framework will output any basic object like dict, list and tuple without any extra work on your part.

So basically you only have to create the function or class that takes in arguments, does all of the required calculations and returns its results in a tuple to the REST api view. If JSON and/or XML fits your needs, django-rest-framework will take care of the serialization for you.

You can skip steps 2 and 3 in this case, and just use one class for calculations and one for presentation to the API consumer.

Here are a few snippets may help you out:

Please note that I have not tested this. It's only meant as an example, but it should work :)

The CalcClass:

class CalcClass(object):

    def __init__(self, *args, **kw):
        # Initialize any variables you need from the input you get
        pass

    def do_work(self):
        # Do some calculations here
        # returns a tuple ((1,2,3, ), (4,5,6,))
        result = ((1,2,3, ), (4,5,6,)) # final result
        return result

The REST view:

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status

from MyProject.MyApp import CalcClass


class MyRESTView(APIView):

    def get(self, request, *args, **kw):
        # Process any get params that you may need
        # If you don't need to process get params,
        # you can skip this part
        get_arg1 = request.GET.get('arg1', None)
        get_arg2 = request.GET.get('arg2', None)

        # Any URL parameters get passed in **kw
        myClass = CalcClass(get_arg1, get_arg2, *args, **kw)
        result = myClass.do_work()
        response = Response(result, status=status.HTTP_200_OK)
        return response

Your urls.py:

from MyProject.MyApp.views import MyRESTView
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    # this URL passes resource_id in **kw to MyRESTView
    url(r'^api/v1.0/resource/(?P<resource_id>\d+)[/]?$', login_required(MyRESTView.as_view()), name='my_rest_view'),
    url(r'^api/v1.0/resource[/]?$', login_required(MyRESTView.as_view()), name='my_rest_view'),
)

This code should output a list of lists when you access http://example.com/api/v1.0/resource/?format=json. If using a suffix, you can substitute ?format=json with .json. You may also specify the encoding you wish to get back by adding "Content-type" or "Accept" to the headers.

[
  [
    1, 
    2, 
    3
  ], 
  [
    4, 
    5, 
    6
  ]
]

Hope this helps you out.

这篇关于Django REST框架:非模型序列化程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆