从数据库条目获取应用程序配置 [英] Get app config from database entries

查看:45
本文介绍了从数据库条目获取应用程序配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种从数据库条目中设置一些静态应用程序配置值(作为werkzeug服务器端口)的方法.我的应用程序使用SQLAlchemy和蓝图,当前从一个对象(config.py)获取配置.

I'm looking for a way to set some static app config value (as werkzeug server port) from database entries. My app uses SQLAlchemy and blueprints, and currently gets config from an object (config.py).

假设数据库的配置仍然来自配置文件,那么如何从数据库配置应用程序的其余部分?

Assuming the configuration for the database still comes from a config file, how can I configure the rest of the application from a database?

推荐答案

从表中读取键/值项,并从这些项中设置配置.请记住,值列只能具有一种类型(我在这里使用String了).解决此问题的一种方法是创建具有不同值类型的多态表,但这超出了此答案的范围.我在这里通过显式命名应为其他类型的键来解决此问题.

Read the key/value items from a table and set the config from those items. Keep in mind that the value column can only have one type (I've gone with String here). One way to solve this is to create polymorphic tables with different value types, but that's beyond the scope of this answer. I've solved it here by explicitly naming keys that should be a different type.

import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

# assuming the database is an sqlite file "app.db" in the instance folder
app.config['SQLALCHEMY_DATABASE_URI'] = os.path.join(app.instance_path, 'app.db')
db = SQLAlchemy()
db.init_app(app)


class ConfigItem(db.Model):
    """Represents one config item.

    All values are strings, so non-string values must be converted later.

    :param key: config key
    :param value: configured value
    """

    __tablename__ = 'config_item'

    key = db.Column(db.String, primary_key=True)
    value = db.Column(db.String)

    def __str__(self):
        return '{}: {}'.format(self.key, self.value)

    def __repr__(self):
        return 'ConfigItem(key={!r}, value={!r})'.format(self.key, self.value)


# map a converter function to key names, so that values will be converted from strings to the correct type
# this is just the mapper for Flask config keys, the list will be much longer will extension config keys added
config_types = {
    lambda value: value == 'True': ('DEBUG', 'PROPAGATE_EXCEPTIONS', 'PRESERVE_CONTEXT_ON_EXCEPTION', 'SESSION_COOKIE_HTTPONLY', 'SESSION_COOKIE_SECURE', 'USE_X_SENDFILE', 'TRAP_HTTP_EXCEPTIONS', 'TRAP_BAD_REQUEST_ERRORS', 'JSON_AS_ASCII', 'JSON_SORT_KEYS', 'JSONIFY_PRETTYPRINT_REGULAR'),
    int: ('PERMANENT_SESSION_LIFETIME', 'MAX_CONTENT_LENGTH', 'SEND_FILE_MAX_AGE_DEFAULT')
}
# convert the type to key list mapping above to a key to type mapping
config_types = {key: type for type, keys in config_types.items() for key in keys}

# flask_sqlalchemy database connections only work in an app context
# we're not in a request handler, so have to create the context explicitly
with app.app_context():
    for item in ConfigItem.query:
        # set the config value for each key, converting it if it's not a string
        if item.key in config_types:
            app.config[item.key] = config_types[item.key](value)
        else:
            app.config[item.key.upper()] = item.value

这篇关于从数据库条目获取应用程序配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