当前位置: 首页>>代码示例>>Python>>正文


Python Config.from_pyfile方法代码示例

本文整理汇总了Python中flask.Config.from_pyfile方法的典型用法代码示例。如果您正苦于以下问题:Python Config.from_pyfile方法的具体用法?Python Config.from_pyfile怎么用?Python Config.from_pyfile使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在flask.Config的用法示例。


在下文中一共展示了Config.from_pyfile方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: load_graph_from_db

# 需要导入模块: from flask import Config [as 别名]
# 或者: from flask.Config import from_pyfile [as 别名]
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)
开发者ID:Randati,项目名称:fc00.org,代码行数:10,代码来源:updateGraph.py

示例2: test

# 需要导入模块: from flask import Config [as 别名]
# 或者: from flask.Config import from_pyfile [as 别名]
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)
开发者ID:mayconbordin,项目名称:boardhood,代码行数:18,代码来源:manage.py

示例3: main

# 需要导入模块: from flask import Config [as 别名]
# 或者: from flask.Config import from_pyfile [as 别名]
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)
开发者ID:akshayms,项目名称:eho,代码行数:47,代码来源:get_auth_token.py

示例4: run

# 需要导入模块: from flask import Config [as 别名]
# 或者: from flask.Config import from_pyfile [as 别名]
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)
开发者ID:SoftlySplinter,项目名称:pytentd,代码行数:24,代码来源:__init__.py

示例5: Config

# 需要导入模块: from flask import Config [as 别名]
# 或者: from flask.Config import from_pyfile [as 别名]
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")
    or os.environ.get("DB_PASSWORD")
开发者ID:ubc,项目名称:acj-versus,代码行数:32,代码来源:configuration.py

示例6: Config

# 需要导入模块: from flask import Config [as 别名]
# 或者: from flask.Config import from_pyfile [as 别名]
                                     client_ip_fingerprint,
                                     browser_fingerprint,
                                     client_ip,
                                     user_agent,
                                     accept,
                                     accept_encoding,
                                     accept_language)
    return is_valid


if __name__ == '__main__':
    conf = Config('..')
    test_request_data = dict(
        accept_encoding='Accept-Encoding: gzip, deflate, sdch',
        accept_language='Accept-Language: en-US,en;q=0.8',
        accept='Accept: application/json, text/javascript, */*; q=0.01',
        user_agent='User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36',
        vm_ip='128.196.64.214',
        client_ip='127.0.0.1'
    )

    conf.from_pyfile('default_settings.py')
    # conf.from_pyfile('local_settings.py')

    signature = generate_signature_01(conf, test_request_data)
    print signature
    values, timestamp = decode_signature_02(conf, signature)
    print values
    is_valid = validate_fingerprints_03(conf, values, test_request_data)
    print is_valid
开发者ID:cyverse,项目名称:nginx_novnc_auth,代码行数:32,代码来源:scratch.py

示例7: make_config

# 需要导入模块: from flask import Config [as 别名]
# 或者: from flask.Config import from_pyfile [as 别名]
def make_config(filename=None):
    config = Config(getcwd())
    if filename is not None:
        config.from_pyfile(filename)
    return config
开发者ID:rlanger,项目名称:Rondo,代码行数:7,代码来源:__init__.py

示例8: Config

# 需要导入模块: from flask import Config [as 别名]
# 或者: from flask.Config import from_pyfile [as 别名]
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
    tz : str
开发者ID:Tutt-Library,项目名称:pilot-tiger-catalog,代码行数:33,代码来源:metrics.py

示例9: Config

# 需要导入模块: from flask import Config [as 别名]
# 或者: from flask.Config import from_pyfile [as 别名]
import logging
import os
from flask.ext.security import RoleMixin
from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy import create_engine, Column, Integer, String, Table, DateTime, exists, ForeignKey, Boolean
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship, backref
from sqlalchemy.orm import scoped_session
from . import jsonalchemy
from flask import Config

cfg = Config(os.path.abspath("."))
cfg.from_pyfile("config.py")

db = SQLAlchemy()

logger = logging.getLogger("Gunrskite::Database")

# Check if we're inside the UDP listener, or not.
if os.environ.get("INSIDE_LISTENER", "n") == "y":
    print("Using declarative_base() for model base.")
    Base = declarative_base()
else:
    # Switch to using Flask-SQLAlchemy's model.
    print("Using db.Model for model base.")
    Base = db.Model
engine = create_engine(cfg["SQLALCHEMY_DATABASE_URI"], pool_recycle=3600)


