flask的配置设置的几种方式

摘要:
Flask的配置对象是字典的一个子类,因此您可以以键值对的形式存储配置。

Flask的配置对象(config)是一个字典(dict)的子类(subclass),所以你可以把配置用键值对的方式存储进去。

1、一些重要的配置,可以设置在系统环境变量里,又或者放到某个服务器里,用的时候下载配置文件并读取配置

#在linux系统里设置环境变量
export MAIL_USERNAME=me@greyli.com
#用的时候取环境变量
importos
from flask importFlask
app = Flask(__name__)
app.config['MAIL_USERNAME'] = os.getenv('MAIL_USERNAME', 'me@greyli.com') #os.geteve(key,default=None)  Get an environment variable, return None if it 
# doesn't exist.The optional second argument can specify an alternate default.

2、直接写入主脚本

from flask importFlask
app = Flask(__name__)
app.config['SECRET_KEY'] = 'some secret words'
app.config['DEBUG'] =True
app.config['ITEMS_PER_PAGE'] = 10

或者写成下面的方式:

from flask importFlask
app = Flask(__name__)
app.config.update(
    DEBUG=True,
    SECRET_KEY='some secret words',
    ITEMS_PER_PAGE=10
)

3、单独的配置文件configure.py

SECRET_KEY = 'some secret words'
DEBUG =True
ITEMS_PER_PAGE = 10

在创建程序实例后导入配置

importconfig
...
app = Flask(__name__)
app.config.from_object(configure)
...

4、为开发环境、测试环境、生成环境、预发布环境创建不同的测试类

