django-Tastypie(1)

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一样。


转载于:https://my.oschina.net/sola1993/blog/495236

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值