Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How use flask route with class based view?

Django style Class Based Views cool and powerful feature. But Flask style routers more suitable to the free style of app structure. How can I do something like this:

@app.route("/")
class MyView(MethodView):
    def get(self):
        return "Hello word"
like image 834
Atterratio Avatar asked Jun 01 '26 17:06

Atterratio


2 Answers

from flask documentation(https://flask.palletsprojects.com/en/1.1.x/views/):

from flask.views import View

class ShowUsers(View):
    def dispatch_request(self):
        users = User.query.all()
        return render_template('users.html', objects=users)

app.add_url_rule('/users/', view_func=ShowUsers.as_view('show_users'))

the last string converts to the function and does registration(@app.route(...)) to the app

like image 171
burney Avatar answered Jun 03 '26 05:06

burney


I could not find such feature in the official flask documentation. And also I did not find any solution on the internet or a similar question at Stack Overflow, so I prepared a snippet for this case.

import types

from flask import Blueprint
from flask.views import MethodView


# decorator code
def class_route(self, rule, endpoint, **options):
    """
    This decorator allow add routed to class view.
    :param self: any flask object that have `add_url_rule` method.
    :param rule: flask url rule.
    :param endpoint: endpoint name
    """

    def decorator(cls):
        self.add_url_rule(rule, view_func=cls.as_view(endpoint), **options)
        return cls

    return decorator

    # Usage
    # I use `Blueprint` and `MethodView`, but it should work correct with `App` and `View` to.


bp = Blueprint("bp", __name__, template_folder="templates")


@class_route(bp, "/", "my_view")
class MyView(MethodView):
    def get(self):
        return "Hello world"


# Advanced usage
# Add decorator as class method
bp.class_route = types.MethodType(class_route, bp)


# And use is as bultin decorator
@bp.class_route("/advanced", "advanced_my_view")
class AdvancedMyView(MethodView):
    def get(self):
        return "Hello world!"
like image 43
Atterratio Avatar answered Jun 03 '26 07:06

Atterratio