Django REST风格接口实现匿名访问

Django REST风格接口实现匿名访问

Piston通过handler将资源与models进行映射。Resource必须是一个类,通常情况下,Resource要实现下列四个方法中的一个或多个:

read:

GET动作调用,获取对象而不做数据修改(该方法是幂等的)

create:

POST动作调用,创建新对象()并返回该对象()(或是返回rc.CREATED.)

update:

PUT动作调用,更新某个已存在的对象并返回该对象(或是返回rc.ALL_OK.)

delete:

DELETE动作调用,删除某个已存的对象,只返回rc.DELETED

实现代码如下:

其结构图为:

urls.py

settings.py

myapp/

__init__.py

views.py

models.py

api/

__init__.py

urls.py

handlers.py

重要部分源码模板为:

handers.py

#!/usr/bin/python
# -*- coding: utf-8 -*-
#filename : handers.py

from django.core.context_processors import request
from django.db.models.query_utils import Q
from piston.handler import AnonymousBaseHandler, BaseHandler
from piston.utils import rc, require_mime, require_extended


class AnonymousMyPistonHandler(AnonymousBaseHandler):
    """某某接口"""
    #只允许为GET请求
    allowed_methods = ('GET','POST','PUT','DELETE')

    @classmethod
    def resource_uri(cls, ddt_login):
        return ('ddt_login', ['json', ])

    #处理GET请求
    def read(self,request):


    #处理POST请求
    @throttle(5, 10*60)     #表示10分钟调用5次
    def create(self,request):
        pass
    
    #处理PUT请求
    def update(self,request):
        pass
    
    #处理DELETE请求
    def delete(self,request):
        pass
    
#接口 支持匿名的方法处理
class MyPistonHandler(BaseHandler):
    anonymous = AnonymousMyPistonHandler


url.py:

#!/usr/bin/python
# -*- coding: utf-8 -*-
#filename : urls.py


from django.conf.urls.defaults import *
from piston.resource import Resource
from piston.authentication import HttpBasicAuthentication

from blogserver.api.handlers import MyPistonHandler

auth = HttpBasicAuthentication(realm='My sample API')

piston_api = Resource(handler=MyPistonHandler, authentication=auth)

urlpatterns = patterns('',
    url(r'^api/$', piston_api),
)


参考文档:http://django-piston-03dev.readthedocs.org/en/latest/documentation.html#documentation

你可能感兴趣的:(Django REST风格接口实现匿名访问)