From d9e7042f1a7c8944af82972f836a80a54e1e58f2 Mon Sep 17 00:00:00 2001 From: Jesper Noehr Date: Thu, 7 May 2009 16:49:04 +0200 Subject: [PATCH] adding @require_mime decorator and @require_extended as well --- examples/blogserver/api/handlers.py | 3 ++- piston/utils.py | 38 ++++++++++++++++++++++++++--- 2 files changed, 36 insertions(+), 5 deletions(-) diff --git a/examples/blogserver/api/handlers.py b/examples/blogserver/api/handlers.py index b468861..058cba7 100644 --- a/examples/blogserver/api/handlers.py +++ b/examples/blogserver/api/handlers.py @@ -1,5 +1,5 @@ from piston.handler import BaseHandler, AnonymousBaseHandler -from piston.utils import rc +from piston.utils import rc, require_mime, require_extended from blogserver.blog.models import Blogpost @@ -16,6 +16,7 @@ class BlogpostHandler(BaseHandler): def content_length(self, blogpost): return len(blogpost.content) + @require_extended def create(self, request): if request.content_type: print request.data diff --git a/piston/utils.py b/piston/utils.py index 9f770fc..439283a 100644 --- a/piston/utils.py +++ b/piston/utils.py @@ -140,6 +140,9 @@ class Mimer(object): if ctype in mimes: return loadee + def content_type(self): + return self.request.META.get('CONTENT_TYPE') + def translate(self): """ Will look at the `Content-type` sent by the client, and maybe @@ -152,9 +155,9 @@ class Mimer(object): It will also set `request.mimetype` so the handler has an easy way to tell what's going on. `request.mimetype` will always be None for multipart form data (what your browser sends.) - """ - ctype = self.request.META.get('CONTENT_TYPE') - + """ + ctype = self.content_type() + if not self.is_multipart() and ctype: loadee = self.loader_for_type(ctype) @@ -181,5 +184,32 @@ class Mimer(object): return cls.TYPES.pop(loadee) def translate_mime(request): - request = Mimer(request).translate() + request = Mimer(request).translate() + +def require_mime(*mimes): + """ + Decorator requiring a certain mimetype. There's a nifty + helper called `require_extended` below which requires everything + we support except for post-data via form. + """ + @decorator + def wrap(f, self, request, *args, **kwargs): + m = Mimer(request) + realmimes = set() + + rewrite = { 'json': 'application/json', + 'yaml': 'application/x-yaml', + 'xml': 'text/xml', + 'pickle': 'application/python-pickle' } + + for idx, mime in enumerate(mimes): + realmimes.add(rewrite.get(mime, mime)) + + if not m.content_type() in realmimes: + return rc.BAD_REQUEST + + return f(self, request, *args, **kwargs) + return wrap + +require_extended = require_mime('json', 'yaml', 'xml', 'pickle') \ No newline at end of file