Skip to content
Myr

views.rst

This file

Path

docs/views.rst

237 lines · 8.1 KiB

Last changed by

Add simple decorator examplePriit Laesbefore adoptiond18868b

History of this file

Take it

1.. _views:23Pluggable Views4===============56.. versionadded:: 0.778Flask 0.7 introduces pluggable views inspired by the generic views from9Django which are based on classes instead of functions.  The main10intention is that you can replace parts of the implementations and this11way have customizable pluggable views.1213Basic Principle14---------------1516Consider you have a function that loads a list of objects from the17database and renders into a template::1819    @app.route('/users/')20    def show_users(page):21        users = User.query.all()22        return render_template('users.html', users=users)2324This is simple and flexible, but if you want to provide this view in a25generic fashion that can be adapted to other models and templates as well26you might want more flexibility.  This is where pluggable class based27views come into place.  As the first step to convert this into a class28based view you would do this::293031    from flask.views import View3233    class ShowUsers(View):3435        def dispatch_request(self):36            users = User.query.all()37            return render_template('users.html', objects=users)3839    app.add_url_rule('/users/', ShowUsers.as_view('show_users'))4041As you can see what you have to do is to create a subclass of42:class:`flask.views.View` and implement43:meth:`~flask.views.View.dispatch_request`.  Then we have to convert that44class into an actual view function by using the45:meth:`~flask.views.View.as_view` class method.  The string you pass to46that function is the name of the endpoint that view will then have.  But47this by itself is not helpful, so let's refactor the code a bit::4849    50    from flask.views import View5152    class ListView(View):5354        def get_template_name(self):55            raise NotImplementedError()5657        def render_template(self, context):58            return render_template(self.get_template_name(), **context)5960        def dispatch_request(self):61            context = {'objects': self.get_objects()}62            return self.render_template(context)6364    class UserView(ListView):6566        def get_template_name(self):67            return 'users.html'6869        def get_objects(self):70            return User.query.all()7172This of course is not that helpful for such a small example, but it's good73enough to explain the basic principle.  When you have a class based view74the question comes up what `self` points to.  The way this works is that75whenever the request is dispatched a new instance of the class is created76and the :meth:`~flask.views.View.dispatch_request` method is called with77the parameters from the URL rule.  The class itself is instanciated with78the parameters passed to the :meth:`~flask.views.View.as_view` function.79For instance you can write a class like this::8081    class RenderTemplateView(View):82        def __init__(self, template_name):83            self.template_name = template_name84        def dispatch_request(self):85            return render_template(self.template_name)8687And then you can register it like this::8889    app.add_url_rule('/about', view_func=RenderTemplateView.as_view(90        'about_page', template_name='about.html'))9192Method Hints93------------9495Pluggable views are attached to the application like a regular function by96either using :func:`~flask.Flask.route` or better97:meth:`~flask.Flask.add_url_rule`.  That however also means that you would98have to provide the names of the HTTP methods the view supports when you99attach this.  In order to move that information to the class you can100provide a :attr:`~flask.views.View.methods` attribute that has this101information::102103    class MyView(View):104        methods = ['GET', 'POST']105106        def dispatch_request(self):107            if request.method == 'POST':108                ...109            ...110111    app.add_url_rule('/myview', view_func=MyView.as_view('myview'))112113Method Based Dispatching114------------------------115116For RESTful APIs it's especially helpful to execute a different function117for each HTTP method.  With the :class:`flask.views.MethodView` you can118easily do that.  Each HTTP method maps to a function with the same name119(just in lowercase)::120121    from flask.views import MethodView122123    class UserAPI(MethodView):124125        def get(self):126            users = User.query.all()127            ...128129        def post(self):130            user = User.from_form_data(request.form)131            ...132133    app.add_url_rule('/users/', view_func=UserAPI.as_view('users'))134135That way you also don't have to provide the136:attr:`~flask.views.View.methods` attribute.  It's automatically set based137on the methods defined in the class.138139Decorating Views140----------------141142Since the view class itself is not the view function that is added to the143routing system it does not make much sense to decorate the class itself.144Instead you either have to decorate the return value of145:meth:`~flask.views.View.as_view` by hand::146147    def user_required(f):148        """Checks whether user is logged in or raises error 401."""149        def decorator(*args, **kwargs):150            if not g.user:151                abort(401)152            return f(*args, **kwargs)153        return decorator154155    view = user_required(UserAPI.as_view('users'))156    app.add_url_rule('/users/', view_func=view)157158Starting with Flask 0.8 there is also an alternative way where you can159specify a list of decorators to apply in the class declaration::160161    class UserAPI(MethodView):162        decorators = [user_required]163164Due to the implicit self from the caller's perspective you cannot use165regular view decorators on the individual methods of the view however,166keep this in mind.167168Method Views for APIs169---------------------170171Web APIs are often working very closely with HTTP verbs so it makes a lot172of sense to implement such an API based on the173:class:`~flask.views.MethodView`.  That said, you will notice that the API174will require different URL rules that go to the same method view most of175the time.  For instance consider that you are exposing a user object on176the web:177178=============== =============== ======================================179URL             Method          Description180--------------- --------------- --------------------------------------181``/users/``     ``GET``         Gives a list of all users182``/users/``     ``POST``        Creates a new user183``/users/<id>`` ``GET``         Shows a single user184``/users/<id>`` ``PUT``         Updates a single user185``/users/<id>`` ``DELETE``      Deletes a single user186=============== =============== ======================================187188So how would you go about doing that with the189:class:`~flask.views.MethodView`?  The trick is to take advantage of the190fact that you can provide multiple rules to the same view.191192Let's assume for the moment the view would look like this::193194    class UserAPI(MethodView):195196        def get(self, user_id):197            if user_id is None:198                # return a list of users199                pass200            else:201                # expose a single user202                pass203204        def post(self):205            # create a new user206            pass207208        def delete(self, user_id):209            # delete a single user210            pass211212        def put(self, user_id):213            # update a single user214            pass215216So how do we hook this up with the routing system?  By adding two rules217and explicitly mentioning the methods for each::218219    user_view = UserAPI.as_view('user_api')220    app.add_url_rule('/users/', defaults={'user_id': None},221                     view_func=user_view, methods=['GET',])222    app.add_url_rule('/users/', view_func=user_view, methods=['POST',])223    app.add_url_rule('/users/<int:user_id>', view_func=user_view,224                     methods=['GET', 'PUT', 'DELETE'])225226If you have a lot of APIs that look similar you can refactor that227registration code::228229    def register_api(view, endpoint, url, pk='id', pk_type='int'):230        view_func = view.as_view(endpoint)231        app.add_url_rule(url, defaults={pk: None},232                         view_func=view_func, methods=['GET',])233        app.add_url_rule(url, view_func=view_func, methods=['POST',])234        app.add_url_rule('%s<%s:%s>' % (url, pk_type, pk), view_func=view_func,235                         methods=['GET', 'PUT', 'DELETE'])236237    register_api(UserAPI, 'user_api', '/users/', pk='user_id')