A, Flask Introduction
Flask is the current popular Web framework that is implemented in Python using its Werkzeug WSGI toolkit template engine is used Jinja2. Flask use BSD license. . Flask notable features: it is a "micro" frame. "Micro" is intended to mean Flask keep it simple core, but at the same time easy to expand. By default, the Flask database abstraction layer does not comprise, form validation, or any other variety of libraries capable of existing functions. However, Flask support to add these features to the application with the extension. Numerous extensions provide database integration, form validation, upload handling, various open authentication and other functions. Flask of these features, making it very popular in Web development.
The two core Flask: Werkzeug and Jinja2
- Werkzeug achieve routing, debugging, and Web Server Gateway Interface
- Jinja2 realized template
Two, Flask installation
pip3 install flask
Common expansion pack:
Flask-SQLalchemy: operation of the database;
Flask-script: insert script;
Flask-migrate: migrate database management;
Flask-Session: Session specified storage;
Flask-WTF: Form;
Flask-Mail: Mail;
Flask-Bable: to provide support for internationalization and localization, translation;
Flask-Login: User Authentication state;
Flask-OpenID: Certification;
Flask-RESTful: the REST API development tools;
Flask-Bootstrap: Twitter Bootstrap integrated front-end frame;
Flask-Moment: localized date and time;
Flask-Admin: simple and extensible framework for the management interface
Third, the basic use of Flask
from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello World!' if __name__ == '__main__': app.run()
. 1 { 2 ' the DEBUG ' : get_debug_flag (default = False), is turned in Debug mode . 3 ' TESTING ' : False, whether to open the test mode . 4 ' PROPAGATE_EXCEPTIONS ' : None, . 5 ' PRESERVE_CONTEXT_ON_EXCEPTION ' : None, . 6 ' of SECRET_KEY ' : None, . 7 ' PERMANENT_SESSION_LIFETIME ' : timedelta (Days 31 is = ), 8 'USE_X_SENDFILE': False, 9 'LOGGER_NAME': None, 10 'LOGGER_HANDLER_POLICY': 'always', 11 'SERVER_NAME': None, 12 'APPLICATION_ROOT': None, 13 'SESSION_COOKIE_NAME': 'session', 14 'SESSION_COOKIE_DOMAIN': None, 15 'SESSION_COOKIE_PATH': None, 16 'SESSION_COOKIE_HTTPONLY': True, 17 'SESSION_COOKIE_SECURE': False, 18 'SESSION_REFRESH_EACH_REQUEST': True, 19 'MAX_CONTENT_LENGTH': None, 20 'SEND_FILE_MAX_AGE_DEFAULT': timedelta(hours=12), 21 'TRAP_BAD_REQUEST_ERRORS': False, 22 'TRAP_HTTP_EXCEPTIONS': False, 23 'EXPLAIN_TEMPLATE_LOADING': False, 24 'PREFERRED_URL_SCHEME': 'http', 25 'JSON_AS_ASCII': True, 26 'JSON_SORT_KEYS': True, 27 'JSONIFY_PRETTYPRINT_REGULAR': True, 28 'JSONIFY_MIMETYPE': 'application/json', 29 'TEMPLATES_AUTO_RELOAD': None, 30 }
A way: the app.config [ ' the DEBUG ' ] = True the PS: Config object because it is essentially a dictionary, it can also be used app.config.update (...) Second way: app.config.from_pyfile ( " Python file name " ) such as: settings.py DEBUG = True app.config.from_pyfile ( " settings.py " ) app.config.from_envvar ( " environment variable name " ) is the name of the file name python environment variable, internal call from_pyfile method app. config.from_json ( " json file name " ) JSON file name must be json format, because the internal performs json.loads app.config.from_mapping ({ ' the DEBUG ' : True}) dictionary format app.config.from_object ( " path python class or type " ) the app.config .from_object ( ' pro_flask.settings.TestingConfig ' ) the settings.py class Config (Object): the DEBUG = False TESTING = False DATABASE_URI = ' SQLite: //: Memory: ' class ProductionConfig (Config): DATABASE_URI = 'mysql://user@localhost/foo' class DevelopmentConfig(Config): DEBUG = True class TestingConfig(Config): TESTING = True
Four, Flask routing system
@app.route('/xxx/<username>') @app.route('/xxx/<int:id>') @app.route('/xxx/<float:id>') @app.route('/xxx/<path:path>') @app.route('/xxx', methods=['GET', 'POST'])
DEFAULT_CONVERTERS = { 'default': UnicodeConverter, 'string': UnicodeConverter, 'any': AnyConverter, 'path': PathConverter, 'int': IntegerConverter, 'float': FloatConverter, 'uuid': UUIDConverter, }
Five, Flask blueprint
"Blueprint" system provides great convenience in the assembly and extend Flask applications. "Component" refers to a Flask applications can be "split" in the layer on Flask, modular management, which greatly simplifies the process of building large-scale applications, but also makes it easier to maintain the application. In addition, the "blueprint" also provides a Flask extension in the application of the registration operation of the core methods.
"Blueprint" and a Flask application object is very similar, but not a Flask application object. It is possible to register a series of operations on a Flask application (for this understanding, mentioned in detail later). Use the "blueprint", you can achieve some of the following features:
- Flask application will "split" into a series of collections "blueprint" of large-scale application simplifies the way to work;
- On the Flask application, a URL or subdomain prefix and registered a blueprint. May be registered more than once a blueprint to a different URL;
- Filter template provided by a blueprint, static files, templates, and other functions.
from blueprint import app_index app.register_blueprint(app_index)
from flask import Blueprint app_index = Blueprint("app_index", __name__, template_folder="templates")