我是Django REST框架的初学者,需要你的建议。我正在开发一个web服务。服务必须提供到其他服务的REST接口。我需要实现的REST接口并不直接使用我的模型(我指的是get、put、post、delete操作)。相反,它为其他服务提供了一些计算结果。在请求时,我的服务进行一些计算并返回结果(不将结果存储在自己的数据库中)。
下面是我对REST接口如何实现的理解。如果我错了,请纠正我。
- Params necessary for the calculations are passed to the constructor.
- Implement the calc operation. It returns results as '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.
用于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).
- 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).
- 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.
我错过了什么吗?这种方法总体上是正确的吗?
发布于 2012-11-29 19:05:25
Django-rest-framework运行良好,即使不将其绑定到模型也是如此。你的方法听起来不错,但我相信你可以减少一些步骤,让一切都正常工作。
例如,rest框架附带了一些内置的渲染器。开箱即用,它可以向API使用者返回JSON和XML。您还可以通过安装所需的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):
# 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
REST视图:
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
您的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'),
)
当您访问http://example.com/api/v1.0/resource/?format=json时,此代码应该会输出一个列表列表。如果使用后缀,可以用.json
替换?format=json
。您还可以通过将"Content-type"
或"Accept"
添加到标头来指定您希望返回的编码。
[
[
1,
2,
3
],
[
4,
5,
6
]
]
希望这能帮到你。
https://stackoverflow.com/questions/13603027
复制相似问题