Created
August 15, 2012 15:54
-
-
Save davbo/3361172 to your computer and use it in GitHub Desktop.
Content negotiation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import Blueprint | |
from .helpers import template_or_json | |
from .views import ServiceView, register_mimetype | |
places = Blueprint('places', __name__, template_folder='templates') | |
@places.route('/') | |
@template_or_json('places/search.html') | |
def search(): | |
return {'places': [{'name': 'the place'}]} | |
class Search(ServiceView): | |
@register_mimetype('*/*') | |
@register_mimetype('text/html') | |
def as_html(self): | |
# With 2 mimetypes! | |
return "HTML" | |
@register_mimetype('application/json') | |
def as_json(self): | |
return "JSON" | |
places.add_url_rule('/foo', view_func=Search.as_view('foo')) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask.views import View | |
from flask import request | |
from collections import defaultdict | |
def register_mimetype(mimetype): | |
def wrapper(f): | |
mimetypes = getattr(f, 'mimetypes', []) | |
mimetypes.append(mimetype) | |
mimetypes = setattr(f, 'mimetypes', mimetypes) | |
return f | |
return wrapper | |
class ServiceView(View): | |
def __init__(self, *args, **kwargs): | |
self.service_responses = defaultdict(list) | |
for attr in dir(self): | |
attr = getattr(self, attr) | |
mimetypes = getattr(attr, 'mimetypes', []) | |
for mt in mimetypes: | |
self.service_responses[mt] = attr | |
super(ServiceView, self).__init__(*args, **kwargs) | |
def dispatch_request(self): | |
for mt in request.accept_mimetypes.values(): | |
if mt in self.service_responses: | |
return self.service_responses[mt]() | |
@register_mimetype('text/html') | |
def as_html(self): | |
raise NotImplementedError() | |
@register_mimetype('application/json') | |
def as_json(self): | |
raise NotImplementedError() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment