Django API:输出文件 提供下载
Piston写的Handler:
1. 简历j_handler类,继承Piston的BaseHandler。
2. model为文件的model
3. def 方法def read(self,request,sub_module)
4. 处理(公司内部文件,不贴了)
5. 提供文件下载:
data=json.dumps(li,indent=4,sort_keys=True) response = HttpResponse(data,mimetype='application/octet-stream') response['Content-Disposition'] = 'attachment; filename=%s' % "Vieri.json" return response
Piston写的Authentication:
1. 在urls.py里操作
2. from piston.authentication import HttpBasicAuthentication
3. 基本的Authentication
auth = HttpBasicAuthentication(realm="Download report")
authhandler = Resource(j_handler, authentication=auth)
4. 将authhandler整合到url中
Piston写的防止Csrf Authentication:
代码:
用Piston写的handler,resource只是一个类,定义的方法何时call取决于用户请求
Piston lets you map resource to models, and by doing so, it will do a lot of the heavy lifting for you.
A resource can be just a class, but usually you would want to define at least 1 of 4 methods:
read
is called on GET requests, and should never modify data (idempotent.)
create
is called on POST, and creates new objects, and should return them (or rc.CREATED.)
update
is called on PUT, and should update an existing product and return them (or rc.ALL_OK.)
delete
is called on DELETE, and should delete an existing object. Should not return anything, just rc.DELETED.
handler 基本代码:
from piston.handler import BaseHandler from myapp.models import Blogpost class BlogpostHandler(BaseHandler): allowed_methods = ('GET',) model = Blogpost def read(self, request, post_slug): ...
mapping到urls.py
from django.conf.urls.defaults import * from piston.resource import Resource from mysite.myapp.api.handlers import BlogpostHandler blogpost_handler = Resource(BlogpostHandler) urlpatterns = patterns('', url(r'^blogpost/(?P<post_slug>[^/]+)/', blogpost_handler), url(r'^blogposts/', blogpost_handler), )
https://bitbucket.org/jespern/django-piston/wiki/Documentation#!resources
https://bitbucket.org/jespern/django-piston/wiki/Documentation#!mapping-urls
class CsrfExemptResource( Resource ): def __init__( self, handler, authentication = None ): super( CsrfExemptResource, self ).__init__( handler, authentication ) self.csrf_exempt = getattr( self.handler, 'csrf_exempt', True ) handler = CsrfExemptResource( j_handler)