Implementation of modular applications in lightweight Web framework Flask and web framework flask

Source: Internet
Author: User

Implementation of modular applications in lightweight Web framework Flask and web framework flask

Flask is a lightweight Web framework. Although it is lightweight, it can also be implemented for a large-scale modular application of components. The "blueprint" is such an implementation. The implementation of modular applications is designed in Flask 0.2. This article does not provide a detailed introduction to the "Blueprint" for the time being, but starts with the implementation of the Module class in version 0.2. In fact, the implementation of the "Blueprint" is very similar to that of the Module class.

Why implement modular Application

For large applications, the scale of the entire application will also expand with the increasing number of features. The different parts of the application are modularized according to certain rules, which not only makes the entire application logic clear, but also easy to maintain. For example, in Flask, you may imagine building a simple project as follows:

/myapplication  /__init__.py  /views    /__init__.py    /admin.py    /frontend.py

In the above directory structure, we changed the previous Flask single file to an application package. All view functions are under views, and the functions are divided into admin and frontend. To build this modular application, Flask implements the Module class in version 0.2. This type of instance can be registered and added to the application after the Flask application is created.

The Module class implements a series of methods:

• Route (rule, ** options)
• Add_url_rule (rule, endpoint, view_func = None, ** options)
• Before_request (f)
• Before_app_request (f)
• After_request (f)
• After_app_request (f)
• Context_processor (f)
• App_context_processor (f)
• _ Record (func)

In addition to add_url_rule and _ record, the above methods can be used as decorators in their own modules. All of these decorators return a function. By calling the _ record method, you can put the function returned by the decorator into _ register_events. After the Flask application is created, you can register this module to the application by running the function in the _ register_events list.

How can a Flask application register a Module?

The following example shows how the Flask application registers a Module.

1. Project Structure

The project structure of this simple example is as follows:

/myapplication  /__init__.py  /app.py  /views    /__init__.py    /admin.py    /blog.py

The code for the admin. py and blog. py modules is as follows:

# admin.pyfrom flask import Moduleadmin = Module(__name__)@admin.route('/')def index():  return "This is admin page!"@admin.route('/profile')def profile():  return "This is profile page."
# blog.pyfrom flask import Moduleblog = Module(__name__)@blog.route('/')def index():  return "This is my blog!"@blog.route('/article/<int:id>')def article(id):  return "The article id is %d." % id

In the above two modules, we first create a Module class, and then add some rules for each Module just like writing a common view function. After that, you can introduce these modules when creating the Flask application, and then register them.

# app.pyfrom flask import Flaskfrom views.admin import adminfrom views.blog import blogapp = Flask(__name__)@app.route('/')def index():  return "This is my app."app.register_module(blog, url_prefix='/blog')app.register_module(admin, url_prefix='/admin')if __name__ == '__main__':  from werkzeug.serving import run_simple  run_simple('localhost', 5000, app)

In app. py:

• We first introduced two Module objects: admin and blog;
• Then, we created a Flask app and added a view function to the app;
• To register the module, we call the register_module method of the application;
• Finally, from werkzeug. serving, we call the run_simple method to create a local server for testing the Flask application.

Based on the above steps, we can test this application. You can access the blog and admin modules by prefix with/blog and/admin respectively.

2. What happened when the Module was registered?

Based on the preceding example, you can register a Module by simply calling the register_module method of the Flask application. The code for the register_module method is as follows:

def register_module(self, module, **options):  """Registers a module with this application. The keyword argument  of this function are the same as the ones for the constructor of the  :class:`Module` class and will override the values of the module if  provided.  """  options.setdefault('url_prefix', module.url_prefix)  state = _ModuleSetupState(self, **options)  for func in module._register_events:    func(state)

The code above shows that:
• You can add url_prefix to differentiate different modules, which we can see when the app registers for admin and blog;
• During registration, we created a _ ModuleSetupState class, which receives Flask applications and some parameters to generate a state instance. This instance reflects the status of the current Flask application.
• When talking about the Module class, we mentioned that some function implementations of the Module will be placed in the _ register_events list when the Module is not registered. These functions are implemented in the form of functions. When registering a module to an application, you only need to pass the parameter about the application information, that is, the state instance above. In this way, you can bind some attributes to the current application by running the function.

In the preceding example, when binding URLs of different modules, the app is registered to form the following URL "map ":

>>> app.url_mapMap([<Rule '/admin/profile' (HEAD, GET) -> admin.profile>,   <Rule '/admin/' (HEAD, GET) -> admin.index>,   <Rule '/blog/' (HEAD, GET) -> blog.index>,   <Rule '/' (HEAD, GET) -> index>,   <Rule '/blog/article/<id>' (HEAD, GET) -> blog.article>,   <Rule '/static/<filename>' (HEAD, GET) -> static>]  )>>> app.url_map._rules_by_endpoint{'admin.index': [<Rule '/admin/' (HEAD, GET) -> admin.index>], 'admin.profile': [<Rule '/admin/profile' (HEAD, GET) -> admin.profile>], 'blog.article': [<Rule '/blog/article/<id>' (HEAD, GET) -> blog.article>], 'blog.index': [<Rule '/blog/' (HEAD, GET) -> blog.index>], 'index': [<Rule '/' (HEAD, GET) -> index>], 'static': [<Rule '/static/<filename>' (HEAD, GET) -> static>]}>>> app.view_functions{'admin.index': <function views.admin.index>, 'admin.profile': <function views.admin.profile>, 'blog.article': <function views.blog.article>, 'blog.index': <function views.blog.index>, 'index': <function __main__.index>}

In this way, you can put the URL rules of different modules together and form a corresponding relationship between the endpoint and the view function. For URL Processing in the Flask application, see URL Processing in the Flask application.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.