1 importos
2 basedir = os.path.abspath(os.path.dirname(__file__))
3 
4 
5 class BaseConfig:  #基本配置类
6     SECRET_KEY = os.getenv('SECRET_KEY', 'some secret words')
7     ITEMS_PER_PAGE = 10
8 
9 
10 classDevelopmentConfig(BaseConfig):
11     DEBUG =True
12     SQLALCHEMY_DATABASE_URI = os.getenv('DEV_DATABASE_URL', 'sqlite:///' + os.path.join(basedir, 'data-dev.sqlite')
13 
14 
15 classTestingConfig(BaseConfig):
16     TESTING =True
17     SQLALCHEMY_DATABASE_URI = os.getenv('TEST_DATABASE_URL', 'sqlite:///' + os.path.join(basedir, 'data-test.sqlite')
18     WTF_CSRF_ENABLED =False
19 
20 
21 config ={
22     'development': DevelopmentConfig,
23     'testing': TestingConfig,
24 
25     'default': DevelopmentConfig
26 }
config.py

导入配置

from config import config  #导入存储配置的字典

...
app = Flask(__name__)
app.config.from_object(config['development'])  #获取相应的配置类
...

5、附下flask内置的配置列表

DEBUGenable/disable debug mode
TESTINGenable/disable testing mode
PROPAGATE_EXCEPTIONSexplicitly enable or disable the propagation of exceptions. If not set or explicitly set toNonethis is implicitly true if eitherTESTINGorDEBUGis true.
PRESERVE_CONTEXT_ON_EXCEPTIONBy default if the application is in debug mode the request context is not popped on exceptions to enable debuggers to introspect the data. This can be disabled by this key. You can also use this setting to force-enable it for non debug execution which might be useful to debug production applications (but also very risky).
SECRET_KEYthe secret key
SESSION_COOKIE_NAMEthe name of the session cookie
SESSION_COOKIE_DOMAINthe domain for the session cookie. If this is not set, the cookie will be valid for all subdomains ofSERVER_NAME.
SESSION_COOKIE_PATHthe path for the session cookie. If this is not set the cookie will be valid for all ofAPPLICATION_ROOTor if that is not set for'/'.
SESSION_COOKIE_HTTPONLYcontrols if the cookie should be set with the httponly flag. Defaults toTrue.
SESSION_COOKIE_SECUREcontrols if the cookie should be set with the secure flag. Defaults toFalse.
PERMANENT_SESSION_LIFETIMEthe lifetime of a permanent session asdatetime.timedeltaobject. Starting with Flask 0.8 this can also be an integer representing seconds.
SESSION_REFRESH_EACH_REQUESTthis flag controls how permanent sessions are refreshed. If set toTrue(which is the default) then the cookie is refreshed each request which automatically bumps the lifetime. If set toFalseaset-cookieheader is only sent if the session is modified. Non permanent sessions are not affected by this.
USE_X_SENDFILEenable/disable x-sendfile
LOGGER_NAMEthe name of the logger
LOGGER_HANDLER_POLICYthe policy of the default logging handler. The default is'always'which means that the default logging handler is always active.'debug'will only activate logging in debug mode,'production'will only log in production and'never'disables it entirely.
SERVER_NAMEthe name and port number of the server. Required for subdomain support (e.g.:'myapp.dev:5000') Note that localhost does not support subdomains so setting this to “localhost” does not help. Setting aSERVER_NAMEalso by default enables URL generation without a request context but with an application context.
APPLICATION_ROOTIf the application does not occupy a whole domain or subdomain this can be set to the path where the application is configured to live. This is for session cookie as path value. If domains are used, this should beNone.
MAX_CONTENT_LENGTHIf set to a value in bytes, Flask will reject incoming requests with a content length greater than this by returning a 413 status code.
SEND_FILE_MAX_AGE_DEFAULTDefault cache control max age to use withsend_static_file()(the default static file handler) andsend_file(), asdatetime.timedeltaor as seconds. Override this value on a per-file basis using theget_send_file_max_age()hook onFlaskorBlueprint, respectively. Defaults to 43200 (12 hours).
TRAP_HTTP_EXCEPTIONSIf this is set toTrueFlask will not execute the error handlers of HTTP exceptions but instead treat the exception like any other and bubble it through the exception stack. This is helpful for hairy debugging situations where you have to find out where an HTTP exception is coming from.
TRAP_BAD_REQUEST_ERRORSWerkzeug’s internal data structures that deal with request specific data will raise special key errors that are also bad request exceptions. Likewise many operations can implicitly fail with a BadRequest exception for consistency. Since it’s nice for debugging to know why exactly it failed this flag can be used to debug those situations. If this config is set toTrueyou will get a regular traceback instead.
PREFERRED_URL_SCHEMEThe URL scheme that should be used for URL generation if no URL scheme is available. This defaults tohttp.
JSON_AS_ASCIIBy default Flask serialize object to ascii-encoded JSON. If this is set toFalseFlask will not encode to ASCII and output strings as-is and return unicode strings.jsonifywill automatically encode it inutf-8then for transport for instance.
JSON_SORT_KEYSBy default Flask will serialize JSON objects in a way that the keys are ordered. This is done in order to ensure that independent of the hash seed of the dictionary the return value will be consistent to not trash external HTTP caches. You can override the default behavior by changing this variable. This is not recommended but might give you a performance improvement on the cost of cachability.
JSONIFY_PRETTYPRINT_REGULARIf this is set toTrue(the default) jsonify responses will be pretty printed if they are not requested by an XMLHttpRequest object (controlled by theX-Requested-Withheader)
JSONIFY_MIMETYPEMIME type used for jsonify responses.
TEMPLATES_AUTO_RELOADWhether to check for modifications of the template source and reload it automatically. By default the value isNonewhich means that Flask checks original file only in debug mode.
EXPLAIN_TEMPLATE_LOADINGIf this is enabled then every attempt to load a template will write an info message to the logger explaining the attempts to locate the template. This can be useful to figure out why templates cannot be found or wrong templates appear to be loaded.

参考:1、https://zhuanlan.zhihu.com/p/24055329?refer=flask

2、http://flask.pocoo.org/docs/0.11/config/#configuration-handling

3、http://www.cnblogs.com/m0m0/p/5624315.html

免责声明:文章转载自《flask的配置设置的几种方式》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇ELK+Kafka 企业日志收集平台(一)Oracle【多表查询操作(SQL92&SQL99)】下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

Python接口测试入门

接口测试基础篇用几个简单的案例,带你轻松了解接口测试 首先了解一下接口测试的重要性: 接口测试有什么要求呢? 首先需要清晰的接口文档,标准如下: 接口名称 接口类型 输入参数 每个参数名; 每个参数类型; 每个参数业务含义; 每个是否可空; 每个字段长度(可选,一般需要提供,有严格要求的字段需特别注明); 输出参数 状态码; 提示信息; 每个参...

flask项目结构(六)快速开发后台flask-admin

简介: Flask-admin 相当django的xadmin吧! 快速装配一个后台用来管理数据。 Flask-admin也是有使用局限性的,他只适合开发小型快速的应用,不适合那种大型并发性高,逻辑复杂的应用。首先,对于大型应用都是前后端分离的,加快访问速度,而且后端装配,尤其是这种动态生成页面的速度更慢。 需要安装Flask-Admin,Flask-Ba...

给首页添加遮罩层,添加提示框

最近给详情页面做了一个遮罩提示,用户第一次登录之后会提示,然后下次登录就不显示。 首先考虑用到的是cookie,这样用户第一次进入到详情页,通过js种下一个cookie,然后下次登录再进行判断即可。 /**设置Cookie */ functionSetCookie(cookieName, cookieValue, nDays) {...

Ueditor1.4.3.3+springMvc+maven 实现图片上传

前记:由于项目中需要有一个新增数据并且要能支持表格图片上传的功能。使用了ueditor控件。为实现这个功能,从一开始什么都看不懂,到一直连着弄了5天,总算是有了眉目。在此记录一下以便能帮到可以和我一样遇到问题的人!本人使用的是ueditor 1.4.3.3 的jsp 版本的。 首先下载ueditor 开发版 到本地目录 下载地址:http://uedito...

《Python》hashlib模块、configparser模块、logging模块

一、hashlib模块     Python的hashlib模块中提供了常见的摘要算法,如md5,sha1等等。     摘要算法又称哈希算法、散列算法。它通过一个函数,把任意长度的数据转换为一个长度固定的字符串(通常用16进制的字符串表示)。     不同的字符串通过这个算法计算出的密文总是不同的,相同的算法,相同的字符串,获得的结果总是相同的(不同的语...

基于OpenAM系列的SSO----基础

基于OpenAM系列的SSO----基础  OpenAM简介:OpenAM是一个开源的访问管理、授权服务平台。由ForegeRock公司发起。OpenAM前身为OpenSSO,由SUN公司创建,现在属于Oracle。 本文在OpenAM 13版的Getting started With OpenAM文档上进行描述和总结。 在这个文档中你将了解如何使...