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:

class MyView(MethodView):
    def get(self):
        return "Hello word"


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!"

Answered By – Atterratio

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More