Skip to content

Instantly share code, notes, and snippets.

@davbo davbo/places.py
Created Aug 15, 2012

Embed
What would you like to do?
Content negotiation
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'))
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
You can’t perform that action at this time.