Reputation: 29
Why are we passing flask.views.MethodView
in the class?
app.add_url_rule
> in this snippet, add_url_rule
is this something predefined property?
Similarly view_func
, View.as_view
> are they predefined?
import flask, flask.views
app = flask.Flask(__name__)
class View(flask.views.MethodView):
def get(self):
return "Hello World!"
app.add_url_rule('/',view_func=View.as_view('main'))
app.debug = True
app.run()
Upvotes: 0
Views: 3108
Reputation: 1121654
View
is a subclass of the flask.views.MethodView
class. The latter provides base functionality, like the as_view()
method:
Converts the class into an actual view function that can be used with the routing system. Internally this generates a function on the fly which will instantiate the View on each request and call the
dispatch_request()
method on it.
Also see Pluggable Views.
Because this is not a function-based view, you cannot use the @app.route()
decorator on it. You use the alternative app.add_url_rule()
method instead in that case:
Connects a URL rule. Works exactly like the
route()
decorator. If aview_func
is provided it will be registered with the endpoint.
view_func
is a documented keyword argument for this method; when the registered path is requested (in your example /
), then whatever as_view()
returned is called by Flask. That in turn calls dispatch_request()
, which then calls the View().get()
method if the HTTP request used a GET method.
Upvotes: 4