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