flask_6: Interpretation of flash project configuration source code

catalog:

1. View app Config type

2. View app Config source code

3. Configuration mode 2 - configuration in object: from_object introduction

 

a key:

app. config. from_ The object () method says that the received parameter obj can make str type, which can be a module or even a class.

 

1. View.app Config type: is a class

from flask import Flask

app = Flask(__name__)
print(type(app.config))


# The output result is a class
<class 'flask.config.Config'>

 

2. View app Config source code:

class Config(dict):
    def __init__(self, root_path, defaults=None):
        dict.__init__(self, defaults or {})
        self.root_path = root_path

    # Method of reading configuration
    def from_envvar(self, variable_name, silent=False):
        pass

    def from_pyfile(self, filename, silent=False):
        pass

    def from_object(self, obj):
        pass

    def from_json(self, filename, silent=False):
        pass

    def from_mapping(self, *mapping, **kwargs):
        pass

See the source code, app Config is a class that inherits the dict class, and then adds several methods to read the configuration, so app Config can use the dictionary method to load the configuration by direct assignment, or use the methods defined above to load the configuration.

 

3. Configuration mode 2 - configuration in object: from_object (recommended)

 

Let's see from first_ Source code of object () method:

 

def from_object(self, obj):
        if isinstance(obj, string_types):  # judge obj Is it str type
            obj = import_string(obj)  # If it is str Type, import the object according to this string
        for key in dir(obj):  # ergodic obj All values of
            if key.isupper():
                self[key] = getattr(obj, key)  # self It means config Instance itself, through getattr Take out the corresponding value for

 

As can be seen from the source code, from_ The object () method says that the received parameter obj can make str type, which can be a module or even a class.

 

Let's try the case of a module and create a setting Py module, as follows:

 

DEBUG = False
TESTING = False

 

Only two configurations are written here. You can write more. It doesn't matter. How to use it?

 

from flask import Flask
import settings
 
app = Flask(__name__)
app.config.from_object(settings)
print('DEBUG:', app.config.get('DEBUG'))
print('TESTING:', app.config.get('TESTING'))
print('A:', app.config.get('A'))

 

Output:

 

DEBUG: True

 

TESTING: True

 

A: 123

 

When obj is a string:

 

from flask import Flask
 
app = Flask(__name__)
app.config.from_object('settings')
print('DEBUG:', app.config.get('DEBUG'))
print('TESTING:', app.config.get('TESTING'))
print('A:', app.config.get('A'))

 

Output:

 

DEBUG: True

 

TESTING: True

 

A: 123

 

See? Whether using app config. from_ Object (settings) or app config. from_ Object ('settings') uses settings Py file. If you don't understand the reason, go back to the source code above.

 

If obj is a class, let's modify settings Py, as follows:

 

class Config(object):
    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

 

In settings In the PY module, we define several classes. The first is the Config class. This class defines the default configuration. Other classes inherit the Config class. Each class represents a configuration. If necessary, config can be overridden in the subclass. If not, the default configuration in config will be used. How to use it?

 

from flask import Flask
import settings
 
app = Flask(__name__)
app.config.from_object(settings.ProductionConfig)
print('DEBUG:', app.config.get('DEBUG'))
print('TESTING:', app.config.get('TESTING'))
print('DATABASE_URI:', app.config.get('DATABASE_URI'))

 

Output:

 

DEBUG: False

 

TESTING: False

 

DATABASE_URI: mysql://user@localhost/foo

 

The advantage of using this method is that it can make full use of the excellent characteristics of object-oriented relay, share configuration and set multiple sets of configuration. When using, you only need to modify the app according to the actual needs config. from_ Object (settings. Productionconfig). This method is also the most used in practical development.

 

 

 

This article refers to: Look at the configuration management of flash framework from the source code

Several other loading methods are described in the original blog, and the original blogger's articles are of high quality. The explanations are familiar and easy to understand, and the typesetting is clear and clear. They have paid attention to the original blogger, and it is recommended to pay attention to the small partners they see.

 

Posted by scuzzo on Fri, 20 May 2022 14:54:07 +0300