tastypie能用于作为Django项目中的接口,开发时候很方便。
class CartResource(Resource):
class Meta:
resource_name = 'cart'
object_class = object
allowed_methods = ['post']
authentication = SiteUserAuthentication()
validation = FormValidation(form_class=GetCartForm)
def get_list(self, request, **kwargs):
return self.create_response(request, req)
def post_list(self, request, **kwargs):
return self.create_response(request, req)
allowed_methods是标明该api的url的限制,默认就['get', 'post', 'put', 'delete', 'patch'],一般会有限制。
get对应get_list方法,post对应post_list方法,经常要对这两个方法中的req进行复制,req是返回的数据,默认是json类型,
所以req的内容是json的格式,如req = {'status':True,'id'=1}。
其中create_response看源代码,可以知道这方法返回时一个HttpResponse,那么可以在酱紫。
def create_response(self, *args, **kwargs):
response = super(AutoResource, self).create_response(*args, **kwargs)
response['Access-Control-Allow-Origin'] = '*'
response['Access-Control-Allow-Headers'] = 'Content-Type'
response['Access-Control-Allow-Methods'] = 'OPTIONS,GET,POST'
return response
重写这个方法,在HttpResponse类的response对象中可以对header等一些地方做小动作。
authentication可以对用户的验证,默认是Django中的User类,如果有自己创建的用户,可以参照源代码中进行小修改,
该验证是读该api的http中的header,Django中http的header是request.META.
validation可以对post的json内容进行验证,用form表单的类进行验证。
里面的bundle是一个很重要的对象,这是生成bundle的源代码
def build_bundle(self, obj=None, data=None, request=None, objects_saved=None):
"""
Given either an object, a data dictionary or both, builds a ``Bundle``
for use throughout the ``dehydrate/hydrate`` cycle.
If no object is provided, an empty object from
``Resource._meta.object_class`` is created so that attempts to access
``bundle.obj`` do not fail.
"""
if obj is None and self._meta.object_class:
obj = self._meta.object_class()
return Bundle(
obj=obj,
data=data,
request=request,
objects_saved=objects_saved
)
里面有obj,data,request,objects_saved,一般常用有data,request,http里面的body在bundle.data取出,bundle.request和request一样。