(4) Flask - detailed configuration

1. Configuration:

A configuration file in Flask is a flask.config.Config object (inheriting a dictionary). I will analyze the source code later.

basic method:

  1. Setting Configuration Items Directly - Configuration items can be set directly in the application without using configuration files or environment variables. For example, use the following code to set configuration items in your application:
from flask import Flask

app = Flask(__name__)
app.config['DEBUG'] = True
app.config['SECRET_KEY'] = 'GuHanZheIsCool'

At the beginning, the Config object inherits the dictionary, so you can also use app.config.update(…).

  1. Use a configuration file - write all configuration items into a configuration file and import it through the app.config.from_pyfile() method. For example, create a configuration file called config.py at the root of your application, and import the configuration with the following code:
from flask import Flask

app = Flask(__name__)
app.config.from_pyfile('config.py')

Example config.py configuration file:

DEBUG = True
SECRET_KEY = 'GuHanZheIsCool'
DATABASE_URI = 'mysql://user:password@localhost/demodatabase'

  1. Use environment variables - set configuration items in the form of environment variables and import them through the app.config.from_envvar() method. For example, set the environment variable FLASK_CONFIG to the path of the configuration file in the terminal or command line, and then use the following code to import the configuration:
from flask import Flask

app = Flask(__name__)
app.config.from_envvar('FLASK_CONFIG')

  • However, in real development, we will face a problem-generally a project will have three environments: testing, development and production, and the configurations in these three environments will be different, such as different databases, different cookie configurations, etc. . So Flask provides us with a solution that is very suitable for development. as follows:

The method used in real development:

  • Use class configuration - Create a configuration class, use all configuration items as attributes of the class, and import them through the app.config.from_object() method. For example, create a configuration class called Config, then import the configuration with the following code:
from flask import Flask

app = Flask(__name__)
# 配置文件              导入settings.py文件里的DevelopmentConfig类对象里的所有配置项
app.config.from_object("settings.DevelopmentConfig")


@app.route('/index', methods=['GET', 'POST'])
def index():
    return 'hello world'


if __name__ == '__main__':
    app.run('localhost', 4000)
    
  • The settings.py file in the same directory:
import os


class BaseConfig(object):
    """Base Configuration"""

    # Root path of project
    PROJECT_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))

    DEBUG = True
    SECRET_KEY = 'GuHanZheIsCool'
    
    # Redis configuration
    REDIS_URL = os.environ.get("REDIS_URL")
    

    # File setting
    UPLOAD_FILE_FOLDER = "./project/data"    # 上传文件存储路径
    FILE_MAX_SIZE = 30 * 1024 * 1024


class ProductionConfig(BaseConfig):
    """Production Configuration"""
    DEBUG = False


class DevelopmentConfig(BaseConfig):
    """Development Configuration"""
    pass


class TestingConfig(BaseConfig):
    """Testing Configuration"""
    pass

In Flask, a configuration file is usually a Python module that contains values ​​for various Flask configuration options. Here are some basic options that can be set in the Flask configuration file:

  1. DEBUG: Whether to enable debugging mode, if set True, you can see detailed error information and debugging information in the web page. At the same time, it will automatically reload our project - in debug mode, if the application's code changes, the server will automatically reload the application so that the code modification is immediately reflected without manually restarting the server.

  2. SECRET_KEY: secret key is the key required to encrypt cookies in Flask. It is the "seed" of the encryption algorithm to ensure the security of the encryption. It is necessary to ensure that each application has a fixed key, and it is recommended to use a tool that generates a random key to generate one.

  3. SQLALCHEMY_DATABASE_URI: Specifies the URI of the SQLite, MySQL, or PostgreSQL database, indicating the database to connect to.

  4. SQLALCHEMY_TRACK_MODIFICATIONS: Whether to enable SQLAlchemy's tracking modification. The default value is False. To disable tracking modifications, you can set its value to False.

  5. CACHE_TYPE: Cache type, supports SimpleCache, RedisCache and MemcachedCache.

  6. CACHE_DEFAULT_TIMEOUT: The default cache time, in seconds.

  7. SESSION_TYPE: session type, supports Redis, Memcached, Filesystem, etc.

  8. SESSION_COOKIE_NAME: session cookie name.

  9. SESSION_COOKIE_SECURE: Whether to use secure cookies, it can be set when using HTTPS protocol True.

  10. SESSION_PERMANENT: Whether the cookie is permanently valid.

  11. SESSION_FILE_DIR: The path to save the file when storing the session.

  12. UPLOAD_FOLDER: The save path when the file is uploaded.

The above are just some basic options in the Flask configuration file. For details, you need to check the official Flask documentation to learn more about configuration options.

The following are links to some frequently-needed inquiries about configuration items in the official Flask documentation:

In these documents, there are detailed descriptions and examples of Flask configuration items. Provides detailed instructions on how to set and use configuration items, as well as the role and default value of each configuration item.

Guess you like

Origin blog.csdn.net/qq_44907926/article/details/131629174