### Subversion checkout URL

You can clone with HTTPS or Subversion.

Fetching contributors…

Cannot retrieve contributors at this time

file 404 lines (319 sloc) 17.828 kb
 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 .. _config:Configuration Handling======================.. versionadded:: 0.3Applications need some kind of configuration. There are different settingsyou might want to change depending on the application environment liketoggling the debug mode, setting the secret key, and other suchenvironment-specific things.The way Flask is designed usually requires the configuration to beavailable when the application starts up. You can hardcode theconfiguration in the code, which for many small applications is notactually that bad, but there are better ways.Independent of how you load your config, there is a config objectavailable which holds the loaded configuration values:The :attr:~flask.Flask.config attribute of the :class:~flask.Flaskobject. This is the place where Flask itself puts certain configurationvalues and also where extensions can put their configuration values. Butthis is also where you can have your own configuration.Configuration Basics--------------------The :attr:~flask.Flask.config is actually a subclass of a dictionary andcan be modified just like any dictionary:: app = Flask(__name__) app.config['DEBUG'] = TrueCertain configuration values are also forwarded to the:attr:~flask.Flask object so you can read and write them from there:: app.debug = TrueTo update multiple keys at once you can use the :meth:dict.updatemethod:: app.config.update( DEBUG=True, SECRET_KEY='...' )Builtin Configuration Values----------------------------The following configuration values are used internally by Flask:.. tabularcolumns:: |p{6.5cm}|p{8.5cm}|================================= =========================================DEBUG enable/disable debug modeTESTING enable/disable testing modePROPAGATE_EXCEPTIONS explicitly enable or disable the                                  propagation of exceptions. If not set or                                  explicitly set to None this is                                  implicitly true if either TESTING or                                  DEBUG 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 keySESSION_COOKIE_NAME the name of the session cookieSESSION_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 as                                  :class:datetime.timedelta object.                                  Starting with Flask 0.8 this can also be                                  an integer representing seconds.USE_X_SENDFILE enable/disable x-sendfileLOGGER_NAME the name of the loggerSERVER_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 with                                  :meth:~flask.Flask.send_static_file (the                                  default static file handler) and                                  :func:~flask.send_file, in                                  seconds. Override this value on a per-file                                  basis using the                                  :meth:~flask.Flask.get_send_file_max_age                                  hook on :class:~flask.Flask or                                  :class:~flask.Blueprint,                                  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.================================= =========================================.. admonition:: More on SERVER_NAME   The SERVER_NAME key is used for the subdomain support. Because   Flask cannot guess the subdomain part without the knowledge of the   actual server name, this is required if you want to work with   subdomains. This is also used for the session cookie.   Please keep in mind that not only Flask has the problem of not knowing   what subdomains are, your web browser does as well. Most modern web   browsers will not allow cross-subdomain cookies to be set on a   server name without dots in it. So if your server name is   'localhost' you will not be able to set a cookie for   'localhost' and every subdomain of it. Please chose a different   server name in that case, like 'myapplication.local' and add   this name + the subdomains you want to use into your host config   or setup a local bind_... _bind: https://www.isc.org/software/bind.. versionadded:: 0.4   LOGGER_NAME.. versionadded:: 0.5   SERVER_NAME.. versionadded:: 0.6   MAX_CONTENT_LENGTH.. versionadded:: 0.7   PROPAGATE_EXCEPTIONS, PRESERVE_CONTEXT_ON_EXCEPTION.. versionadded:: 0.8   TRAP_BAD_REQUEST_ERRORS, TRAP_HTTP_EXCEPTIONS,   APPLICATION_ROOT, SESSION_COOKIE_DOMAIN,   SESSION_COOKIE_PATH, SESSION_COOKIE_HTTPONLY,   SESSION_COOKIE_SECURE.. versionadded:: 0.9   PREFERRED_URL_SCHEMEConfiguring from Files----------------------Configuration becomes more useful if you can store it in a separate file,ideally located outside the actual application package. This makespackaging and distributing your application possible via various packagehandling tools (:ref:distribute-deployment) and finally modifying theconfiguration file afterwards.So a common pattern is this:: app = Flask(__name__) app.config.from_object('yourapplication.default_settings') app.config.from_envvar('YOURAPPLICATION_SETTINGS')This first loads the configuration from theyourapplication.default_settings module and then overrides the valueswith the contents of the file the :envvar:YOURAPPLICATION_SETTINGSenvironment variable points to. This environment variable can be set onLinux or OS X with the export command in the shell before starting theserver:: $export YOURAPPLICATION_SETTINGS=/path/to/settings.cfg$ python run-app.py * Running on http://127.0.0.1:5000/ * Restarting with reloader...On Windows systems use the set builtin instead:: >set YOURAPPLICATION_SETTINGS=\path\to\settings.cfgThe configuration files themselves are actual Python files. Only valuesin uppercase are actually stored in the config object later on. So makesure to use uppercase letters for your config keys.Here is an example of a configuration file:: # Example configuration DEBUG = False SECRET_KEY = '?\xbf,\xb4\x8d\xa3"<\x9c\xb0@\x0f5\xab,w\xee\x8d$0\x13\x8b83'Make sure to load the configuration very early on, so that extensions havethe ability to access the configuration when starting up. There are othermethods on the config object as well to load from individual files. For acomplete reference, read the :class:~flask.Config object'sdocumentation.Configuration Best Practices----------------------------The downside with the approach mentioned earlier is that it makes testinga little harder. There is no single 100% solution for this problem ingeneral, but there are a couple of things you can keep in mind to improvethat experience:1. create your application in a function and register blueprints on it. That way you can create multiple instances of your application with different configurations attached which makes unittesting a lot easier. You can use this to pass in configuration as needed.2. Do not write code that needs the configuration at import time. If you limit yourself to request-only accesses to the configuration you can reconfigure the object later on as needed.Development / Production------------------------Most applications need more than one configuration. There should be atleast separate configurations for the production server and the one usedduring development. The easiest way to handle this is to use a defaultconfiguration that is always loaded and part of the version control, and aseparate configuration that overrides the values as necessary as mentionedin the example above:: app = Flask(__name__) app.config.from_object('yourapplication.default_settings') app.config.from_envvar('YOURAPPLICATION_SETTINGS')Then you just have to add a separate config.py file and exportYOURAPPLICATION_SETTINGS=/path/to/config.py and you are done. Howeverthere are alternative ways as well. For example you could use imports orsubclassing.What is very popular in the Django world is to make the import explicit inthe config file by adding an from yourapplication.default_settingsimport * to the top of the file and then overriding the changes by hand.You could also inspect an environment variable likeYOURAPPLICATION_MODE and set that to production, development etcand import different hardcoded files based on that.An interesting pattern is also to use classes and inheritance forconfiguration:: class Config(object): DEBUG = False TESTING = False DATABASE_URI = 'sqlite://:memory:' class ProductionConfig(Config): DATABASE_URI = 'mysql://user@localhost/foo' class DevelopmentConfig(Config): DEBUG = True class TestingConfig(Config): TESTING = TrueTo enable such a config you just have to call into:meth:~flask.Config.from_object:: app.config.from_object('configmodule.ProductionConfig')There are many different ways and it's up to you how you want to manageyour configuration files. However here a list of good recommendations:- keep a default configuration in version control. Either populate the config with this default configuration or import it in your own configuration files before overriding values.- use an environment variable to switch between the configurations. This can be done from outside the Python interpreter and makes development and deployment much easier because you can quickly and easily switch between different configs without having to touch the code at all. If you are working often on different projects you can even create your own script for sourcing that activates a virtualenv and exports the development configuration for you.- Use a tool like fabric_ in production to push code and configurations separately to the production server(s). For some details about how to do that, head over to the :ref:fabric-deployment pattern... _fabric: http://fabfile.org/.. _instance-folders:Instance Folders----------------.. versionadded:: 0.8Flask 0.8 introduces instance folders. Flask for a long time made itpossible to refer to paths relative to the application's folder directly(via :attr:Flask.root_path). This was also how many developers loadedconfigurations stored next to the application. Unfortunately however thisonly works well if applications are not packages in which case the rootpath refers to the contents of the package.With Flask 0.8 a new attribute was introduced::attr:Flask.instance_path. It refers to a new concept called the“instance folder”. The instance folder is designed to not be underversion control and be deployment specific. It's the perfect place todrop things that either change at runtime or configuration files.You can either explicitly provide the path of the instance folder whencreating the Flask application or you can let Flask autodetect theinstance folder. For explicit configuration use the instance_pathparameter:: app = Flask(__name__, instance_path='/path/to/instance/folder')Please keep in mind that this path *must* be absolute when provided.If the instance_path parameter is not provided the following defaultlocations are used:- Uninstalled module:: /myapp.py /instance- Uninstalled package:: /myapp /__init__.py /instance- Installed module or package::$PREFIX/lib/python2.X/site-packages/myapp        $PREFIX/var/myapp-instance $PREFIX is the prefix of your Python installation. This can be    /usr or the path to your virtualenv. You can print the value of    sys.prefix to see what the prefix is set to.Since the config object provided loading of configuration files fromrelative filenames we made it possible to change the loading via filenamesto be relative to the instance path if wanted. The behavior of relativepaths in config files can be flipped between “relative to the applicationroot” (the default) to “relative to instance folder” via theinstance_relative_config switch to the application constructor:: app = Flask(__name__, instance_relative_config=True)Here is a full example of how to configure Flask to preload the configfrom a module and then override the config from a file in the configfolder if it exists:: app = Flask(__name__, instance_relative_config=True) app.config.from_object('yourapplication.default_settings') app.config.from_pyfile('application.cfg', silent=True)The path to the instance folder can be found via the:attr:Flask.instance_path. Flask also provides a shortcut to open afile from the instance folder with :meth:Flask.open_instance_resource.Example usage for both:: filename = os.path.join(app.instance_path, 'application.cfg') with open(filename) as f: config = f.read() # or via open_instance_resource: with app.open_instance_resource('application.cfg') as f: config = f.read()
Something went wrong with that request. Please try again.