Home >Backend Development >Python Tutorial >Share five ways to use configuration files in the python Flask framework

Share five ways to use configuration files in the python Flask framework

高洛峰
高洛峰Original
2017-03-10 17:08:113190browse

This article shares five ways to use configuration file loading in the python Flask framework

Several ways to manage Flask configuration files:

Method 1: Directly configure

#!/usr/bin/env python
# encoding: utf-8
from flask import Flask
import time
app = 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()

to see a global large dictionary:

98ffaebc276a592246a2971f2a5e58aa


Method 2: Load configuration through environment variables

Create an environment variable file. config.py

#内容为键值,不一定要是大字典里的
HOST=localhost
POST=3306   #自己创建
export CONFIG_SET=./config.py
代码中:
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 3: Loading through objects (commonly used)--from_object()

config object code--using the config structure based on class inheritance to save the default configuration Config class As a base class, other classes inherit from it.

Create a file Configlist.py

#!/usr/bin/env python
# encoding: utf-8
class 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':DevelopmentConfig,
   'pro':ProductionConfig,
   'default':DevelopmentConfig
}

Call Configlist.py

#!/usr/bin/env python
# encoding: utf-8
from flask import Flask
from configlist import *
import time
app = Flask(__name__)
#对象加载,from config import *
#第一种加载方式
app.config.from_object(ProductionConfig)
#第二种加载方式,加载简写的config短也可以加载的到
#app.config.from_object(config['pro'])
print app.config
@app.route('/')    #/表示URL后边+/,也可使其他URI,访问就是IP+URI
def hello_world():
   return 'Hello World!  %s  %s %s' %(app.config.get('SQL_URI'),app.config.get('HOST'),app.config.get('AUTHOR'))
if __name__=='__main__':
   app.run()

Browser access result:

Hello World! mysql://root: password@192.168.1.101/devops localhost aolens

如何判断测试环境还是生产:
#!/usr/bin/env python
# encoding: utf-8
from flask import Flask
from config2 import *
import os
import time
app = Flask(__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 %s' %(app.config.get('SQL_URI'),app.config.get('HOST'),app.config.get('AUTHOR'))
if __name__=='__main__':
   app.run()

Method 4: Through the configuration file--app.config.from_pyfile, the config file must be in the app directory

vim confile.py
HOST='locolhost'
PORT=10000
AUTHOR='aolens'
from flask import Flask
app.config.from_pyfile('./confile.py') #加载配置文件
print app.config
@app.route('/TEST')
def hello_world():
   return 'Hello World!  %s  %s %s' %(app.config.get('PORT'),app.config.get('HOST'),app.config.get('AUTHOR'))
if __name__=='__main__':
   app.run()

Method 5: It is the right method An improvement of ConfigParser module configuration file management

ConfigParser introduction:

is a package used to read configuration files. The brackets [] in the configuration file include session. Below the section is the configuration file content similar to key-value.

The format is as follows:

vim test.conf
[api] #session
port=11111 #option
path=/data/api/log
[web]
port=1002
path=/data/web/log

Usage: configure.py

import ConfigParser
def getconfig(filename,section=''):
   cf=ConfigParser.ConfigParser()   #实例化
   cf.read(filename)   #读取配置文件
   cf_items = dict(cf.items(section)) if cf.has_section(section)  else {}  #判断SECTION是否存在,存在把数据存入字典,没有返回空字典
   return cf_items
if __name__=='__main__':
   conf =getconfig('test.conf','web')
   print conf
   print conf['port']
   print conf.get('path')

Running result:

{'path': '/data/web/log' , 'port': '1002'}

1002

/data/web/log

Call: demo.py

#!/usr/bin/env python
# encoding: utf-8
from confile import getconfig
from flask import Flask
app = Flask(__name__)
#直接配置
@app.route('/TEST')
def hello_world():
     conf=getconfig('test.conf','api')
     return 'Hello World!   %s' %(conf['port'])
if __name__=='__main__':
     app.run()

Result:

Hello World! 11111 #option

The above is the detailed content of Share five ways to use configuration files in the python Flask framework. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn