本文整理汇总了Python中flask.Config类的典型用法代码示例。如果您正苦于以下问题:Python Config类的具体用法?Python Config怎么用?Python Config使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Config类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: load_graph_from_db
def load_graph_from_db(time_limit):
config = Config('./')
config.from_pyfile('web_config.cfg')
with NodeDB(config) as db:
nodes = db.get_nodes(time_limit)
edges = db.get_edges(nodes, 60*60*24*7)
return (nodes, edges)
示例2: setup
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()
示例3: test
def test():
config = Config('application/config/')
config.from_pyfile('testing.cfg')
#db('createall', database=config['POSTGRESQL_DATABASE_DB'])
print ' [START] Testing server'
proc = subprocess.Popen(["python", "runserver.py", "testing"])
time.sleep(5)
call(["python", "application/tests/testsuite.py"])
print 'KILLING THE TESTING SERVER...'
time.sleep(5)
os.kill(proc.pid, signal.SIGTERM)
for pid in children_pid(proc.pid):
os.kill(pid, signal.SIGTERM)
示例4: setup_config
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
示例5: main
def main():
if len(sys.argv) > 1 and len(sys.argv) != 4:
print "You must either specify no parameters or exactly 3: <username> <password> <tenant>.\n" \
"If you specify no parameters, credentials and tenant will be taken from config"
exit
scriptDir = os.path.dirname(os.path.realpath(__file__))
config = Config(scriptDir + '/../etc')
config.from_pyfile('local.cfg')
print "Configuration has been loaded from 'etc/local.cfg'"
if len(sys.argv) == 4:
user = sys.argv[1]
password = sys.argv[2]
tenant = sys.argv[3]
else:
print "You didn't provided credentials, using ones found in config"
user = config['OS_ADMIN_USER']
password = config['OS_ADMIN_PASSWORD']
tenant = config['OS_ADMIN_TENANT']
protocol = config['OS_AUTH_PROTOCOL']
host = config['OS_AUTH_HOST']
port = config['OS_AUTH_PORT']
auth_url = "%s://%s:%s/v2.0/" % (protocol, host, port)
print "User: %s" % user
print "Password: %s" % password
print "Tenant: %s" % tenant
print "Auth URL: %s" % auth_url
keystone = keystone_client(
username=user,
password=password,
tenant_name=tenant,
auth_url=auth_url
)
result = keystone.authenticate()
print "Auth succeed: %s" % result
print "Auth token: %s" % keystone.auth_token
print "Tenant [%s] id: %s" % (tenant, keystone.tenant_id)
示例6: ConfigurationRegistry
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()
示例7: init_app
def init_app(cls, app):
Config.init_app(app)
# email errors to the administrators
import logging
from logging.handlers import SMTPHandler
credentials = None
secure = None
if getattr(cls, 'MAIL_USERNAME', None) is not None:
credentials = (cls.MAIL_USERNAME, cls.MAIL_PASSWORD)
if getattr(cls, 'MAIL_USE_TLS', None):
secure = ()
mail_handler = SMTPHandler(mailhost=(cls.MAIL_SERVER, cls.MAIL_PORT),
fromaddr=cls.FLASKY_MAIL_SENDER,
toaddrs=[cls.FLASKY_ADMIN],
subject=cls.FLASKY_MAIL_SUBJECT_PREFIX + ' Application Error',
credentials=credentials,
secure=secure)
mail_handler.setLevel(logging.ERROR)
app.logger.addHandler(mail_handler)
示例8: run
def run():
"""Parse the command line arguments and run the application"""
args = parser.parse_args()
config = Config(getcwd())
# Set the configuration options from the file given
if args.conf:
config.from_pyfile(args.conf)
# Load the rest of the arguments, overriding the conf file
config['DEBUG'] = args.debug
# Create the application and create the database
app = create_app(config)
# Show the application config
if args.show:
from pprint import pprint
pprint(dict(app.config))
# Run the application
app.run(threaded=True)
示例9: main
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()
示例10: ConfigurationRegistry
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()
示例11: __init__
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.
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.update(self.new_config)
示例12: __init__
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
示例13: create_app
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
示例14: Config
#-------------------------------------------------------------------------------
import datetime
import os
import re
import redis
import urlparse
from flask import Blueprint, Config, flash, g, jsonify, request, render_template
from flask import session, url_for
from flask_bibframe.models import CoverArt
blueprint_folder = os.path.abspath(os.path.dirname(__file__))
app_folder = os.path.split(blueprint_folder)[0]
metrics_config = Config(app_folder)
metrics_config.from_pyfile('catalog.cfg')
redis_ds = redis.StrictRedis(metrics_config.get('REDIS_HOST'))
def parse_logfile(log_path, redis_ds=redis_ds, tz='-0700'):
"""Takes a nginx access log, opens the file, and parses through and creates
metrics for use by other Blueprints and apps.
Parameters
----------
log_path : str
Full path and filename of the nginx access log
redis_ds : StrictRedis instance
defaults to Redis datastore for CPP's metrics
示例15: Config
* DATABASE_URI
* 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: