Skip to content

Instantly share code, notes, and snippets.

@davbo davbo/
Created Aug 15, 2012

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')
def search():
return {'places': [{'name': 'the place'}]}
class Search(ServiceView):
def as_html(self):
# With 2 mimetypes!
return "HTML"
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 = 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]()
def as_html(self):
raise NotImplementedError()
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.