python plug Flask- view lazy loading decorator

Flask commonly used decorator. Decorator easy to use, as long as the URL in front of the corresponding function on it. However, this approach has one drawback: the decorator code must be introduced in advance, otherwise Flask can not really find your function.

When you have to quickly import application, which will become a problem. In the Google App Engine or other systems, you must quickly import applications. So, if your applications have this problem, you must use the centralized URL mapping.

add_url_rule() URL mapping function for centralized, and the decorator difference is that you need a specialized application of all URL file settings.

Into centrally URL mapping

Suppose 111.py applied as follows:

from flask import Flask
app = Flask(__name__) @app.route('/') def index(): pass @app.route('/user/<username>') def user(username): pass 

In order to focus the mapping, we create a file without using a decorator (  views.py  ):

def index():
    pass

def user(username): pass 

In 111.py mapping function and centralized file URL:

from flask import Flask
from yourapplication import views app = Flask(__name__) app.add_url_rule('/', view_func=views.index) app.add_url_rule('/user/<username>', view_func=views.user) 

Delayed loading

At this point, we just view and routing separation, but the module is pre-loaded with. The ideal way is to load the view on demand. Here we use an auxiliary function similar to a class-demand load:

from werkzeug import import_string, cached_property class LazyView(object): def __init__(self, import_name): self.__module__, self.__name__ = import_name.rsplit('.', 1) self.import_name = import_name @cached_property def view(self): return import_string(self.import_name) def __call__(self, *args, **kwargs): return self.view(*args, **kwargs) 

The most important is the example set correctly  __module__  and  __name__  , it is used correctly named URL rules without providing URL rules.

Then this can centrally define URL rules:

from flask import Flask
from yourapplication.helpers import LazyView app = Flask(__name__) app.add_url_rule('/', view_func=LazyView('yourapplication.views.index')) app.add_url_rule('/user/<username>', view_func=LazyView('yourapplication.views.user')) 

Can be further optimized code: Write a function call  add_url_rule() , the prefix plus the application and point symbols:

def url(url_rule, import_name, **options): view = LazyView('yourapplication.' + import_name) app.add_url_rule(url_rule, view_func=view, **options) url('/', 'views.index') url('/user/<username>', 'views.user') 

One thing to keep in mind: Before request and the request processor must import before the first request.

Guess you like

Origin www.cnblogs.com/dingjiaoyang/p/10985390.html