当前位置:网站首页>In simple terms, flask (1): how to read configuration parameters

In simple terms, flask (1): how to read configuration parameters

2021-08-10 08:32:09 caimouse

In the process of developing software , Must deal with configuration parameters , Why do you say that ? Because the developed software needs to be released to customers , In this way, the value of software can be realized . This leads to the difference between the development environment and the customer's use environment , In this case, you need to use the configuration parameters , In order to distinguish the development environment from the customer's production environment . Because the development environment needs to output more information , Like logs , And the log will print more detailed information , Easy debugging and error correction . And at the customer , You don't need to output so many logs , Because too many logs are output , Always occupied CPU resources , This leads to a poor user experience , This will lead to unfavorable competition between their own products and other people's products . Say something bad , In today's business environment , Experience is the king of the times , If the experience is not good , Even if it meets the needs of users , If the experience is not good, users will give up , In this way, without users, there will be no income , The company will go bankrupt . It can be seen that software development is an extremely detailed work , It's also a perfect job .

stay flask Configuring parameters in is a relatively simple job , If a small project , You can write the parameters directly into the program , Take the following example :

#python 3.7.4, flask 
# Cai Junsheng  https://blog.csdn.net/caimouse
#9073204@qq.com
#

from flask import Flask

app = Flask(__name__)
#  Direct assignment 
app.config['SECRET_KEY'] = 'some secret words'
app.config['DEBUG'] = True
app.config['ITEMS_PER_PAGE'] = 10
#  Or how to update the dictionary 
app.config.update(
    DEBUG=True,
    SECRET_KEY='some secret words',
    ITEMS_PER_PAGE=10
)

print(app.config)

The output is as follows :

<Config {'ENV': 'production', 'DEBUG': True, 'TESTING': False, 'PROPAGATE_EXCEPTIONS': None, 'PRESERVE_CONTEXT_ON_EXCEPTION': None, 'SECRET_KEY': 'some secret words', 'PERMANENT_SESSION_LIFETIME': datetime.timedelta(days=31), 'USE_X_SENDFILE': False, 'SERVER_NAME': None, 'APPLICATION_ROOT': '/', 'SESSION_COOKIE_NAME': 'session', 'SESSION_COOKIE_DOMAIN': None, 'SESSION_COOKIE_PATH': None, 'SESSION_COOKIE_HTTPONLY': True, 'SESSION_COOKIE_SECURE': False, 'SESSION_COOKIE_SAMESITE': None, 'SESSION_REFRESH_EACH_REQUEST': True, 'MAX_CONTENT_LENGTH': None, 'SEND_FILE_MAX_AGE_DEFAULT': datetime.timedelta(seconds=43200), 'TRAP_BAD_REQUEST_ERRORS': None, 'TRAP_HTTP_EXCEPTIONS': False, 'EXPLAIN_TEMPLATE_LOADING': False, 'PREFERRED_URL_SCHEME': 'http', 'JSON_AS_ASCII': True, 'JSON_SORT_KEYS': True, 'JSONIFY_PRETTYPRINT_REGULAR': False, 'JSONIFY_MIMETYPE': 'application/json', 'TEMPLATES_AUTO_RELOAD': None, 'MAX_COOKIE_SIZE': 4093, 'ITEMS_PER_PAGE': 10}>
>>> 

But when the project is large , You need to write the configuration information into the configuration file separately , This is convenient for modification , It is also convenient to use different files to select parameters . Use app.config.from_object Function or app.config.from_pyfile('config.py') To load configuration information .

Take the following example , First write the configuration information to config.py In the document :

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

Then write code to read the configuration information :

#python 3.7.4, flask 
# Cai Junsheng  https://blog.csdn.net/caimouse
#9073204@qq.com
#

from flask import Flask

app = Flask(__name__)

app.config.from_object('config.ProductionConfig')

print(app.config)

The output is as follows :

<Config {'ENV': 'production', 'DEBUG': False, 'TESTING': False, 'PROPAGATE_EXCEPTIONS': None, 'PRESERVE_CONTEXT_ON_EXCEPTION': None, 'SECRET_KEY': None, 'PERMANENT_SESSION_LIFETIME': datetime.timedelta(days=31), 'USE_X_SENDFILE': False, 'SERVER_NAME': None, 'APPLICATION_ROOT': '/', 'SESSION_COOKIE_NAME': 'session', 'SESSION_COOKIE_DOMAIN': None, 'SESSION_COOKIE_PATH': None, 'SESSION_COOKIE_HTTPONLY': True, 'SESSION_COOKIE_SECURE': False, 'SESSION_COOKIE_SAMESITE': None, 'SESSION_REFRESH_EACH_REQUEST': True, 'MAX_CONTENT_LENGTH': None, 'SEND_FILE_MAX_AGE_DEFAULT': datetime.timedelta(seconds=43200), 'TRAP_BAD_REQUEST_ERRORS': None, 'TRAP_HTTP_EXCEPTIONS': False, 'EXPLAIN_TEMPLATE_LOADING': False, 'PREFERRED_URL_SCHEME': 'http', 'JSON_AS_ASCII': True, 'JSON_SORT_KEYS': True, 'JSONIFY_PRETTYPRINT_REGULAR': False, 'JSONIFY_MIMETYPE': 'application/json', 'TEMPLATES_AUTO_RELOAD': None, 'MAX_COOKIE_SIZE': 4093, 'DATABASE_URI': 'mysql://user@localhost/foo'}>

You can see that the configuration file information is modified by inheritance .

Then come down , Let's take a practical example , It may be more complicated , First create a configuration directory , Here's the picture :

Then the program reads the file in the directory sample, Here's the picture :

In this way, you can put different configuration files in the directory configs in , It is convenient to save different configuration parameter files , It is also convenient for future deployment personnel to manage and modify . It will read the directory configs Files in default.py, It is a way of managing packages , Then read the class name :DefaultConfig.

app.config.from_object("configs.default.DefaultConfig")

The code of this example is as follows :

#python 3.7.4, flask 
# Cai Junsheng  https://blog.csdn.net/caimouse
#9073204@qq.com
#
import logging
import logging.config

from flask import Flask, request

logger = logging.getLogger(__name__)

def create_app(config=None, instance_path=None):
    app = Flask(
        "flaskRDMS", instance_path=instance_path, instance_relative_config=True
    )

    app.config.from_object("configs.default.DefaultConfig")

    print(app.config)

#
create_app()

After running, the output results are as follows :

