本文整理汇总了Python中flask.Config.from_object方法的典型用法代码示例。如果您正苦于以下问题:Python Config.from_object方法的具体用法?Python Config.from_object怎么用?Python Config.from_object使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类flask.Config
的用法示例。
在下文中一共展示了Config.from_object方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: setup
# 需要导入模块: from flask import Config [as 别名]
# 或者: from flask.Config import from_object [as 别名]
def setup(context=None, config=None, app_factory=get_app):
app_abspath = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
app_config = Config(app_abspath)
app_config.from_object('superdesk.tests.test_settings')
app_config['APP_ABSPATH'] = app_abspath
app_config.update(get_test_settings())
app_config.update(config or {})
app_config.update({
'DEBUG': True,
'TESTING': True,
})
app = app_factory(app_config)
logger = logging.getLogger('superdesk')
logger.setLevel(logging.ERROR)
logger = logging.getLogger('elasticsearch')
logger.setLevel(logging.ERROR)
logger = logging.getLogger('urllib3')
logger.setLevel(logging.ERROR)
drop_elastic(app)
drop_mongo(app)
# create index again after dropping it
app.data.init_elastic(app)
if context:
context.app = app
context.client = app.test_client()
示例2: setup_config
# 需要导入模块: from flask import Config [as 别名]
# 或者: from flask.Config import from_object [as 别名]
def setup_config(config):
app_abspath = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
app_config = Config(app_abspath)
app_config.from_object('superdesk.default_settings')
update_config(app_config)
app_config.update(config or {}, **{
'APP_ABSPATH': app_abspath,
'DEBUG': True,
'TESTING': True,
})
logging.getLogger('superdesk').setLevel(logging.WARNING)
logging.getLogger('elastic').setLevel(logging.WARNING) # elastic datalayer
logging.getLogger('elasticsearch').setLevel(logging.WARNING)
logging.getLogger('urllib3').setLevel(logging.WARNING)
return app_config
示例3: ConfigurationRegistry
# 需要导入模块: from flask import Config [as 别名]
# 或者: from flask.Config import from_object [as 别名]
class ConfigurationRegistry(ModuleDiscoveryRegistry):
"""
Specialized ``ModuleDiscoveryRegistry`` that search for ``config`` modules
in a list of Python packages and merge them into the Flask application
config without overwriting already set variables.
:param app: A Flask application
:param registry_namespace: The registry namespace of an
``ImportPathRegistry`` with a list Python packages to search for
``config`` modules in. Defaults to ``packages``.
"""
def __init__(self, app, registry_namespace=None):
super(ConfigurationRegistry, self).__init__(
'config',
registry_namespace=registry_namespace,
with_setup=False,
)
# Create a new configuration module to collect configuration in.
from flask import Config
self.new_config = Config(app.config.root_path)
# Auto-discover configuration in packages
self.discover(app)
# Overwrite default configuration with user specified configuration
self.new_config.update(app.config)
app.config = self.new_config
def register(self, new_object):
"""
Register a new ``config`` module.
:param new_object: The configuration module.
``app.config.from_object()`` will be called on it.
"""
self.new_config.from_object(new_object)
super(ConfigurationRegistry, self).register(new_object)
def unregister(self, *args, **kwargs):
"""
It is not possible to unregister configuration.
"""
raise NotImplementedError()
示例4: main
# 需要导入模块: from flask import Config [as 别名]
# 或者: from flask.Config import from_object [as 别名]
def main(expected):
config = Config(here)
config.from_object('ooi_status.default_settings')
if 'OOISTATUS_SETTINGS' in os.environ:
config.from_envvar('OOISTATUS_SETTINGS')
for key in config:
log.info('OOI_STATUS CONFIG: %r: %r', key, config[key])
monitor = StatusMonitor(config)
if expected:
monitor.read_expected_csv(expected)
else:
scheduler = BlockingScheduler()
log.info('adding jobs')
# notify on change every minute
scheduler.add_job(monitor.check_all, 'cron', second=0)
scheduler.add_job(monitor.notify_all, 'cron', second=10)
log.info('starting jobs')
scheduler.start()
示例5: ConfigurationRegistry
# 需要导入模块: from flask import Config [as 别名]
# 或者: from flask.Config import from_object [as 别名]
class ConfigurationRegistry(ModuleDiscoveryRegistry):
"""
Specialized import path registry that takes the initial list of import
paths from ``PACKAGES`` configuration variable.
Example::
app.extensions['registry']['packages'] = PackageRegistry()
app.extendsions['registry']['config'] = ConfigurationRegistry(
_app, base_config='invenio.core.config'
)
"""
def __init__(self, app, registry_namespace=None):
super(ConfigurationRegistry, self).__init__(
'config',
registry_namespace=registry_namespace,
with_setup=False,
)
# Create a new configuration module to collect configuration in.
from flask import Config
self.new_config = Config(app.config.root_path)
# Auto-discover configuration in packages
self.discover(app)
# Overwrite default configuration with user specified configuration
self.new_config.update(app.config)
app.config = self.new_config
def register(self, new_object):
self.new_config.from_object(new_object)
super(ConfigurationRegistry, self).register(new_object)
def unregister(self, *args, **kwargs):
raise NotImplementedError()
示例6: Config
# 需要导入模块: from flask import Config [as 别名]
# 或者: from flask.Config import from_object [as 别名]
* DATABASE
Currently the supported environment variables:
* OpenShift
* DATABASE_URI
"""
import os
from flask import Config
from sqlalchemy.engine.url import URL
config = Config(".")
config.from_object("compair.settings")
config.from_pyfile(os.path.join(os.path.dirname(os.path.abspath(__file__)), "../config.py"), silent=True)
if os.environ.get("OPENSHIFT_MYSQL_DB_HOST"):
config["SQLALCHEMY_DATABASE_URI"] = URL(
"mysql+pymysql",
host=os.getenv("OPENSHIFT_MYSQL_DB_HOST", "localhost"),
port=os.getenv("OPENSHIFT_MYSQL_DB_PORT", "3306"),
username=os.getenv("OPENSHIFT_MYSQL_DB_USERNAME", "compair"),
password=os.getenv("OPENSHIFT_MYSQL_DB_PASSWORD", "compair"),
database=os.getenv("OPENSHIFT_GEAR_NAME", "compair"),
)
elif (
os.environ.get("DB_HOST")
or os.environ.get("DB_PORT")
or os.environ.get("DB_USERNAME")
示例7: Config
# 需要导入模块: from flask import Config [as 别名]
# 或者: from flask.Config import from_object [as 别名]
* DATABASE
Currently the supported environment variables:
* OpenShift
* DATABASE_URI
"""
import os
from flask import Config
from sqlalchemy.engine.url import URL
config = Config('.')
config.from_object('acj.settings')
config.from_pyfile(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../config.py'), silent=True)
if os.environ.get('OPENSHIFT_MYSQL_DB_HOST'):
config['SQLALCHEMY_DATABASE_URI'] = URL({
'drivername': 'mysql',
'host': os.environ.get('OPENSHIFT_MYSQL_DB_HOST'),
'port': os.environ.get('OPENSHIFT_MYSQL_DB_PORT'),
'username': os.environ.get('OPENSHIFT_MYSQL_DB_USERNAME'),
'password': os.environ.get('OPENSHIFT_MYSQL_DB_PASSWORD'),
'database': os.environ.get('OPENSHIFT_GEAR_NAME'),
})
elif os.environ.get('DATABASE_URI'):
config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URI')
elif "DATABASE" in config and 'DATABASE_URI' not in config:
config['SQLALCHEMY_DATABASE_URI'] = URL(**config['DATABASE'])
示例8: Config
# 需要导入模块: from flask import Config [as 别名]
# 或者: from flask.Config import from_object [as 别名]
from flask import Config
from os import path
config = Config('../')
config.from_object('config')
if path.exists(config["IMAGEMAGICK_CONVERT"]) is False:
raise StandardError("No imagemagick 'convert' found. Check your config or/and install imagemagick.")
from ifsApprover.DB import DB
db = DB(config["DB_NAME"])
示例9: get_user_config
# 需要导入模块: from flask import Config [as 别名]
# 或者: from flask.Config import from_object [as 别名]
def get_user_config():
from flask import Config
config = Config('/')
config.from_object('alerta.settings')
config.from_pyfile('/etc/alertad.conf', silent=True)
config.from_envvar('ALERTA_SVR_CONF_FILE', silent=True)
if 'DEBUG' in os.environ:
config['DEBUG'] = True
if 'BASE_URL' in os.environ:
config['BASE_URL'] = os.environ['BASE_URL']
if 'USE_PROXYFIX' in os.environ:
config['USE_PROXYFIX'] = True if os.environ['USE_PROXYFIX'] == 'True' else False
if 'SECRET_KEY' in os.environ:
config['SECRET_KEY'] = os.environ['SECRET_KEY']
database_url = (
os.environ.get('DATABASE_URL', None) or
# The following database settings are deprecated.
os.environ.get('MONGO_URI', None) or
os.environ.get('MONGODB_URI', None) or
os.environ.get('MONGOHQ_URL', None) or
os.environ.get('MONGOLAB_URI', None)
)
# Use app config for DATABASE_URL if no env var from above override it
config['DATABASE_URL'] = database_url or config['DATABASE_URL']
if 'DATABASE_NAME' in os.environ:
config['DATABASE_NAME'] = os.environ['DATABASE_NAME']
if 'AUTH_REQUIRED' in os.environ:
config['AUTH_REQUIRED'] = True if os.environ['AUTH_REQUIRED'] == 'True' else False
if 'AUTH_PROVIDER' in os.environ:
config['AUTH_PROVIDER'] = os.environ['AUTH_PROVIDER']
if 'ADMIN_USERS' in os.environ:
config['ADMIN_USERS'] = os.environ['ADMIN_USERS'].split(',')
if 'SIGNUP_ENABLED' in os.environ:
config['SIGNUP_ENABLED'] = True if os.environ['SIGNUP_ENABLED'] == 'True' else False
if 'CUSTOMER_VIEWS' in os.environ:
config['CUSTOMER_VIEWS'] = True if os.environ['CUSTOMER_VIEWS'] == 'True' else False
if 'OAUTH2_CLIENT_ID' in os.environ:
config['OAUTH2_CLIENT_ID'] = os.environ['OAUTH2_CLIENT_ID']
if 'OAUTH2_CLIENT_SECRET' in os.environ:
config['OAUTH2_CLIENT_SECRET'] = os.environ['OAUTH2_CLIENT_SECRET']
if 'ALLOWED_EMAIL_DOMAINS' in os.environ:
config['ALLOWED_EMAIL_DOMAINS'] = os.environ['ALLOWED_EMAIL_DOMAINS'].split(',')
if 'AZURE_TENANT' in os.environ:
config['AZURE_TENANT'] = os.environ['AZURE_TENANT']
if 'GITHUB_URL' in os.environ:
config['GITHUB_URL'] = os.environ['GITHUB_URL']
if 'ALLOWED_GITHUB_ORGS' in os.environ:
config['ALLOWED_GITHUB_ORGS'] = os.environ['ALLOWED_GITHUB_ORGS'].split(',')
if 'GITLAB_URL' in os.environ:
config['GITLAB_URL'] = os.environ['GITLAB_URL']
if 'ALLOWED_GITLAB_GROUPS' in os.environ:
config['ALLOWED_OIDC_ROLES'] = os.environ['ALLOWED_GITLAB_GROUPS'].split(',')
if 'KEYCLOAK_URL' in os.environ:
config['KEYCLOAK_URL'] = os.environ['KEYCLOAK_URL']
if 'KEYCLOAK_REALM' in os.environ:
config['KEYCLOAK_REALM'] = os.environ['KEYCLOAK_REALM']
if 'ALLOWED_KEYCLOAK_ROLES' in os.environ:
config['ALLOWED_OIDC_ROLES'] = os.environ['ALLOWED_KEYCLOAK_ROLES'].split(',')
if 'OIDC_ISSUER_URL' in os.environ:
config['OIDC_ISSUER_URL'] = os.environ['OIDC_ISSUER_URL']
if 'ALLOWED_OIDC_ROLES' in os.environ:
config['ALLOWED_OIDC_ROLES'] = os.environ['ALLOWED_OIDC_ROLES'].split(',')
if 'PINGFEDERATE_OPENID_ACCESS_TOKEN_URL' in os.environ:
config['PINGFEDERATE_OPENID_ACCESS_TOKEN_URL'] = os.environ['PINGFEDERATE_OPENID_ACCESS_TOKEN_URL'].split(
',')
if 'PINGFEDERATE_OPENID_PAYLOAD_USERNAME' in os.environ:
config['PINGFEDERATE_OPENID_PAYLOAD_USERNAME'] = os.environ['PINGFEDERATE_OPENID_PAYLOAD_USERNAME'].split(
',')
if 'PINGFEDERATE_OPENID_PAYLOAD_EMAIL' in os.environ:
config['PINGFEDERATE_OPENID_PAYLOAD_EMAIL'] = os.environ['PINGFEDERATE_OPENID_PAYLOAD_EMAIL'].split(',')
if 'PINGFEDERATE_OPENID_PAYLOAD_GROUP' in os.environ:
#.........这里部分代码省略.........
示例10: Configurator
# 需要导入模块: from flask import Config [as 别名]
# 或者: from flask.Config import from_object [as 别名]
class Configurator(object):
"""
Object that takes care of loading the different configurations from the
different sources. There are 3 types of settings:
* Project: The basic set of settings needed by the system. These are
shipped with Shiva.
* Local: Specific to each instance, useful for overwriting system
settings. Some of them must be defined before running Shiva, like the
DB URI.
* Debug: This setting will only be loaded if ``DEBUG`` is set to True
in the local settings.
There are also 3 different places where Shiva looks for this config files:
* A ``local.py`` file inside the ``config/`` directory, relative to
Shiva.
* The ``$SHIVA_CONFIG`` environment variable. It's assumed to be
pointing to a file (not a dir) if exists.
* The ``$XDG_CONFIG_HOME/shiva/config.py`` file. If
``$XDG_CONFIG_HOME`` is not set, defaults to ``$HOME/.config``, as
defined by the `XDG Base Directory Specification
<http://standards.freedesktop.org/basedir-spec/basedir-spec-latest\
.html>`_.
"""
def __init__(self):
self._config = FlaskConfig("")
# project
_project = self.load_project()
# local
_xdg_config = self.from_xdg_config()
_env = self.from_env()
_local = self.from_local()
# debug
_debug = self.load_debug()
self.extract_conf(self._config)
if not (_xdg_config or _env or _local):
raise NoConfigFoundError
def load_project(self):
return self._config.from_object(project)
def get_xdg_path(self):
path_home = os.getenv("HOME")
if not path_home:
return None
default_config_home = os.path.join(path_home, ".config")
return os.getenv("XDG_CONFIG_HOME") or default_config_home
def from_xdg_config(self):
xdg_path = self.get_xdg_path()
if not xdg_path:
return False
local_py = os.path.join(xdg_path, "shiva/config.py")
if not os.path.exists(local_py):
return False
return self._config.from_pyfile(local_py)
def from_env(self):
if not os.getenv("SHIVA_CONFIG"):
return False
return self._config.from_envvar("SHIVA_CONFIG")
def from_local(self):
with ignored(ImportError):
self._config.from_object("shiva.config.local")
return True
return False
def load_debug(self):
if not self._config.get("DEBUG"):
return False
loaded = False
with ignored(ImportError):
from shiva.config import debug
loaded = self._config.from_object(debug)
xdg_path = self.get_xdg_path()
if not xdg_path:
return False
debug_py = os.path.join(xdg_path, "shiva/debug.py")
if not os.path.exists(debug_py):
return False
return self._config.from_pyfile(debug_py) or loaded
#.........这里部分代码省略.........
示例11: LoginManager
# 需要导入模块: from flask import Config [as 别名]
# 或者: from flask.Config import from_object [as 别名]
from flask_oauthlib.client import OAuth
from flask.ext.login import LoginManager, login_required, \
login_user, logout_user
from matchmaker import app
from models import User, BotIdentity
# Wire everything up
login_manager = LoginManager()
login_manager.init_app(app)
oauth = OAuth(app)
# Casino GitHub OAuth
oauth_config = Config("")
oauth_config.from_object('matchmaker.default_oauth')
oauth_config.from_envvar('CASINO_OAUTH', silent=True)
github = oauth.remote_app(
'github',
**{k.lower(): v for k, v in oauth_config.items()}
)
@app.route('/login')
def login():
return github.authorize(
callback=url_for('authorized', _external=True,
_scheme=app.config.get("PREFERRED_URL_SCHEME"))
)
示例12: create_app
# 需要导入模块: from flask import Config [as 别名]
# 或者: from flask.Config import from_object [as 别名]
def create_app(config_file=None, **kwargs):
"""
Create a new eve app object and initialize everything.
User configuration can be loaded in the following order:
1. Use the `config_file` arg to specify a file
2. If `config_file` is `None`, you set the environment variable
`AMIVAPI_CONFIG` to the path of your config file
3. If no environment variable is set either, `config.py` in the current
working directory is used
Args:
config (path): Specify config file to use.
kwargs: All other key-value arguments will be used to update the config
Returns:
(Eve): The Eve application
"""
# Load config
config = Config(getcwd())
config.from_object("amivapi.settings")
# Specified path > environment var > default path; abspath for better log
user_config = abspath(config_file or getenv('AMIVAPI_CONFIG', 'config.py'))
try:
config.from_pyfile(user_config)
config_status = "Config loaded: %s" % user_config
except IOError:
config_status = "No config found."
config.update(kwargs)
# Initialize empty domain to create Eve object, register resources later
config['DOMAIN'] = {}
app = Eve("amivapi", # Flask needs this name to find the static folder
settings=config,
validator=ValidatorAMIV)
app.logger.info(config_status)
# Set up error logging with sentry
init_sentry(app)
# Create LDAP connector
ldap.init_app(app)
# Initialize modules to register resources, validation, hooks, auth, etc.
users.init_app(app)
auth.init_app(app)
events.init_app(app)
groups.init_app(app)
blacklist.init_app(app)
joboffers.init_app(app)
beverages.init_app(app)
studydocs.init_app(app)
cascade.init_app(app)
cron.init_app(app)
documentation.init_app(app)
# Fix that eve doesn't run hooks on embedded documents
app.on_fetched_item += utils.run_embedded_hooks_fetched_item
app.on_fetched_resource += utils.run_embedded_hooks_fetched_resource
return app