# Function for creating the engine and session.
def create_sess():
开发者ID:SunDwarf,项目名称:Gunrskite,代码行数:33,代码来源:db.py

示例10: Configurator

# 需要导入模块: from flask import Config [as 别名]
# 或者: from flask.Config import from_pyfile [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
#.........这里部分代码省略.........
开发者ID:tooxie,项目名称:shiva-server,代码行数:103,代码来源:__init__.py

示例11: get_user_config

# 需要导入模块: from flask import Config [as 别名]
# 或者: from flask.Config import from_pyfile [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:
#.........这里部分代码省略.........
开发者ID:guardian,项目名称:alerta,代码行数:103,代码来源:config.py

示例12: FromEmails

# 需要导入模块: from flask import Config [as 别名]
# 或者: from flask.Config import from_pyfile [as 别名]
def FromEmails():

    #Config, init variables
    config = Config(os.getcwd())
    config.from_pyfile('settings.cfg')

    logger = logging.getLogger('ICONZ.HelpdeskDashboard.OutageParse')
    logger.addHandler(config['HANDLER'])

    def GetBody(msg):
        if msg.is_multipart():
            return(msg.get_payload(0)).get_payload(decode=True)
        else:
            return(msg.get_payload(decode=True))



    def Passthrough(msg_list):
        try:
            smtp_conn = smtplib.SMTP(config['OUTAGES_SMTP_SERVER'],
                    config['OUTAGES_SMTP_PORT'])

            for msg in msg_list:
                smtp_conn.sendmail(config['OUTAGES_SMTP_FROM_ADDR'],
                    config['OUTAGES_SMTP_TO_ADDR'], msg.as_string())

            logger.info('Succesfully passed through ' + str(len(msg_list)) + ' messages')
        except Exception as e:
            logger.error('Faliure to passthrough all messages.', exc_info = True)
            


    def DBInsert(data):
        #Could tidy this up so it's done as a batch operation. Probably unecessary
        conn = connect_db()
        cur = conn.cursor()

        try:
            cur.execute('select rowid from outage_texts where provider_ref_id match(?)',
                    [data['reference']])

            db_outage = cur.fetchone()
            db_outage_id = None
            db_outage_text_id = None

            if db_outage == None:
                cur.execute('insert into outage_texts (provider_ref_id, equipment_list, full_text) values (?,?,?)',
                    [unicode(data['reference']), unicode(data['equipment']), unicode(data['full_text'])])
                db_outage_text_id = cur.lastrowid
                cur.execute('insert into outages (provider, num_affected, start_time, end_time, issues, text_id) values (?,?,?,?,?,?)',
                    [data['provider'], data['num_affected'], data['start_datetime'], data['end_datetime'], data['issues'], db_outage_text_id])

                db_outage_id = cur.lastrowid
                conn.commit()

                logger.debug('Created new outage with id ' + str(db_outage_id))

            else:
                cur.execute('update outage_texts set equipment_list=(?), full_text=(?) where rowid==?',
                        [unicode(data['equipment']), unicode(data['full_text']), db_outage[0]])
                db_outage_text_id = db_outage[0]
                cur.execute('select id from outages where text_id==?', [db_outage_text_id])
                db_outage_id = cur.fetchone()[0]
                cur.execute('update outages set num_affected=(?), start_time=(?), end_time=(?), issues=(?) where id==?',
                        [data['num_affected'], data['start_datetime'], data['end_datetime'], data['issues'], db_outage_id])

                conn.commit()

                logger.debug('Updated outage with id ' + str(db_outage_id))


            users = list()

            for line in data['equipment'].split('\n'):
                cur.execute('select id, name from dslams where name==?', [line])
                dslam = cur.fetchone()
                if dslam is not None:
                    cur.execute('select id, asid from dslusers where dslam_id==?', [dslam[0]])
                    users.append(cur.fetchall())

            for db_block in users:
                for user in db_block:
                    if user is not None:
                        cur.execute('select * from outages_dslusers_rel where (outages_id==?) and (dslusers_id==?)', [db_outage_id, user[0]])
                        if cur.fetchone() is None:
                            cur.execute('insert into outages_dslusers_rel (outages_id, dslusers_id) values (?,?)',
                                    [db_outage_id, user[0]])
                            conn.commit()
        #Clears connection so that program can continue in case of exception
        except sqlite3.IntegrityError as e:
            conn.close()
            conn = connect_db()
            raise(e)

                        
    def ChorusHTMLFat(data):

        def FindContent(fieldname, soup, one = True):
            if one:
                out = [string for string in soup.find(
#.........这里部分代码省略.........
开发者ID:lfn3,项目名称:dsl-outage-tracker,代码行数:103,代码来源:OutageParse.py

示例13: Config

# 需要导入模块: from flask import Config [as 别名]
# 或者: from flask.Config import from_pyfile [as 别名]
from asyncio import get_event_loop, coroutine, gather, wait
from io import BytesIO
import logging
from os.path import dirname

from aiohttp import web
from flask import Config
import arrow
import pygal

from .redmine import AsyncRedmine


config = Config(dirname(__file__))
config.from_pyfile('default.cfg')
config.from_pyfile('settings.cfg')

pygal_config = pygal.Config(style=config['PYGAL_STYLE'])

redmine = AsyncRedmine(config['REDMINE_URL'], key=config['API_KEY'])

access_logger = logging.getLogger('aiohttp.access')
access_logger.addHandler(logging.StreamHandler())
access_logger.setLevel(logging.INFO)

issue_statuses = []


def main():
    loop = get_event_loop()
    loop.run_until_complete(redminecharts(loop))
开发者ID:Perlence,项目名称:redmine-charts-images,代码行数:33,代码来源:redminecharts.py

示例14: create_app

# 需要导入模块: from flask import Config [as 别名]
# 或者: from flask.Config import from_pyfile [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
开发者ID:amiv-eth,项目名称:amivapi,代码行数:66,代码来源:bootstrap.py

示例15: main

# 需要导入模块: from flask import Config [as 别名]
# 或者: from flask.Config import from_pyfile [as 别名]
def main(argconfig):
    # Load the config file the same way Flask does which Chill uses.
    config_file = argconfig if argconfig[0] == os.sep else os.path.join(os.getcwd(), argconfig)
    config = Config(os.getcwd())
    config.from_pyfile(config_file)

    pyrax.set_credential_file(config["RACKSPACE_CREDENTIAL_FILE"])
    cf = pyrax.cloudfiles

    # sync sync_folder_to_container
    local = config["FREEZER_DESTINATION"]
    container_name = config.get("RACKSPACE_CONTAINER_NAME", os.path.basename(os.getcwd()))

    prefix = config.get("PUBLIC_URL_PREFIX", None)
    if prefix:
        for page in (INDEX_PAGE, ERROR_PAGE, "401{0}".format(ERROR_PAGE), "404{0}".format(ERROR_PAGE)):
            # If no index.html or error pages then link to the one found in
            # PUBLIC_URL_PREFIX
            if not os.path.exists(os.path.join(local, page)) and os.path.exists(os.path.join(local, prefix[1:], page)):
                print "Creating hard link for {0}".format(page)
                print "{0} -> {1}".format(os.path.join(local, page), os.path.join(local, prefix[1:], page))
                os.link(os.path.join(local, prefix[1:], page), os.path.join(local, page))

    confirm = raw_input(
        "\nsync the folder: {local} \nto rackspace cloudfiles container: {container_name}\n[n]/y\n".format(**locals())
    )
    if confirm != "y":
        return

    remote = cf.create_container(container_name)

    local_files = set()
    for root, dir, files in os.walk(local):
        for f in files:
            local_files.add(os.path.join(root[len(local) + 1 :], f))

    cf.sync_folder_to_container(local, remote)

    # Mark all objects on remote to be deleted if not in local
    # The limit here is arbitrary, but can not be higher then 10000.
    limit = 1000
    marker = ""
    remote_objects_list = remote.get_objects(limit=limit, marker=marker)
    while remote_objects_list:
        marker = remote_objects_list[-1].name
        for obj in remote_objects_list:
            if obj.name not in local_files:
                obj.delete_in_seconds(DELETE_OBJECTS_DELAY)

        remote_objects_list = remote.get_objects(limit=limit, marker=marker)

    # publish
    cf.make_container_public(container_name, ttl=TTL)

    # cdn website
    remote.set_web_index_page(INDEX_PAGE)
    remote.set_web_error_page(ERROR_PAGE)

    # Totally copied from the docs
    print
    print "After Making Public"
    print "cdn_enabled", remote.cdn_enabled
    print "cdn_ttl", remote.cdn_ttl
    print "cdn_log_retention", remote.cdn_log_retention
    print "cdn_uri", remote.cdn_uri
    print "cdn_ssl_uri", remote.cdn_ssl_uri
    print "cdn_streaming_uri", remote.cdn_streaming_uri
    print "cdn_ios_uri", remote.cdn_ios_uri
开发者ID:jkenlooper,项目名称:dot_files,代码行数:70,代码来源:chill-upload-rackspace.py


注:本文中的flask.Config.from_pyfile方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。