<Config {'ENV': 'production', 'DEBUG': False, 'TESTING': False, 'PROPAGATE_EXCEPTIONS': None, 'PRESERVE_CONTEXT_ON_EXCEPTION': None, 'SECRET_KEY': 'secret key', 'PERMANENT_SESSION_LIFETIME': datetime.timedelta(days=31), 'USE_X_SENDFILE': False, 'SERVER_NAME': None, 'APPLICATION_ROOT': '/', 'SESSION_COOKIE_NAME': 'session', 'SESSION_COOKIE_DOMAIN': None, 'SESSION_COOKIE_PATH': None, 'SESSION_COOKIE_HTTPONLY': True, 'SESSION_COOKIE_SECURE': False, 'SESSION_COOKIE_SAMESITE': None, 'SESSION_REFRESH_EACH_REQUEST': True, 'MAX_CONTENT_LENGTH': None, 'SEND_FILE_MAX_AGE_DEFAULT': datetime.timedelta(seconds=43200), 'TRAP_BAD_REQUEST_ERRORS': None, 'TRAP_HTTP_EXCEPTIONS': False, 'EXPLAIN_TEMPLATE_LOADING': False, 'PREFERRED_URL_SCHEME': 'http', 'JSON_AS_ASCII': True, 'JSON_SORT_KEYS': True, 'JSONIFY_PRETTYPRINT_REGULAR': False, 'JSONIFY_MIMETYPE': 'application/json', 'TEMPLATES_AUTO_RELOAD': None, 'MAX_COOKIE_SIZE': 4093, 'ADMINS': ['admin@example.org'], 'ADMIN_URL_PREFIX': '/admin', 'ALEMBIC': {'script_location': 'D:\\work\\Flask\\src\\flaskbb/migrations', 'version_locations': '', 'file_template': '%%(year)d%%(month).2d%%(day).2d%%(hour).2d%%(minute).2d_%%(rev)s_%%(slug)s'}, 'ALEMBIC_CONTEXT': {'render_as_batch': True}, 'ALLOWED_HOSTS': None, 'AUTH_URL_PREFIX': '/auth', 'CACHE_DEFAULT_TIMEOUT': 60, 'CACHE_TYPE': 'SimpleCache', 'CELERY_CONFIG': {'broker_url': 'redis://localhost:6379', 'result_backend': 'redis://localhost:6379', 'broker_transport_options': {'max_retries': 1}}, 'FORUM_URL_PREFIX': '', 'LOGIN_MESSAGE_CATEGORY': 'info', 'LOGIN_VIEW': 'auth.login', 'LOG_CONF_FILE': None, 'LOG_DEFAULT_CONF': {'version': 1, 'disable_existing_loggers': False, 'formatters': {'standard': {'format': '%(asctime)s %(levelname)-7s %(name)-25s %(message)s'}, 'advanced': {'format': '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'}}, 'handlers': {'console': {'level': 'NOTSET', 'formatter': 'standard', 'class': 'logging.StreamHandler'}, 'flaskbb': {'level': 'DEBUG', 'formatter': 'standard', 'class': 'logging.handlers.RotatingFileHandler', 'filename': 'D:\\work\\Flask\\src\\logs\\flaskbb.log', 'mode': 'a', 'maxBytes': 10485760, 'backupCount': 5}, 'infolog': {'level': 'INFO', 'formatter': 'standard', 'class': 'logging.handlers.RotatingFileHandler', 'filename': 'D:\\work\\Flask\\src\\logs\\info.log', 'mode': 'a', 'maxBytes': 10485760, 'backupCount': 5}, 'errorlog': {'level': 'ERROR', 'formatter': 'standard', 'class': 'logging.handlers.RotatingFileHandler', 'filename': 'D:\\work\\Flask\\src\\logs\\error.log', 'mode': 'a', 'maxBytes': 10485760, 'backupCount': 5}}, 'loggers': {'flask.app': {'handlers': ['infolog', 'errorlog'], 'level': 'INFO', 'propagate': True}, 'flaskbb': {'handlers': ['console', 'flaskbb'], 'level': 'WARNING', 'propagate': True}}}, 'LOG_PATH': 'D:\\work\\Flask\\src\\logs', 'MAIL_DEFAULT_SENDER': ('Default Sender', 'noreply@example.org'), 'MAIL_PASSWORD': '', 'MAIL_PORT': 25, 'MAIL_SERVER': 'localhost', 'MAIL_USERNAME': 'noreply@example.org', 'MAIL_USE_SSL': False, 'MAIL_USE_TLS': False, 'MESSAGE_URL_PREFIX': '/message', 'REAUTH_VIEW': 'auth.reauth', 'REDIS_DATABASE': 0, 'REDIS_ENABLED': False, 'REDIS_URL': 'redis://localhost:6379', 'REFRESH_MESSAGE_CATEGORY': 'info', 'REMEMBER_COOKIE_DOMAIN': None, 'REMEMBER_COOKIE_DURATION': datetime.timedelta(days=365), 'REMEMBER_COOKIE_HTTPONLY': False, 'REMEMBER_COOKIE_NAME': 'remember_token', 'REMEMBER_COOKIE_PATH': '/', 'REMEMBER_COOKIE_SECURE': None, 'REMOVE_DEAD_PLUGINS': False, 'SEND_LOGS': False, 'SQLALCHEMY_DATABASE_URI': 'sqlite:///D:\\work\\Flask\\src/flaskbb.sqlite', 'SQLALCHEMY_ECHO': False, 'SQLALCHEMY_TRACK_MODIFICATIONS': False, 'USER_URL_PREFIX': '/user', 'USE_DEFAULT_LOGGING': True, 'WHOOSHEE_DIR': 'D:\\work\\Flask\\src\\whoosh_index\\37', 'WHOOSHEE_MIN_STRING_LEN': 3, 'WHOOSHEE_WRITER_TIMEOUT': 2, 'WTF_CSRF_ENABLED': True, 'WTF_CSRF_SECRET_KEY': 'reallyhardtoguess'}>
>>> 

Learn from the above , We understand flask Configuration parameters for , Written like this flask The first step of the project is to do .

版权声明
本文为[caimouse]所创,转载请带上原文链接,感谢
https://chowdera.com/2021/08/20210810083135992E.html

随机推荐