Flask学习笔记——配置管理

1、硬编码:

app = Flask(__name__)

# app.config 是flask.config.Config类的实例,继承自内置数据结构dict
app.config[‘DEBUG‘] = True

2、参考——flask.config.Config类:

class Config(dict):
    """Works exactly like a dict but provides ways to fill it from files
    or special dictionaries.  There are two common patterns to populate the
    config.

    Either you can fill the config from a config file::

        app.config.from_pyfile(‘yourconfig.cfg‘)

    Or alternatively you can define the configuration options in the
    module that calls :meth:`from_object` or provide an import path to
    a module that should be loaded.  It is also possible to tell it to
    use the same module and with that provide the configuration values
    just before the call::

        DEBUG = True
        SECRET_KEY = ‘development key‘
        app.config.from_object(__name__)

    In both cases (loading from any Python file or loading from modules),
    only uppercase keys are added to the config.  This makes it possible to use
    lowercase values in the config file for temporary values that are not added
    to the config or to define the config keys in the same file that implements
    the application.

    Probably the most interesting way to load configurations is from an
    environment variable pointing to a file::

        app.config.from_envvar(‘YOURAPPLICATION_SETTINGS‘)

    In this case before launching the application you have to set this
    environment variable to the file you want to use.  On Linux and OS X
    use the export statement::

        export YOURAPPLICATION_SETTINGS=‘/path/to/config/file‘

    On windows use `set` instead.

    :param root_path: path to which files are read relative from.  When the
                      config object is created by the application, this is
                      the application‘s :attr:`~flask.Flask.root_path`.
    :param defaults: an optional dictionary of default values
    """

    def __init__(self, root_path, defaults=None):
        dict.__init__(self, defaults or {})
        self.root_path = root_path

    def from_envvar(self, variable_name, silent=False):
        """Loads a configuration from an environment variable pointing to
        a configuration file.  This is basically just a shortcut with nicer
        error messages for this line of code::

            app.config.from_pyfile(os.environ[‘YOURAPPLICATION_SETTINGS‘])

        :param variable_name: name of the environment variable
        :param silent: set to ``True`` if you want silent failure for missing
                       files.
        :return: bool. ``True`` if able to load config, ``False`` otherwise.
        """
        rv = os.environ.get(variable_name)
        if not rv:
            if silent:
                return False
            raise RuntimeError(‘The environment variable %r is not set ‘
                               ‘and as such configuration could not be ‘
                               ‘loaded.  Set this variable and make it ‘
                               ‘point to a configuration file‘ %
                               variable_name)
        return self.from_pyfile(rv, silent=silent)

    def from_pyfile(self, filename, silent=False):
        """Updates the values in the config from a Python file.  This function
        behaves as if the file was imported as module with the
        :meth:`from_object` function.

        :param filename: the filename of the config.  This can either be an
                         absolute filename or a filename relative to the
                         root path.
        :param silent: set to ``True`` if you want silent failure for missing
                       files.

        .. versionadded:: 0.7
           `silent` parameter.
        """
        filename = os.path.join(self.root_path, filename)
        d = types.ModuleType(‘config‘)
        d.__file__ = filename
        try:
            with open(filename, mode=‘rb‘) as config_file:
                exec(compile(config_file.read(), filename, ‘exec‘), d.__dict__)
        except IOError as e:
            if silent and e.errno in (errno.ENOENT, errno.EISDIR):
                return False
            e.strerror = ‘Unable to load configuration file (%s)‘ % e.strerror
            raise
        self.from_object(d)
        return True

    def from_object(self, obj):
        """Updates the values from the given object.  An object can be of one
        of the following two types:

        -   a string: in this case the object with that name will be imported
        -   an actual object reference: that object is used directly

        Objects are usually either modules or classes. :meth:`from_object`
        loads only the uppercase attributes of the module/class. A ``dict``
        object will not work with :meth:`from_object` because the keys of a
        ``dict`` are not attributes of the ``dict`` class.

        Example of module-based configuration::

            app.config.from_object(‘yourapplication.default_config‘)
            from yourapplication import default_config
            app.config.from_object(default_config)

        You should not use this function to load the actual configuration but
        rather configuration defaults.  The actual config should be loaded
        with :meth:`from_pyfile` and ideally from a location not within the
        package because the package might be installed system wide.

        See :ref:`config-dev-prod` for an example of class-based configuration
        using :meth:`from_object`.

        :param obj: an import name or object
        """
        if isinstance(obj, string_types):
            obj = import_string(obj)
        for key in dir(obj):
            if key.isupper():
                self[key] = getattr(obj, key)

    def from_json(self, filename, silent=False):
        """Updates the values in the config from a JSON file. This function
        behaves as if the JSON object was a dictionary and passed to the
        :meth:`from_mapping` function.

        :param filename: the filename of the JSON file.  This can either be an
                         absolute filename or a filename relative to the
                         root path.
        :param silent: set to ``True`` if you want silent failure for missing
                       files.

        .. versionadded:: 0.11
        """
        filename = os.path.join(self.root_path, filename)

        try:
            with open(filename) as json_file:
                obj = json.loads(json_file.read())
        except IOError as e:
            if silent and e.errno in (errno.ENOENT, errno.EISDIR):
                return False
            e.strerror = ‘Unable to load configuration file (%s)‘ % e.strerror
            raise
        return self.from_mapping(obj)

    def from_mapping(self, *mapping, **kwargs):
        """Updates the config like :meth:`update` ignoring items with non-upper
        keys.

        .. versionadded:: 0.11
        """
        mappings = []
        if len(mapping) == 1:
            if hasattr(mapping[0], ‘items‘):
                mappings.append(mapping[0].items())
            else:
                mappings.append(mapping[0])
        elif len(mapping) > 1:
            raise TypeError(
                ‘expected at most 1 positional argument, got %d‘ % len(mapping)
            )
        mappings.append(kwargs.items())
        for mapping in mappings:
            for (key, value) in mapping:
                if key.isupper():
                    self[key] = value
        return True

    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‘
            }

        This is often useful when configuration options map directly to
        keyword arguments in functions or class constructors.

        :param namespace: a configuration namespace
        :param lowercase: a flag indicating if the keys of the resulting
                          dictionary should be lowercase
        :param trim_namespace: a flag indicating if the keys of the resulting
                          dictionary should not include the namespace

        .. versionadded:: 0.11
        """
        rv = {}
        for k, v in iteritems(self):
            if not k.startswith(namespace):
                continue
            if trim_namespace:
                key = k[len(namespace):]
            else:
                key = k
            if lowercase:
                key = key.lower()
            rv[key] = v
        return rv

    def __repr__(self):
        return ‘<%s %s>‘ % (self.__class__.__name__, dict.__repr__(self))

3、想要集中管理设置项,将它们放到一个文件里面——settings.py,可以通过三种方式加载:

# 方式一、通过配置文件加载
# 通过模块的字符串名
app.config.from_object(‘settings‘)
# 或者导入后直接传入模块对象
import settings
app.config.from_objcet(settings)

# 方式二、通过文件全名,不限于.py后缀的文件
# slient=True, 文件不存在时只返回False, 不抛出异常
app.config.from_pyfile(‘settings.py‘, silent=True)

# 方式三、通过环境变量加载,也支持silent参数。获得路径后其实
# 还是使用from_pyfile的方式加载
> export YOURAPPLICATION_SETTINGS=‘settings.py‘
app.config.from_envvar(‘YOURAPPLICATION_SETTINGS‘)
时间: 2024-10-07 07:36:38

Flask学习笔记——配置管理的相关文章

flask学习笔记(-操作数据库)

Python 数据库框架 大多数的数据库引擎都有对应的 Python 包,包括开源包和商业包.Flask 并不限制你使用何种类型的数据库包,因此可以根据自己的喜好选择使用 MySQL.Postgres.SQLite.Redis.MongoDB 或者 CouchDB. 如果这些都无法满足需求,还有一些数据库抽象层代码包供选择,例如SQLAlchemy和MongoEngine.你可以使用这些抽象包直接处理高等级的 python 对象,而不用处理如表.文档或查询语言此类的数据库实体. 选择数据库框架的

Flask学习笔记-No module named flask.ext.wtf

1 from flask.ext.wtf import Form 2 from wtforms import StringField,BooleanField 3 from wtforms.validators import DataRequired 4 5 class LoginForm(Form): 6 openid = StringField('openid',validators=[DataRequired()]) 7 remember_me = BooleanField('rememb

flask学习笔记(-数据库)

Python 数据库框架 大多数的数据库引擎都有对应的 Python 包,包括开源包和商业包.Flask 并不限制你使用何种类型的数据库包,因此可以根据自己的喜好选择使用 MySQL.Postgres.SQLite.Redis.MongoDB 或者 CouchDB. 如果这些都无法满足需求,还有一些数据库抽象层代码包供选择,例如SQLAlchemy和MongoEngine.你可以使用这些抽象包直接处理高等级的 Python 对象,而不用处理如表.文档或查询语言此类的数据库实体. 选择数据库框架的

flask学习笔记之--表单控件

表单验证 Flask-WTF 从 version 0.9.0有了变化,正确要引用wtforms包 正确的写法: from flask.ext.wtf import Form from wtforms import TextField, BooleanField from wtforms.validators import Required

Flask学习笔记(3)-数据库迁移

数据库迁移 通过创建虚拟flask环境来迁移数据库. 一.创建虚拟环境 virtualenvwrapper库中有个mkvirtualenv函数,用来创建虚拟环境(make virtual envirement).使用命令 mkvirtualenv flask-tutorial --python=python3.6 创建一个名为flask-tutorial的虚拟环境,如图可利用workon flask-tutorial命令激活这个虚拟环境.使用deactivate退出这个虚拟环境.在默认条件下,虚

flask学习笔记1

Flask是一个基于Python开发并且依赖jinja2模板和Werkzeug WSGI服务的一个微型框架,对于Werkzeug本质是Socket服务端,其用于接收http请求并对请求进行预处理,然后触发Flask框架,开发人员基于Flask框架提供的功能对请求进行相应的处理,并返回给用户,如果要返回给用户复杂的内容时,需要借助jinja2模板来实现对模板的处理,即:将模板和数据进行渲染,将渲染后的字符串返回给用户浏览器. "微"(micro) 并不表示你需要把整个 Web 应用塞进单

flask学习笔记(1)-虚拟环境安装

Mac(类Linux): pip install virtualenv mkdir testvirtualenv cd testvirtualenv virtualenv flask-env#创建虚拟环境 source bin/activate#激活虚拟环境 deactivate#退出虚拟环境 windows: virtualenv flask-env cd Scripts activate 决定入Flask这个坑竟然是为了给公司的问卷分析产品做一个前端,这样能通过Python对数据库做一些操作

Flask学习笔记

1.路由用"/"结尾. 比如@app.route("/about/"),可以匹配/about和/about/,而@app.route("/about")不能匹配/about/ 2.url_for:就是一个根据函数名,找到对应路由,返回一个url字符串的函数而已. 3.静态地址默认为static,可以访问静态文件,如http://127.0.0.1/static/logo.png

Flask 学习笔记-第十五章-应用编程接口

(Rich Internet Application,RIA)的架构. 在RIA中,服务器的主要功能(有时是唯一功能)是为客户端提供数据存取服务. 在这种模式中,服务器变成了Web服务或应用编程接口(Application Programming Interface,API). 表现层状态转移(Representational State Transfer,REST)架构崭 露头角,成为Web程序的新宠,因为这种架构建立在大家熟识的万维网 基础之上. Web服务的REST架构方式,并列出了6个符