With the help offind_modules.import_stringGracefully register blueprint modules

The functions find_modules and import_string are included in the Werkzeug. utils toolkit. These two utility functions can help you gracefully register blueprint modules for your application, especially if there are many blueprint modules in your project. It saves a lot of lines of code and looks a lot more comfortable.

import_string(import_name, silent=False)

Import_string Exports modules or objects to be imported using a string:

parameter

  • Import_name: specifies the module or object name of the object to be imported
  • Silent: If set to True, import errors are ignored and None is returned

find_modules(import_path, include_packages=False, recursive=False)

Find all modules under a package, which is useful for automatically importing all blueprint modules

parameter

  • Import_path: indicates the package path
  • Include_packages: If set to True, subpackages within a package are returned
  • Recursive: Whether to search subpackages recursively

The sample code

blueprints/example.py

# Module part
# create blueprint :)
bp = Blueprint('bp_name', __name__)

Copy the code

app.py

# register
def register_blueprints(app):
    """Register all blueprint modules"""
    for name in find_modules('blueprints'):
        module = import_string(name)
        if hasattr(module, 'bp'):
            app.register_blueprint(module.bp)
    return None
Copy the code

Use the Flash memory in the Flask to pass feedback

Flask’s flash memory system is mainly used to provide feedback to users. The content generally gives feedback on the user’s last request. The feedback information is stored on the server, and the user can access the previous feedback information in this (and only this) request. When the user receives the feedback information, the server deletes it. Flask opens a get_flashed_messages(with_categories=False, category_filter=[]) function for Jinja2 to retrieve the last flash memory information, which can be used directly in the template.

parameter

  • With_categories: True returns the primitive ancestor, False returns the message itself
  • Category_filter: Filter category keyword (string or list)

The flash(message, category=’message’) function is used to save a feedback message for the next request when it is ready to return.

parameter

  • “Message” : message text
  • Category: user-defined category keyword

Official sample code

Use the Flask built-in logging system to send error log emails

Flask uses Python’s built-in logging system, which can actually send error emails.

Sample code:

ADMINS = ['[email protected]']
if not app.debug:
    import logging
    from logging.handlers import SMTPHandler
    mail_handler = SMTPHandler('127.0.0.1'.# mail server
                               '[email protected]'.# the sender
                               ADMINS, # the recipient
                               'YourApplication Failed') # Email subject
    mail_handler.setLevel(logging.ERROR)
    app.logger.addHandler(mail_handler)
Copy the code

You can go one step further and format the error log for easy reading:

from logging import Formatter
mail_handler.setFormatter(Formatter(''' Message type: %(levelname)s Location: %(pathname)s:%(lineno)d Module: %(module)s Function: %(funcName)s Time: %(asctime)s Message: %(message)s '''))
Copy the code

For an introduction to SMTPHandler, visit the SMTPHandler manual on the official website

Preinterrupt requests return error codes and customize the corresponding error pages

In Flask we can use the redirect() function to redirect users to other places. You can also use the abort() function to prematurely interrupt a request with an error code.

The sample code

from flask import abort, redirect, url_for

@app.route('/')
def index(a):
    return redirect(url_for('login'))

@app.route('/login')
def login(a):
    abort(404)
    this_is_never_executed() # will never be executed
Copy the code

Customize your own error interface with the ErrorHandler () decorator supplied by Flask

from flask import render_template

@app.errorhandler(404)
def page_not_found(error):
    return render_template('page_not_found.html'), 404
Copy the code

Notice that 404 comes after render_template(). Flask is told that the error code for the page should be 404, that is, not found. ` `

Original link: vimiix.com/post/2017/1…