flask的配置设置的几种方式
Flask的配置对象(config)是一个字典(dict)的子类(subclass),所以你可以把配置用键值对的方式存储进去。
1、一些重要的配置,可以设置在系统环境变量里,又或者放到某个服务器里,用的时候下载配置文件并读取配置
# 在linux系统里设置环境变量
export MAIL_USERNAME=me@greyli.com # 用的时候取环境变量
import os
from flask import Flask 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 import Flask app = Flask(__name__)
app.config['SECRET_KEY'] = 'some secret words'
app.config['DEBUG'] = True
app.config['ITEMS_PER_PAGE'] = 10
或者写成下面的方式:
from flask import Flask 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
在创建程序实例后导入配置
import config ...
app = Flask(__name__)
app.config.from_object(configure)
...
4、为开发环境、测试环境、生成环境、预发布环境创建不同的测试类
import os
basedir = os.path.abspath(os.path.dirname(__file__)) class BaseConfig: # 基本配置类
SECRET_KEY = os.getenv('SECRET_KEY', 'some secret words')
ITEMS_PER_PAGE = 10 class DevelopmentConfig(BaseConfig):
DEBUG = True
SQLALCHEMY_DATABASE_URI = os.getenv('DEV_DATABASE_URL', 'sqlite:///' + os.path.join(basedir, 'data-dev.sqlite') class TestingConfig(BaseConfig):
TESTING = True
SQLALCHEMY_DATABASE_URI = os.getenv('TEST_DATABASE_URL', 'sqlite:///' + os.path.join(basedir, 'data-test.sqlite')
WTF_CSRF_ENABLED = False config = {
'development': DevelopmentConfig,
'testing': TestingConfig, 'default': DevelopmentConfig
}
config.py
导入配置
from config import config # 导入存储配置的字典 ...
app = Flask(__name__)
app.config.from_object(config['development']) # 获取相应的配置类
...
5、附下flask内置的配置列表
DEBUG |
enable/disable debug mode |
TESTING |
enable/disable testing mode |
PROPAGATE_EXCEPTIONS |
explicitly enable or disable the propagation of exceptions. If not set or explicitly set to None this is implicitly true if either TESTING orDEBUG is true. |
PRESERVE_CONTEXT_ON_EXCEPTION |
By 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_KEY |
the secret key |
SESSION_COOKIE_NAME |
the name of the session cookie |
SESSION_COOKIE_DOMAIN |
the domain for the session cookie. If this is not set, the cookie will be valid for all subdomains of SERVER_NAME . |
SESSION_COOKIE_PATH |
the path for the session cookie. If this is not set the cookie will be valid for all of APPLICATION_ROOT or if that is not set for '/' . |
SESSION_COOKIE_HTTPONLY |
controls if the cookie should be set with the httponly flag. Defaults to True . |
SESSION_COOKIE_SECURE |
controls if the cookie should be set with the secure flag. Defaults to False . |
PERMANENT_SESSION_LIFETIME |
the lifetime of a permanent session asdatetime.timedelta object. Starting with Flask 0.8 this can also be an integer representing seconds. |
SESSION_REFRESH_EACH_REQUEST |
this flag controls how permanent sessions are refreshed. If set to True (which is the default) then the cookie is refreshed each request which automatically bumps the lifetime. If set to False a set-cookie header is only sent if the session is modified. Non permanent sessions are not affected by this. |
USE_X_SENDFILE |
enable/disable x-sendfile |
LOGGER_NAME |
the name of the logger |
LOGGER_HANDLER_POLICY |
the 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_NAME |
the 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 a SERVER_NAME also by default enables URL generation without a request context but with an application context. |
APPLICATION_ROOT |
If 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 be None . |
MAX_CONTENT_LENGTH |
If 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_DEFAULT |
Default cache control max age to use withsend_static_file() (the default static file handler) and send_file() , asdatetime.timedelta or as seconds. Override this value on a per-file basis using theget_send_file_max_age() hook on Flask orBlueprint , respectively. Defaults to 43200 (12 hours). |
TRAP_HTTP_EXCEPTIONS |
If this is set to True Flask 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_ERRORS |
Werkzeug’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 to True you will get a regular traceback instead. |
PREFERRED_URL_SCHEME |
The URL scheme that should be used for URL generation if no URL scheme is available. This defaults to http . |
JSON_AS_ASCII |
By default Flask serialize object to ascii-encoded JSON. If this is set to False Flask will not encode to ASCII and output strings as-is and return unicode strings. jsonify will automatically encode it in utf-8 then for transport for instance. |
JSON_SORT_KEYS |
By 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_REGULAR |
If this is set to True (the default) jsonify responses will be pretty printed if they are not requested by an XMLHttpRequest object (controlled by the X-Requested-With header) |
JSONIFY_MIMETYPE |
MIME type used for jsonify responses. |
TEMPLATES_AUTO_RELOAD |
Whether to check for modifications of the template source and reload it automatically. By default the value is None which means that Flask checks original file only in debug mode. |
EXPLAIN_TEMPLATE_LOADING |
If 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的配置设置的几种方式的更多相关文章
- 【转】Apache 配置虚拟主机三种方式
Apache 配置虚拟主机三种方式 原文博客http://www.cnblogs.com/hi-bazinga/archive/2012/04/23/2466605.html 一.基于IP 1. 假 ...
- web.config文件中配置数据库连接的两种方式
web.config文件中配置数据库连接的两种方式 标签: 数据库webconfig 2015-04-28 18:18 31590人阅读 评论(1)收藏举报 分类: 数据库(74) 在网站开发 ...
- 【转】python之配置日志的几种方式
[转]python之配置日志的几种方式 作为开发者,我们可以通过以下3种方式来配置logging: 1)使用Python代码显式的创建loggers, handlers和formatters并分别调用 ...
- Python 配置日志的几种方式
Python配置日志的几种方式 作为开发者,我们可以通过以下3种方式来配置logging: (1)使用Python代码显式的创建loggers,handlers和formatters并分别调用它们的配 ...
- springmvc配置AOP的两种方式
spingmvc配置AOP有两种方式,一种是利用注解的方式配置,另一种是XML配置实现. 应用注解的方式配置: 先在maven中引入AOP用到的依赖 <dependency> <gr ...
- spring配置属性的两种方式
spring配置属性有两种方式,第一种方式通过context命名空间中的property-placeholder标签 <context:property-placeholder location ...
- MyBatis配置数据源的两种方式
---------------------siwuxie095 MyBatis 配置数据源的两种方式 1.配置方 ...
- /*透明度设置的两种方式,以及hover的用法,fixed,(relative,absolute)这两个一起用*/
<!DOCTYPE html> /*透明度设置的两种方式,以及hover的用法,fixed,(relative,absolute)这两个一起用*/ <html lang=" ...
- Spring配置事务的五种方式
Java事务的类型有三种: JDBC事务. 可以将多个 SQL 语句结合到一个事务中.JDBC 事务的一个缺点是事务的范围局限于一个数据库连接.一个 JDBC 事务不能跨越多个数据库 JTA(Java ...
随机推荐
- angular2框架搭建,angular-cli使用,angular2学习
angular红红火火很多年了,一眨眼ng4都出来了,我也只能叹息前端的日新月异,以及感叹自己永远追赶不上时代的步伐,但是没关系,一个优秀的前端不在于他懂的无数的框架,而在于遇到问题时候懂得如何学习, ...
- webstorm vue代码修改后不更新问题
把 safe write 的勾去掉就行了.
- AE特效-与MAYA的结合、制作音乐舞蹈太极动作
http://blog.sina.com.cn/s/blog_a439a2670101fbkk.html AE特效-与MAYA的结合.制作音乐舞蹈太极动作 (2013-07-24 14:44:12) ...
- Delphi字符串、PChar与字符数组之间的转换
来自:http://my.oschina.net/kavensu/blog/193719 ------------------------------------------------------- ...
- linux常用命令 查看文件
Linux常用命令 查看文件 cat命令 cat命令的用途是连接文件或标准打印输入并打印.这个命令常用来显示文件内容,或者将几个文件连接起来显示,或者从标准输入读取内容并显示. 命令格式: cat [ ...
- CentOS7下,安装网卡驱动,命令行手动连接WIFI指导
买了一个无线网卡,型号为TL-WN823N,谁知道在CentOS下没有驱动 于是开始了无线上网的漫漫征途 经历了无数个坑啊,解决了一个又一个的问题啊 到最后ping通的时候成就感简直爆棚 文章结构简介 ...
- MySQL数据库中的Date,DateTime,int,TimeStamp和Time类型的对比
DATETIME 用在你需要同时包含日期和时间信息的值时.MySQL检索并且以'YYYY-MM-DD HH:MM:SS'格式显示DATETIME值,支持的范围是'1000-01-01 00:00:00 ...
- hit2739
好题,回路的问题一般都要转化为度数来做若原图的基图不连通,或者存在某个点的入度或出度为0则无解.统计所有点的入度出度之差di对于di>0的点,加边(s,i,di,0):对于di<0的点,加 ...
- 只用120行Java代码写一个自己的区块链-3挖矿算法
在本系列前两篇文章中,我们向大家展示了如何通过精炼的Java代码实现一个简单的区块链.包括生成块,验证块数据,广播通信等等,这一篇让我们聚焦在如何实现 PoW算法. 大家都无不惊呼比特币.以太坊及其他 ...
- The number of steps(概率dp)
Description Mary stands in a strange maze, the maze looks like a triangle(the first layer have one r ...