Django的HTTP rest工具包
django-restlayer的Python项目详细描述
简介
django restlayer是一个非常简单的工具包,可以使用它为django项目创建restfulapi。 或应用程序。
功能
- 允许您尊重应用程序中的http方法和头。
- 基于类的资源。
- 代码简单。
- 表单验证以备需要。
安装
- 对于django 1.4:pip install django-restlayer==0.8.5
- 对于django 1.5+:pip install django-restlayer
配置
django restlayer不需要任何配置,也不需要INSTALLED_APPS设置中的任何应用程序。
简单示例
网址.py:
from django.conf.urls import patterns, url urlpatterns = patterns('', url(r'^$', 'myapp.resources.simple', name='simple'), )
myapp/resources.py:
from restlayer import Resource, Response # Our resource class class SimpleResponse(Response): def response_get(self, request): return ['foo', 'bar'] # Resource (a callable object or a view if you prefer) simple = Resource(SimpleResponse)
就这样。现在,查询您的开发服务器
curl -s -v -H "accept:application/json" http://localhost:8000/ > GET /api/ HTTP/1.1 > User-Agent: curl/7.33.0 > Host: localhost > accept:application/json > < HTTP/1.1 200 OK < Server: nginx/1.4.3 < Date: Thu, 28 Nov 2013 14:34:15 GMT < Content-Type: application/json; charset=UTF-8 < Transfer-Encoding: chunked < Connection: keep-alive < Vary: Accept-Language, Cookie < Content-Language: en < [ "foo", "bar" ]
用法
响应类
所有响应都应该继承restlayer.Response类。然后,添加名为 response_VERB,其中VERB是http动词。要处理get响应,需要创建 一个response_get方法,用于post,response_post。每个response_VERB方法都充当视图 有必要的论据。一个基本示例:
from restlayer import Response class SimpleResponse(Response): def response_get(self, request, my_id): # This method will match a URL pattern with "my_id" return "foo"
预定义的响应方法
有两种预定义的响应方法:
- response_options返回带有Allow头的空204响应。
- response_head调用response_get如果有,则返回它而不返回body。
序列化程序
您可以设置serializers和deserializers属性。他们设定了数据的格式 序列化(出)或非序列化(入)。在本例中,我们为text/plain添加了一个愚蠢的序列化程序:
class SimpleResponse(Response): serializers = Response.serializers + ( ('text/plain', lambda x: return str(x)) )
好吧,那不太管用,但你有主意。serializers是mime的元组列表 将数据作为唯一参数的类型和可调用项。deserializers与accepted相同 数据类型(callable只接受request作为参数)。
默认格式为:
- serializers
- 应用程序/json
- 应用程序/xml
- 应用程序/python pickle
- deserializers
- 应用程序/x-www-form-urlencoded
- 多部分/窗体数据
- 应用程序/json
响应是有效的httpresponse对象
restlayer.Response实例是有效的django.http.HttpResponse对象。因此您可以:
- 在返回数据之前,将任何想要的头添加到响应设置self['my-header']中;
- 使用self.status_code; 更改状态代码
- 如果需要在不使用序列化程序的情况下设置特定的响应内容,则返回self。
资源
您的响应类应该包装在一个restlayer.Resource类中。结果实例 是一个可调用的行为像一个经典的观点。你可以扩展这个类来创建你自己的资源。 只需重写__call__方法。
from restlayer import Resource class SillyResource(Resource): def __call__(self, request, *args, **kwargs): rsp = super(SillyResource, self).__call__(request, *args, **kwargs) rsp.status_code = 401 rsp['Content-Type'] = 'text/plain' return rsp
django模型的响应
如果您使用的是django模型,那么可以使用restlayer.ModelResponse。使用此父项 类的响应,可以返回模型实例或QuerySet。下面是一个简单的示例:
from django.contrib.auth.models import User from restlayer import ModelResponse class SimpleResponse(ModelResponse): fields = ('id', 'name', 'firstname', 'email') def response_get(self, request): return User.objects.all()
就这样!使用fields属性,设置要在响应中返回的字段。
可以添加自定义方法来创建特定的响应字段。此方法有两个参数: ìnstance和request。示例:
from django.contrib.auth.models import User from restlayer import ModelResponse class SimpleResponse(ModelResponse): fields = ('id', 'name', 'firstname', 'email', 'other_field') def other_field(self, instance, request): return instance.name.capitalize() def response_get(self, request): return User.objects.all()
网址
通常需要创建一个resource_uri字段来指向api中的另一个资源。 Response类提供了两种方法来创建绝对(使用fqdn)URL:
- _build_absolute_uri(self, request, [location])只调用request.build_absolute_uri(location) 但如果需要的话你可以重写它。
- reverse(self, request, view, [args, kwargs])充当django.core.urlresolvers.reverse但是 返回绝对url。
分页
你可能想把你的回答分页。restlayer响应类为 此任务:paginate(self, request, object_list, [limit]),这是一个简单的包装 django.core.paginator.Paginator。结果ing响应将包含以下标题:
- X页对象
- X页计数
- X-页-当前
使用源
我承认这份文件有点粗糙。别犹豫,看看源代码,没有 隐藏的火箭科学,只有一些基本的python代码:)
许可证
django restlayer是在mit许可下发布的。查看许可证 完整许可证的文件。