Inside Flask - Implementation of configuration

flask Configuration objects for app.config Itself is very simple to use , It's just in the form of a dictionary , And its implementation , It's in the form of a dictionary .

stay flask/config.py In file , Contains flask Configuration implementation code , There are only two classes ConfigAttribute and Config .

ConfigAttribute Represents a configuration property , Its code is just a few lines , But because of the use of descriptor Pattern , Yes python It's not easy for unfamiliar people to understand . Have a look first descriptor What is it .

descriptor Belong to python The concept of metaprogramming ( It's programming for programming ,%>_<%), Essentially, it provides a programming protocol , That is to develop a framework for business programming ( image C# / java Reflection is also part of metaprogramming ). Because of the nature of dynamic languages , Metaprogramming in python It's very simple to implement . As descriptor The object of , It provides a protocol for describing properties , It needs to be implemented __get__ __set__ and __delete__, To describe an object ( The described object ) How to get data 、 Set data and delete objects .

Now let's take a look at ConfigAttribute class ::

class ConfigAttribute(object):
"""Makes an attribute forward to the config""" def __init__(self, name, get_converter=None):
self.__name__ = name
self.get_converter = get_converter def __get__(self, obj, type=None):
if obj is None:
return self
rv = obj.config[self.__name__]
if self.get_converter is not None:
rv = self.get_converter(rv)
return rv def __set__(self, obj, value):
obj.config[self.__name__] = value

The convention here is to define ConfigAttribute In the object of , It should contain a config Dictionaries , And then when you take a value or set a value , Change to take or set config Corresponding key Value ( stay flask Of Flask In class , contain config, Type is what we're going to see next Config class ).

Config Class inheritance dict , It's a preservation ConfigAttribute Dictionary ::

class Config(dict):
...

meanwhile ,Config Class provides several ways to load configuration , Namely ::

from_envvar(...) # Read the to load from the environment variable py File path , And then use from_pyfile load 
from_pyfile(...) # from py Load file from file , And then use from_object load
from_object(...) # Load from object , hold dir(obj) in , Data whose name is uppercase is loaded into self
from_json(...) # from json File loading , And then call from_mapping load
from_mapping(...) # From multiple dictionaries , or **kwargs Parameters of form , And the data whose name is uppercase is loaded into self

When loading a file , You can use the flask Relative paths within applications ( See below ), Or use absolute paths , Code in processing , Use both ::

filename = os.path.join(self.root_path, filename)

When the file is a relative path , I'll use the current flask app The path of the file is combined with the relative path to locate the file .

Config There are two configurations in namespace The concept of , adopt Underline Classify the parameters , It is convenient to obtain multiple configuration items at one time ::

def get_namespace(self, namespace, lowercase=True, trim_namespace=True):
"""Returns a dictionary containing a subset of configuration options
that match the specified namespace/prefix. Example usage:: app.config['IMAGE_STORE_TYPE'] = 'fs'
app.config['IMAGE_STORE_PATH'] = '/var/app/images'
app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com'
image_store_config = app.config.get_namespace('IMAGE_STORE_') The resulting dictionary `image_store_config` would look like:: {
'type': 'fs',
'path': '/var/app/images',
'base_url': 'http://img.website.com'
}

From the source code level , Here are a few points to pay attention to :(1) The last thing that works from_object and from_mapping, The others are pretreatment ;(2) Configured key It should be in capitals , And then I'm going to separate them with the underscores

OK, Now look at flask How to use configuration inside .

First, in the flask/app.py Inside ,Flask Class code contains a config_class , It defaults to Config class . then config Property through make_config Generate ::

self.config = self.make_config(instance_relative_config)

and make_config The code for is as follows ::

def make_config(self, instance_relative=False):
"""Used to create the config attribute by the Flask constructor.
The `instance_relative` parameter is passed in from the constructor
of Flask (there named `instance_relative_config`) and indicates if
the config should be relative to the instance path or the root path
of the application. .. versionadded:: 0.8
"""
root_path = self.root_path
if instance_relative:
root_path = self.instance_path
return self.config_class(root_path, self.default_config)

The concept here is instance_relative Configuration of , That is, the configuration related to the instance . If you use several in an application flask app , And these app When the configuration is different , We need to use instance related configuration , Change the current root_path Set to initialize flask app Time parameters instance_path( Free to set ).

self.default_config Is a default dictionary , as follows ::

default_config = ImmutableDict({
'DEBUG': get_debug_flag(default=False),
'TESTING': False,
'PROPAGATE_EXCEPTIONS': None,
'PRESERVE_CONTEXT_ON_EXCEPTION': None,
'SECRET_KEY': None,
'PERMANENT_SESSION_LIFETIME': timedelta(days=31),
'USE_X_SENDFILE': False,
...
})

And the use of ConfigAttribute The following are some of the codes for ::

debug = ConfigAttribute('DEBUG')
...
testing = ConfigAttribute('TESTING')
...

flask After setting configuration items , Users can choose according to their own needs , Modify by manipulating the dictionary 、 Update configuration ::

app.config.update({'DEBUG': False})
app.config.from_object(config_obj)
app.config.setdefault('DEBUG', False)
...

Inside Flask - Configuration of the implementation of more related articles

  1. Inside Flask - json Handle

    Inside Flask - json Handle Processing web api when ,json It's a very useful data exchange format , It has a simple structure , Basically, all kinds of mainstream programming languages have good support tools . flask In dealing with json when ...

  2. Inside Flask - app.py - 2

    Inside Flask - app.py - 2 Flask Initialize parameters Flass Class is Flask The core of the framework , One flask Object processing view function registration .URL The rules . Template configuration . Parameter setting and so on . commonly ...

  3. Inside Flask - app.py - 1

    Inside Flask - app.py - 1 except werkzeug and jinja2 And so on ,app.py Is in Flask Of __init__.py The first one imported in Flask The mold of oneself ...

  4. Inside Flask - signal Signaling mechanism

    Inside Flask - signal Signaling mechanism singal In the ordinary flask web Less contact with... In the development process , But for the use of flask When developing at the framework level , We must understand the relevant working mechanism .flas ...

  5. Inside Flask - globals Global variables ( Object agent )

    Inside Flask - globals Global variables ( Object agent ) A frame is a container , Programming within a framework , In general, it is necessary to abide by the conventions and usage patterns of the framework . The usual pattern is IoC, That is, the framework calls the user's code , Instead of the user calling the framework ...

  6. Inside Flask - flask Extend the loading process

    Inside Flask - flask Extend the loading process flask Expand ( plug-in unit ) Usually with flask_< Extension name > For the extended python Package name , And when you use it , You can use import flask. ...

  7. Inside Flask - flask.__init__.py And core components

    Inside Flask - flask.__init__.py And core components A simple example Let's start with a simple example . Use Flask , Usually from flask Module import Flask . request etc. ...

  8. Inside Flask - Flask brief introduction

    Inside Flask - Flask brief introduction Preface Flask Our design goal is to achieve a wsgi The micro framework of , Its core code remains simple and extensible , Easy to learn . For beginners with some experience , Follow the examples and the code of some books ...

  9. Chapter eight Flask To configure

    Flask It's a very flexible, small and sophisticated web frame , So where does flexibility come from ? Columns such as   Flask To configure , How to use this thing ? How convenient can it bring us ? app To configure First of all, let's show : from fl ...

Random recommendation

  1. Custom browser protocol , Realization web The program calls the local program

    from   http://blog.csdn.net/talking12391239/article/details/40712759 Close test available tencent://Message/?Uin=000000 ...

  2. CFgym Board Queries ( rotate 、 Flip and simplify )

    http://codeforces.com/gym/100497 codeforces 2014-2015 CT S02E04: Codeforces Trainings Season 2 Episo ...

  3. linux Modify permissions for a folder and its subfolders

    Join in -R Parameters , You can pass read and write permissions to subfolders, such as chmod -R 777 /home/mypackage that mypackage The properties of the folder and all its subfolders become 777.777 Yes. . Write . perform ...

  4. Use split There is a problem with special characters during segmentation

    Use split When it's divided : String[] a="aa|bb|cc".split("|"); output: [a, a, |, b, b, |, c, c] First ...

  5. Project optimization experience sharing ( 6、 ... and )SVN Conflict and handling

    In the last blog, we shared the idea of identifying new requirements < Look at the whole situation >. Today we're going to share with you SVN Conflict resolution experience :SVN Conflict and handling ! introduction Anyone who has developed a project knows , Company development of a project will use version number control ...

  6. PLSQL Developer The next error message shows garbled code

    PLSQL Developer The next error message shows garbled code Connect to the environment :win 7 Database version number :oracle 11g Simulate a mistake , See the error prompt display "????" The code problem , For example, the following : Check ...

  7. Mycat Library sub-table

    Other methods : Snowflake algorithm or redis To achieve id The problem of non repetition . Database sub database sub table : Advantages and disadvantages of vertical splitting : Horizontal split : Piecewise enumeration : That is, according to the enumeration ( Defined constant ) Classified storage .

  8. CSS Solution to high collapse problem

    The existence of high collapse : Cause analysis 1 <!DOCTYPE html> <html> <head> <meta charset="utf-8" /& ...

  9. JS Get the last day of any month

    When getting the days of the month , Because the months are different , So the number of days per month also varies , And because of the flat leap year ,2 The number of days in the month also varies , It is very complicated to get the days of any month in the program , Here's how to solve this problem , Call this method to pass in any year and month , ...

  10. 【bzoj2001】 Hnoi2010—City urban construction

    http://www.lydsy.com/JudgeOnline/problem.php?id=2001 ( Topic link ) The question Give an undirected graph ,$m$ Group operation , Modify the weight of one edge at a time , For each operation, the output is modified ...