Using a decorator function defined as an instance variable

(Although this question specifically refers to Flask, it can be summarized according to the title)

I am trying to use the Flask decorator app.route() inside the class. However, the Flask application is initialized as an instance variable, i.e. self.server installed in the application. This means that I cannot use the decorator, since self undefined is outside the decorated method. I would like to be able to do the following:

 class MyClass: def __init__(self): self.server = Flask(__name__) @self.server.route('/') def home(): return '<h1>Success</h1>' 

Are there any problems for this problem? Any help is much appreciated!

+6
source share
3 answers

You can define a function in the context of the __init__ method. Then, so that the function can be called normally, set the home member to it.

 class MyClass: def __init__(self): self.server = Flask(__name__) # This is indented at __init__ level, so a new instance of the function # is defined every time __init__ runs. That means a new instance # is defined for each instance of the class, and so it can be wrapped with # the instance "self" value. @self.server.route('/') def home_func(): return '<h1>Success</h1>' # Then, you make it an object member manually: self.home = home_func 
+2
source

Instead of using the route() decorator, you should use the add_url_rule method of the self.server object, for example:

 class MyClass: def __init__(self): self.server = Flask(__name__) self.server.add_url_rule('/', 'home', self.home) self.server.add_url_rule('/route-1', 'route-1', self.route_1) self.server.add_url_rule('/route-2', 'route-2', self.route_2) def home(): return '<h1>Success</h1>' def route_1(): ... def route_2(): ... 

This template allows you to define route handlers as class methods, and it is much easier to read, since you can see all your URL rules in one block.

+3
source

I'm not sure what your common use case is, but you might be better off if you don't embed the application object in the class and use Flask Pluggable Views instead. This will allow you to clearly define your views as classes that inherit from flask.views.View. Example:

 import flask import flask.views class MyClass(flask.views.View): def dispatch_request(self): return '<h1>Success</h1>' app.add_url_rule('/test', view_func=MyClass.as_view('home')) 

This is certainly more code, given a small example, but it gives you more flexibility to define other classes or functions with their own routes, and perhaps instead considers MethodViews, which provide a good structure for defining several HTTP methods and binding them to one class.

+2
source

Source: https://habr.com/ru/post/1013409/


All Articles