This article shares five ways to use the configuration file load in the Python flask framework
Flask several ways to manage profiles:
Method One: Direct configuration
#!/usr/bin/env python# encoding:utf-8from flask import Flaskimport Timeapp = Flask (__name__) app.config[' SEND_FILE_MAX_ Age_default ']=time.asctime () app.config[' HOST ']= ' www.aolens.cn ' Print app.config@app.route ('/') def hello_world (): return ' Hello world! %s %s '% (App.config.get (' Send_file_max_age_default '), App.config.get (' HOST ')) if __name__== ' __main__ ': App.run ()
You can see a large dictionary of the global:
<config {' json_as_ascii ': True, ' use_x_sendfile ': False, ' Session_cookie_path ': None, ' Session_cookie_domain ': none , ' session_cookie_name ': ' SESSION ', ' session_refresh_each_request ': True, ' logger_handler_policy ': ' Always ', ' logger_ NAME ': ' __main__ ', ' DEBUG ': false, ' Secret_key ': None, ' explain_template_loading ': false, ' max_content_length ': none, ' Application_root ': None, ' server_name ': None, ' preferred_url_scheme ': ' http ', ' jsonify_prettyprint_regular ': True, ' Testing ': False, ' HOST ': ' www.aolens.cn ', ' permanent_session_lifetime ': Datetime.timedelta, ' Propagate_ EXCEPTIONS ': None, ' templates_auto_reload ': None, ' trap_bad_request_errors ': False, ' Json_sort_keys ': True, ' Jsonify_ MIMETYPE ': ' Application/json ', ' session_cookie_httponly ': True, ' send_file_max_age_default ': ' Thu Mar 2 16:33:17 2017 ', ' Preserve_context_on_exception ': None, ' session_cookie_secure ': False, ' trap_http_exceptions ': false}>
Method Two: Load the configuration with environment variables
Create an environment variable file. config.py
# content is a key value, not necessarily a large dictionary of host=localhostpost=3306 #自己创建export config_set=./config.py Code: App.config.from_envvar (' Config_set) @app. Route ('/') def hello_world (): Return "Hello World%s%s"% (App.config.get (' HOST '), App.config.get (' POST '))
Method Three: Load by object (common)--from_object ()
Config object code-based on the class inheritance of the config structure, save the default configuration of the Config class as the base class, other classes inherit.
Create a file configlist.py
#!/usr/bin/env python# Encoding:utf-8class Config (): #父类可以被下边的类继承到AUTHOR参数 author= ' Aolens ' class Developmentconfig (Config): DEBUG = True sql_uri= ' Mysql://root:password@192.168.1.101/test ' class Productionconfig (Config): sql_uri= ' mysql://root:password@192.168.1.101/devops ' host= ' localhost ' Config = {#将类写成字典的形式存储 ' dev ':D evelopmentconfig, ' Pro ':P roductionconfig, ' default ':D Evelopmentconfig}
Call configlist.py
#!/usr/bin/env python# encoding:utf-8from flask Import flaskfrom configlist import *import Timeapp = Flask (__name__) #对象加载 , the FROM config import * #第一种加载方式app. Config.from_object (productionconfig) #第二种加载方式, loading the short config can also be loaded to #app.config.from _object (config[' Pro ') print app.config@app.route ('/') #/means the URL behind +/, or other URIs, Access is Ip+uridef Hello_world (): Return ' Hello world! %s%s '% (app.config.get (' Sql_uri '), App.config.get (' HOST '), App.config.get (' AUTHOR ')) if __name__== ' __main__ ' : App.run ()
Browser Access results:
Hello world! Mysql://root:password@192.168.1.101/devops localhost Aolens
How to determine the test environment or production: #!/usr/bin/env python# encoding:utf-8from flask Import flaskfrom config2 import *import osimport Timeapp = F Lask (__name__) if Os.path.exists ("./pro"): App.config.from_object (config[' Pro ']) elif os.path.exists ("./dev"): App.config.from_object (developmentconfig) print app.config@app.route ('/test ') def hello_world (): Return ' Hello world! %s%s '% (app.config.get (' Sql_uri '), App.config.get (' HOST '), App.config.get (' AUTHOR ')) if __name__== ' __main__ ' : App.run ()
Method Four: Through the configuration file--app.config.from_pyfile,config file must be in the app directory
Vim confile.pyhost= ' locolhost ' port=10000author= ' aolens ' from flask import Flaskapp.config.from_pyfile ('./confile.py ') #加载配置文件print app.config@app.route ('/test ') def hello_world (): return ' Hello world! %s%s '% (app.config.get (' PORT '), App.config.get (' HOST '), App.config.get (' AUTHOR ')) if __name__== ' __main__ ': App.run ()
Method Five: is a kind of improvement to method four Configparser module configuration file Management
Configparser Introduction:
Is the package that is used to read the configuration file, and the parentheses in the configuration file contain the session. section below is a configuration file content similar to Key-value.
The format is as follows:
Vim Test.conf[api] #sessionport =11111 #optionpath =/data/api/log[web]port=1002path=/data/web/log
Use: confile.py
Import configparserdef GetConfig (filename,section= "): cf=configparser.configparser () #实例化 Cf.read ( FileName) #读取配置文件 cf_items = dict (cf.items (section)) If Cf.has_section (section) else {} # To determine if a section exists, there are data stored in a dictionary, no return empty dictionary returns cf_itemsif __name__== ' __main__ ': conf =getconfig (' test.conf ', ' web ' Print conf print conf[' port '] print conf.get (' path ')
Operation Result:
{' path ': '/data/web/log ', ' Port ': ' 1002 '}
1002
/data/web/log
Call: demo.py
#!/usr/bin/env python# encoding:utf-8from confile import getconfigfrom flask Import Flaskapp = Flask (__name__) #直接配置 @app. Route ('/test ') def hello_world (): conf=getconfig (' test.conf ', ' API ') return ' Hello world! %s '% (conf[' Port ']) if __name__== ' __main__ ': app.run ()
Results:
Hello world! 11111 #option