Flask的配置對象(config)是一個字典(dict)的子類(subclass),因此你能夠把配置用鍵值對的方式存儲進去。html
一、一些重要的配置,能夠設置在系統環境變量裏,又或者放到某個服務器裏,用的時候下載配置文件並讀取配置python
# 在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.
二、直接寫入主腳本linux
from flask import Flask app = Flask(__name__) app.config['SECRET_KEY'] = 'some secret words' app.config['DEBUG'] = True app.config['ITEMS_PER_PAGE'] = 10
或者寫成下面的方式:sql
from flask import Flask app = Flask(__name__) app.config.update( DEBUG=True, SECRET_KEY='some secret words', ITEMS_PER_PAGE=10 )
三、單獨的配置文件configure.pyjson
SECRET_KEY = 'some secret words' DEBUG = True ITEMS_PER_PAGE = 10
在建立程序實例後導入配置flask
import config ... app = Flask(__name__) app.config.from_object(configure) ...
四、爲開發環境、測試環境、生成環境、預發佈環境建立不一樣的測試類api
1 import os 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 class DevelopmentConfig(BaseConfig): 11 DEBUG = True 12 SQLALCHEMY_DATABASE_URI = os.getenv('DEV_DATABASE_URL', 'sqlite:///' + os.path.join(basedir, 'data-dev.sqlite') 13 14 15 class TestingConfig(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 }
導入配置服務器
from config import config # 導入存儲配置的字典 ... app = Flask(__name__) app.config.from_object(config['development']) # 獲取相應的配置類 ...
五、附下flask內置的配置列表cookie
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. |
參考:一、https://zhuanlan.zhihu.com/p/24055329?refer=flasksession
二、http://flask.pocoo.org/docs/0.11/config/#configuration-handling
三、http://www.cnblogs.com/m0m0/p/5624315.html