Django-睡觉-框架运行良好,即使不将其与模型Bundle 在一起.你的方法听起来不错,但我相信你可以减少一些步骤,让一切都运转起来.
例如,睡觉框架附带了一些内置渲染器.它可以开箱即用地将JSON和XML返回给API使用者.您还可以通过只安装所需的python模块来启用YAML.django-睡觉-framework可以输出任何基本对象,如dict、list和tuple,不需要您做任何额外的工作.
因此,基本上您只需创建接受参数的函数或类,执行所有必需的计算,并将其结果以元组形式返回给睡觉API视图.如果json和/或xml满足您的需要,django-睡觉-framework将为您处理序列化.
在本例中,您可以跳过第2步和第3步,只使用一个类进行计算,并使用一个类向API使用者呈现.
以下是一些可能对您有所帮助的片段:
Please note that I have not tested this. It's only meant as an example, but it should work :)
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
其余视图:
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
来替身.您还可以通过将"Content-type"
或"Accept"
添加到标头来指定您希望返回的编码.
[
[
1,
2,
3
],
[
4,
5,
6
]
]
希望这能帮到你.