Пример #1
0
def profile_execute(p_id):
    data = Profile().find_by_pk(p_id)
    source = data['source']
    destination = data['destination']
    data = data['profile']
    split = int(data.get('split_size') or 0)
    
    """ Dumping from Source """
    SourceAct = import_string(source.get('provider') + '.model.SourceAct')
    src_act = SourceAct(**source)
    file_name = src_act.dump_zipped()
    
    """ Output file name """
    dt_utc = datetime.utcnow().strftime('%Y_%m_%d_%H-%M-%S')
    out = 'wb_' + functions.clean_str(data['title']) + dt_utc + functions.ext_file(file_name)
    
    if split > 0:
        cmd = "split -b %sm %s /tmp/%s" % (split, file_name, out)
        subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    
    """ Executing destination part  """
    DestinationAct = import_string(destination.get('provider') + '.model.DestinationAct')
    dst_act = DestinationAct(**destination)
    if split == 0:
        dst_act.upload_file(file_name, out)
    elif split > 0:
        dst_act.mkdir(dt_utc)
        dst_act.cd(dt_utc)
        for f in os.listdir('/tmp'):
            if f.startswith(out):
                dst_act.upload_file('/tmp/%s' % f, f)
        os.unlink(file_name)
    
    return data
Пример #2
0
def configure_template_filters(app):
    """Configure filters and tags for jinja"""

    app.jinja_env.filters['nl2br'] = import_string('utils.templates.nl2br')
    app.jinja_env.filters['dateformat'] = import_string('utils.templates.dateformat')
    app.jinja_env.filters['timeformat'] = import_string('utils.templates.timeformat')
    app.jinja_env.filters['datetimeformat'] = import_string('utils.templates.datetimeformat')
Пример #3
0
    def load(self):
        """Load all the installed packages.
        """
        if self.loaded:
            return

        from kalapy.web.package import Package

        self.lock.acquire()
        try:
            for package in settings.INSTALLED_PACKAGES:
                if package in self.packages:
                    continue
                logger.info(' * Loading package: %s' % package)
                if package not in sys.modules:
                    import_string(package)

                self.packages[package] = Package(package)

                self.load_modules(package, 'models')
                self.load_modules(package, 'views')

            self.loaded = True
        finally:
            self.lock.release()
Пример #4
0
    def load(self):
        """Load all the installed packages.
        """
        if self.loaded:
            return

        from kalapy.web.package import Package

        self.lock.acquire()
        try:
            for package in settings.INSTALLED_PACKAGES:
                if package in self.packages:
                    continue
                logger.info(' * Loading package: %s' % package)
                if package not in sys.modules:
                    import_string(package)

                self.packages[package] = Package(package)

                self.load_modules(package, 'models')
                self.load_modules(package, 'views')

            self.loaded = True
        finally:
            self.lock.release()
Пример #5
0
def set_blueprints(app, blueprints):
    """
    Registers blueprints with the app.
    """
    # Register blueprints.
    for blueprint in blueprints:
        url_prefix = None
        if len(blueprint) == 2:
            blueprint, url_prefix = blueprint
        blueprint_object = import_string('%s:BLUEPRINT' % blueprint, silent=True)
        blueprint_name, blueprint_import_name = blueprint.split('.')[-1], blueprint
        if not blueprint_object:
            options = dict(static_folder='static', template_folder='templates')
            blueprint_object = Blueprint(blueprint_name, blueprint_import_name, **options)
        blueprint_routes = import_string('%s.urls:routes' % blueprint_import_name, silent=True)
        if blueprint_routes:
            urls.set_urls(blueprint_object, blueprint_routes)

        # Other initializations.
        for fn, values in [(set_before_handlers, import_string('%s:BEFORE_REQUESTS' % blueprint, silent=True)),
                           (set_before_app_handlers, import_string('%s:BEFORE_APP_REQUESTS' % blueprint, silent=True)),
                           (set_after_handlers, import_string('%s:AFTER_REQUESTS' % blueprint, silent=True)),
                           (set_after_app_handlers, import_string('%s:AFTER_APP_REQUESTS' % blueprint, silent=True)),
                           (set_context_processors, import_string('%s:CONTEXT_PROCESSORS' % blueprint, silent=True)),
                           (set_app_context_processors, import_string('%s:APP_CONTEXT_PROCESSORS' % blueprint, silent=True)),
                           (set_error_handlers, import_string('%s:ERROR_HANDLERS' % blueprint, silent=True)),
                           (set_app_error_handlers, import_string('%s:APP_ERROR_HANDLERS' % blueprint, silent=True))]:
            if values:
                fn(blueprint_object, values)
        # Can be mounted at specific prefix.
        if url_prefix:
            app.register_blueprint(blueprint_object, url_prefix=url_prefix)
        else:
            app.register_blueprint(blueprint_object)
Пример #6
0
def db_create_models():
    "Creates database tables."
    # db_createall doesn't work if the models aren't imported
    import_string('models', silent=True)
    for blueprint_name, blueprint in app.blueprints.iteritems():
        import_string('%s.models' % blueprint.import_name, silent=True)
    db.create_all()
Пример #7
0
def db_dropall():
    "Drops all database tables"
    # db_dropall doesn't work if the models aren't imported
    import_string('models', silent=True)
    for blueprint_name, blueprint in app.blueprints.iteritems():
        import_string('%s.models' % blueprint.import_name, silent=True)
    db.drop_all()
Пример #8
0
def get_view(endpoint):
  try:
    return import_string('catonmat.views.' + endpoint)
  except (ImportError, AttributeError):
    try:
      return import_string(endpoint)
    except (ImportError, AttributeError):
      raise RuntimeError('Could not locate view for %r' % endpoint)
Пример #9
0
def build_suite(name):
    """Build test suite for the given name. A name can be either a package name
    or a fully qualified name of the test class or a specific test method within
    a package prefixed with ``package_name:``.

    For example:

        >>> build_suite('hello')
        >>> build_suite('hello:HelloTest')
        >>> build_suite('hello:HelloTest.test_hello')
        >>> build_suite('foo:foo.FooTest')
        >>> build_suite('foo:bar.BarTest')

    :returns:
        an instance of `TestSuite`
    """
    try:
        package, test = name.split(':')
    except:
        package, test = name, None

    test_module = '%s.%s' % (package, TEST_MODULE)
    test_fullname = '%s.%s' % (test_module, test) if test else test_module

    suite = unittest.TestSuite()

    match = re.match('(.*?)\.(test_\w+)$', test_fullname)
    if match:
        try:
            TestClass = import_string(match.group(1))
        except ImportError:
            raise ImportError(match.group(1))
        suite.addTest(TestClass(match.group(2)))

    elif test:
        try:
            TestClass = import_string(test_fullname)
        except AttributeError:
            raise AttributeError(test_fullname)
        if isinstance(TestClass, unittest.TestCase.__class__):
            suite.addTest(unittest.TestLoader().loadTestsFromTestCase(TestClass))
        else:
            suite.addTest(unittest.defaultTestLoader.loadTestsFromModule(TestClass))

    else:
        try:
            test_modules = list(find_modules(test_module))
        except ValueError:
            test_modules = [test_module]
        for module in map(import_string, test_modules):
            suite.addTest(unittest.defaultTestLoader.loadTestsFromModule(module))

    return suite
Пример #10
0
def get_view(endpoint):
    """Returns the view for the endpoint.  It will cache both positive and
    negative hits, so never pass untrusted values to it.  If a view does
    not exist, `None` is returned.
    """
    view = _resolved_views.get(endpoint)
    if view is not None:
        return view
    try:
        view = import_string('solace.views.' + endpoint)
    except (ImportError, AttributeError):
        view = import_string(endpoint, silent=True)
    _resolved_views[endpoint] = view
    return view
Пример #11
0
def get_view(endpoint):
    """Returns the view for the endpoint.  It will cache both positive and
    negative hits, so never pass untrusted values to it.  If a view does
    not exist, `None` is returned.
    """
    view = _resolved_views.get(endpoint)
    if view is not None:
        return view
    try:
        view = import_string('rater.views.' + endpoint)
    except (ImportError, AttributeError):
        view = import_string(endpoint, silent=True)
    _resolved_views[endpoint] = view
    return view
Пример #12
0
def configure_blueprints(app, blueprints):
    blueprints_list = []
    packages_list = []

    for name in blueprints:
        blueprint = import_string(name)
        blueprints_list.append(blueprint)
        package = import_string(blueprint.import_name)
        packages_list.append(package)

    for package in list(set(packages_list)):
        __import__('%s.views' % package.__name__)

    for blueprint in list(set(blueprints_list)):
        app.register_blueprint(blueprint)
Пример #13
0
 def init_app(self, app):
     app.config.setdefault('MSEARCH_BACKEND', 'simple')
     msearch_backend = app.config['MSEARCH_BACKEND']
     if msearch_backend == 'simple':
         backend = import_string(
             "flask_msearch.simple_backend.SimpleSearch")
     elif msearch_backend == 'whoosh':
         backend = import_string(
             "flask_msearch.whoosh_backend.WhooshSearch")
     elif msearch_backend == 'elasticsearch':
         backend = import_string(
             "flask_msearch.elasticsearch_backend.ElasticSearch")
     else:
         raise ValueError('backends {} not exists.'.format(msearch_backend))
     self._backend = backend(app, self.db, self.analyzer)
Пример #14
0
def get_auth_system():
    """Return the auth system."""
    global _auth_system
    with _auth_select_lock:
        if _auth_system is None:
            _auth_system = import_string(settings.AUTH_SYSTEM)()
        return _auth_system
Пример #15
0
def __register_blueprint(app, blueprint):
    path = ""
    name = ""
    url_prefix = None
    if type(blueprint) == "":
        path = blueprint
        name = "bp_" + blueprint.split(".")[-1]
    else:
        path = str(blueprint[0])
        if len(blueprint) >= 2:
            name = str(blueprint[1])
        if len(blueprint) >= 3:
            url_prefix = str(blueprint[2])
    try:
        package = import_string(path + ".views")
    except:
        raise

    bp = getattr(package, name, None)
    if not bp:
        app.logger.error("import blueprint %s from %s failed!\n" %
                         (name, package + ".views"))
        raise

    if url_prefix:
        if not url_prefix.startswith("/"):
            url_prefix = "/" + url_prefix
        app.register_blueprint(bp, url_prefix=url_prefix)
    else:
        app.register_blueprint(bp)
Пример #16
0
def add_objtypes(objects, force=False):
    """Add a list of MIME types."""

    objs = []
    for obj in objects:
        name = NotGiven
        doc = NotGiven
        if isinstance(obj, (list, tuple)):
            if len(obj) > 2:
                doc = obj[2]
            name = obj[1]
            obj = obj[0]
        if isinstance(obj, string_types):
            obj = import_string(obj)
            if name is NotGiven:
                name = getattr(obj, 'NAME', name)
            if doc is NotGiven:
                doc = getattr(obj, 'DOC', doc)

        objs.append((obj, name, doc))

    db.create_all()
    try:
        root = root_site.add_default_permissions
    except NoData:
        return

    for obj, name, doc in objs:
        obj = ObjType.get(obj)  # will create the record
        _upd(obj, (('name', name), ('doc', doc)), force=force)
        if obj._is_new or force:
            root(obj)
Пример #17
0
def find_related_modules(package, related_name_re='.+',
                         ignore_exceptions=False):
    """Find matching modules using a package and a module name pattern."""
    warnings.warn('find_related_modules has been deprecated.',
                  DeprecationWarning)
    package_elements = package.rsplit(".", 1)
    try:
        if len(package_elements) == 2:
            pkg = __import__(package_elements[0], globals(), locals(), [
                             package_elements[1]])
            pkg = getattr(pkg, package_elements[1])
        else:
            pkg = __import__(package_elements[0], globals(), locals(), [])
        pkg_path = pkg.__path__
    except AttributeError:
        return []

    # Find all modules named according to related_name
    p = re.compile(related_name_re)
    modules = []

    for name in find_modules(package, include_packages=True):
        if p.match(name.split('.')[-1]):
            try:
                modules.append(import_string(name, silent=ignore_exceptions))
            except Exception as e:
                if not ignore_exceptions:
                    raise e

    return modules
Пример #18
0
def get_auth_system():
    """Return the auth system."""
    global _auth_system
    with _auth_select_lock:
        if _auth_system is None:
            _auth_system = import_string(settings.AUTH_SYSTEM)()
        return _auth_system
Пример #19
0
Файл: app.py Проект: peper/tipfy
    def i18n_store_class(self):
        """Returns the configured auth store class.

        :returns:
            An auth store class.
        """
        return import_string(self.config["tipfy"]["i18n_store_class"])
Пример #20
0
    def load_cache(self):
        """
        Load the cache and assign the Cache interface to
        """
        BackendClass = import_string(self.cache_type)

        if self.cache_type == 'werkzeug.contrib.cache.NullCache':
            self.cache = BackendClass(self.cache_default_timeout)
        elif self.cache_type == 'werkzeug.contrib.cache.SimpleCache':
            self.cache = BackendClass(
                self.cache_threshold, self.cache_default_timeout)
        elif self.cache_type == 'werkzeug.contrib.cache.MemcachedCache':
            self.cache = BackendClass(
                self.cache_memcached_servers,
                self.cache_default_timeout,
                self.cache_key_prefix)
        elif self.cache_type == 'werkzeug.contrib.cache.GAEMemcachedCache':
            self.cache = BackendClass(
                self.cache_default_timeout,
                self.cache_key_prefix)
        elif self.cache_type == 'werkzeug.contrib.cache.FileSystemCache':
            self.cache = BackendClass(
                self.cache_dir,
                self.cache_threshold,
                self.cache_default_timeout)
        else:
            self.cache = BackendClass(**self.cache_init_kwargs)
Пример #21
0
def __register_blueprint(app, blueprint):
    path = ""
    name = ""
    url_prefix = None
    if type(blueprint) == "":
        path = blueprint
        name = "bp_" + blueprint.split(".")[-1]
    else:
        path = str(blueprint[0])
        if len(blueprint) >= 2:
            name = str(blueprint[1])
        if len(blueprint) >= 3:
            url_prefix = str(blueprint[2])
    try:
        package = import_string(path+".views")
    except:
        raise

    bp = getattr(package, name, None)
    if not bp:
        app.logger.error("import blueprint %s from %s failed!\n" %(name, package+".views"))
        raise

    if url_prefix:
        if not url_prefix.startswith("/"):
            url_prefix = "/" + url_prefix
        app.register_blueprint(bp, url_prefix=url_prefix)
    else:
        app.register_blueprint(bp)
Пример #22
0
 def init_app(self, app):
     config = app.config.get_namespace(self.ns)
     conn_params = config.get('conn_params', {})
     self.database = db_url.connect(config['db_url'], **conn_params)
     self.model_class = import_string(
         config.get('model', 'peeweext.model.Model'))
     self._register_handlers(app)
Пример #23
0
def obj_or_import_string(value, default=None):
    """Import string or return object."""
    if isinstance(value, string_types):
        return import_string(value)
    elif value:
        return value
    return default
Пример #24
0
 def __init__(self):
     engine = import_string(
         'kalapy.contrib.sessions.engines.%s' % settings.SESSION_ENGINE)
     self.store = engine.Store()
     opts = settings.SESSION_COOKIE
     self.cookie_name = opts.get('name', 'session_id')
     self.cookie_age = opts.get('age', 0)
Пример #25
0
 def __init__(self, result):
     self.url = result['url']
     self.title_text = result['title']
     self.title = highlight_all(result, 'title')
     cls = import_string(result['type'])
     self.kind = cls.search_document_kind
     self.description = cls.describe_search_result(result)
Пример #26
0
    def session_store_class(self):
        """Returns the configured session store class.

        :returns:
            A session store class.
        """
        return import_string(self.config['tipfy']['session_store_class'])
Пример #27
0
    def dispatch(self, request):
        """Dispatches a request. This instantiates and calls a
        :class:`tipfy.RequestHandler` based on the matched :class:`Rule`.

        :param request:
            A :class:`tipfy.Request` instance.
        :param match:
            A tuple ``(rule, rule_args)`` with the matched rule and rule
            arguments.
        :param method:
            A method to be used instead of using the request or handler method.
        :returns:
            A :class:`tipfy.Response` instance.
        """
        rule, rule_args = self.match(request)
        handler = rule.handler
        if isinstance(handler, basestring):
            if handler not in self.handlers:
                self.handlers[handler] = import_string(handler)

            rule.handler = handler = self.handlers[handler]

        rv = local.current_handler = handler(request)
        if not isinstance(rv, BaseResponse) and hasattr(rv, '__call__'):
            # If it is a callable but not a response, we call it again.
            rv = rv()

        return rv
Пример #28
0
def find_related_modules(package,
                         related_name_re='.+',
                         ignore_exceptions=False):
    """Given a package name and a module name pattern, tries to find matching
    modules."""
    package_elements = package.rsplit(".", 1)
    try:
        if len(package_elements) == 2:
            pkg = __import__(package_elements[0], globals(), locals(),
                             [package_elements[1]])
            pkg = getattr(pkg, package_elements[1])
        else:
            pkg = __import__(package_elements[0], globals(), locals(), [])
        pkg_path = pkg.__path__
    except AttributeError:
        return []

    # Find all modules named according to related_name
    p = re.compile(related_name_re)
    modules = []

    for name in find_modules(package, include_packages=True):
        if p.match(name.split('.')[-1]):
            try:
                modules.append(import_string(name, silent=ignore_exceptions))
            except Exception as e:
                if not ignore_exceptions:
                    raise e

    return modules
Пример #29
0
 def __init__(self, result):
     self.url = result['url']
     self.title_text = result['title']
     self.title = highlight_all(result, 'title')
     cls = import_string(result['type'])
     self.kind = cls.search_document_kind
     self.description = cls.describe_search_result(result)
Пример #30
0
def obj_or_import_string(value, default=None):
    """Import string or return object."""
    if isinstance(value, string_types):
        return import_string(value)
    elif value:
        return value
    return default
Пример #31
0
    def i18n_store_class(self):
        """Returns the configured auth store class.

        :returns:
            An auth store class.
        """
        return import_string(self.config['tipfy']['i18n_store_class'])
Пример #32
0
Файл: app.py Проект: peper/tipfy
    def session_store_class(self):
        """Returns the configured session store class.

        :returns:
            A session store class.
        """
        return import_string(self.config["tipfy"]["session_store_class"])
Пример #33
0
    def session_store_class(self):
        """Returns the configured session store class.

        :returns:
            A session store class.
        """
        return import_string(self.config['tipfy']['session_store_class'])
Пример #34
0
    def i18n_store_class(self):
        """Returns the configured i18n store class.

        :returns:
            An i18n store class.
        """
        return import_string(self.config['tipfy']['i18n_store_class'])
Пример #35
0
    def auth_user_model(self):
        """Returns the configured user model.

        :returns:
            A :class:`tipfy.ext.auth.model.User` class.
        """
        return import_string(self.app.get_config(__name__, 'user_model'))
Пример #36
0
def _load(Obj, lister, force=False):
    for obj in lister:
        name = NotGiven
        doc = NotGiven
        if isinstance(obj, (list, tuple)):
            if len(obj) > 2:
                doc = obj[2]
            name = obj[1]
            obj = obj[0]
        if isinstance(obj, string_types):
            obj = import_string(obj)
            if name is NotGiven:
                name = getattr(obj, 'NAME', name)
            if doc is NotGiven:
                doc = getattr(obj, 'DOC', doc)

        path = obj.__module__ + '.' + obj.__name__
        try:
            obj = Obj.q.get_by(path=path)
        except NoData:
            if name is NotGiven:
                name = path
            obj = Obj.new(name=name, path=path)
        else:
            _upd(obj, (('name', name), ('doc', doc)), force=force)

        add_vars(getattr(obj.mod, 'VAR', ()), obj, force=force)
        add_templates(getattr(obj.mod, 'TEMPLATE', ()),
                      parent=obj,
                      force=force)
Пример #37
0
 def view(self):
     view = import_string(self.name)
     if isinstance(view, (object, )):
         assert self.options.get('endpoint') is not None
         endpoint = self.options.pop('endpoint')
         view = view.as_view(endpoint)
     return view
Пример #38
0
    def auth_store_class(self):
        """Returns the configured auth store class.

        :returns:
            An auth store class.
        """
        return import_string(self.config['tipfy']['auth_store_class'])
Пример #39
0
    def _set_cache(self, app, config):
        import_me = config['CACHE_TYPE']
        if '.' not in import_me:
            from . import backends

            try:
                cache_obj = getattr(backends, import_me)
            except AttributeError:
                raise ImportError("%s is not a valid FlaskCache backend" %
                                  (import_me))
        else:
            cache_obj = import_string(import_me)

        cache_args = config['CACHE_ARGS'][:]
        cache_options = {'default_timeout': config['CACHE_DEFAULT_TIMEOUT']}

        if config['CACHE_OPTIONS']:
            cache_options.update(config['CACHE_OPTIONS'])

        if not hasattr(app, 'extensions'):
            app.extensions = {}

        app.extensions.setdefault('cache', {})
        app.extensions['cache'][self] = cache_obj(app, config, cache_args,
                                                  cache_options)
Пример #40
0
def create_app(config_name):

    app = flask.Flask(__name__, instance_relative_config=1)

    app.config.from_object(config_name)
    app.config.from_pyfile("config.py")

    for name in extensions:
        extension = import_string(name)
        extension.init_app(app)

    for name in blueprints:
        blueprint = import_string(name)
        app.register_blueprint(blueprint)

    return app
Пример #41
0
 def __init__(self):
     engine = import_string('kalapy.contrib.sessions.engines.%s' %
                            settings.SESSION_ENGINE)
     self.store = engine.Store()
     opts = settings.SESSION_COOKIE
     self.cookie_name = opts.get('name', 'session_id')
     self.cookie_age = opts.get('age', 0)
Пример #42
0
def cmd():
    """
    Help to run the command line
    :return:
    """
    global asm_app, app_dir
    asmpyfile = os.path.join(os.path.join(CWD, ENTRY_PY))
    if os.path.isfile(asmpyfile):
        cwd_to_sys_path()
        entry = import_string(ENTRY_PY.replace('.py', ''))
        asm_app = entry.app
        app_dir = CWD
        cli()
        return
    else:
        header()
        if len(sys.argv) == 1 or (len(sys.argv) > 1
                                  and sys.argv[1] != 'gen:init'):
            print("Error: %s is not setup yet" % about.__title__)
            print("missing file '%s' in %s" % (ENTRY_PY, CWD))
            print("Run %s in this directory to initialize" %
                  bold("asm gen:init"))
            print('_' * 80)
            print("")
        elif len(sys.argv) == 1 or (len(sys.argv) > 1
                                    and sys.argv[1] == 'gen:init'):
            cli()
Пример #43
0
    def __init__(self):

        #: If application is runing in debug mode.
        self.debug = settings.DEBUG

        # Initialize logging.
        init_logger()

        # Initialize the object pool
        pool.load()

        #: List of all the registered middlewares (settings.MIDDLEWARE_CLASSES)
        self.middlewares = [
            import_string(s)() for s in settings.MIDDLEWARE_CLASSES
        ]

        # static data middleware
        self.dispatch = StaticMiddleware.from_paths(
            self.dispatch, {
                '/static': os.path.join(settings.PROJECT_DIR, 'static'),
            }, pool.get_static_paths(), settings.STATIC_LINKS)

        pool.url_map.add(
            Rule('/static/<filename>',
                 endpoint='static',
                 methods=('GET', ),
                 build_only=True))

        #: The jinja2 environment
        self.jinja_env = self._create_jinja_env(pool.get_template_paths())
Пример #44
0
    def __init__(self):

        #: If application is runing in debug mode.
        self.debug = settings.DEBUG

        # Initialize logging.
        init_logger()

        # Initialize the object pool
        pool.load()

        #: List of all the registered middlewares (settings.MIDDLEWARE_CLASSES)
        self.middlewares = [import_string(s)() for s in settings.MIDDLEWARE_CLASSES]

        # static data middleware
        self.dispatch = StaticMiddleware.from_paths(self.dispatch, {
                '/static': os.path.join(settings.PROJECT_DIR, 'static'),
            }, pool.get_static_paths(), settings.STATIC_LINKS)

        pool.url_map.add(
            Rule('/static/<filename>',
                endpoint='static', methods=('GET',), build_only=True))

        #: The jinja2 environment
        self.jinja_env = self._create_jinja_env(pool.get_template_paths())
Пример #45
0
    def _set_cache(self, app, config):
        import_me = config['CACHE_TYPE']
        if '.' not in import_me:
            from . import backends

            try:
                cache_obj = getattr(backends, import_me)
            except AttributeError:
                raise ImportError("%s is not a valid FlaskCache backend" % (
                                  import_me))
        else:
            cache_obj = import_string(import_me)

        cache_args = config['CACHE_ARGS'][:]
        cache_options = {'default_timeout': config['CACHE_DEFAULT_TIMEOUT']}

        if config['CACHE_OPTIONS']:
            cache_options.update(config['CACHE_OPTIONS'])

        if not hasattr(app, 'extensions'):
            app.extensions = {}

        app.extensions.setdefault('cache', {})
        app.extensions['cache'][self] = cache_obj(
                app, config, cache_args, cache_options)
Пример #46
0
def cmd():
    """
    Help to run the command line
    :return:
    """
    global asm_app, app_dir

    script_name = sys.argv[0].split('/')[-1]
    is_admin = script_name == 'asm-admin'

    asmpyfile = os.path.join(os.path.join(CWD, ENTRY_PY))
    if os.path.isfile(asmpyfile):
        cwd_to_sys_path()
        entry = import_string(ENTRY_PY.replace('.py', ''))
        asm_app = entry.app
        app_dir = CWD
        cli_admin() if is_admin is True else cli()
        return 
    else:
        header()
        if len(sys.argv) == 1 or (len(sys.argv) > 1 and sys.argv[1] != 'init'):
            print("Error: %s is  not setup yet" % about.__title__)
            print("Run %s in the directory you want to create it" % bold("asm-admin init"))
            print("Missing file '%s' in %s" % (ENTRY_PY, CWD))
            print('_' * 80)
            print("")
    if is_admin is True:
        cli_admin()
Пример #47
0
    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.

        Just the uppercase variables in that object are stored in the config
        after lowercasing.  Example usage::

            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.

        :param obj: an import name or object
        """
        if isinstance(obj, basestring):
            obj = import_string(obj)
        for key in dir(obj):
            if key.isupper():
                self[key] = getattr(obj, key)
Пример #48
0
    def __getitem__(self, module):
        """Returns the configuration for a module. If it is not already
        set, loads a ``default_config`` variable from the given module and
        updates the configuration with those default values

        Every module that allows some kind of configuration sets a
        ``default_config`` global variable that is loaded by this function,
        cached and used in case the requested configuration was not defined
        by the user.

        :param module:
            The module name.
        :returns:
            A configuration value.
        """
        if module not in self.loaded:
            # Load default configuration and update config.
            values = import_string(module + '.default_config', silent=True)
            if values:
                self.setdefault(module, values)

            self.loaded.append(module)

        try:
            return dict.__getitem__(self, module)
        except KeyError:
            raise KeyError('Module %r is not configured.' % module)
Пример #49
0
    def load_middleware(self, classes):
        """Returns a dictionary of middleware instance methods for a list of
        classes.

        :param classes:
            A list of middleware classes.
        :return:
            A dictionary with middleware instance methods.
        """
        res = {}

        for cls in classes:
            if isinstance(cls, basestring):
                id = cls
            else:
                id = cls.__module__ + '.' + cls.__name__

            if id not in self.methods:
                if isinstance(cls, basestring):
                    cls = import_string(cls)

                obj = cls()
                self.instances[id] = obj
                self.methods[id] = [getattr(obj, n, None) for n in self.names]

            for name, method in zip(self.names, self.methods[id]):
                if method:
                    res.setdefault(name, []).append(method)

        for name in self.reverse_names:
            if name in res:
                res[name].reverse()

        return res
Пример #50
0
    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.

        Just the uppercase variables in that object are stored in the config
        after lowercasing.  Example usage::

            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.

        :param obj: an import name or object
        """
        if isinstance(obj, basestring):
            obj = import_string(obj)
        for key in dir(obj):
            if key.isupper():
                self[key] = getattr(obj, key)
Пример #51
0
def _load(Obj,lister, force=False):
	for obj in lister:
		name = NotGiven
		doc = NotGiven
		if isinstance(obj,(list,tuple)):
			if len(obj) > 2:
				doc = obj[2]
			name = obj[1]
			obj = obj[0]
		if isinstance(obj,string_types):
			obj = import_string(obj)
			if name is NotGiven:
				name = getattr(obj,'NAME',name)
			if doc is NotGiven:
				doc = getattr(obj,'DOC',doc)
		
		path = obj.__module__+'.'+obj.__name__
		try:
			obj = Obj.q.get_by(path=path)
		except NoData:
			if name is NotGiven:
				name = path
			obj = Obj.new(name=name, path=path)
		else:
			_upd(obj,(('name',name),('doc',doc)), force=force)

		add_vars(getattr(obj.mod,'VAR',()),obj, force=force)
		add_templates(getattr(obj.mod,'TEMPLATE',()), parent=obj, force=force)
Пример #52
0
def add_objtypes(objects, force=False):
	"""Add a list of MIME types."""

	objs = []
	for obj in objects:
		name = NotGiven
		doc = NotGiven
		if isinstance(obj,(list,tuple)):
			if len(obj) > 2:
				doc = obj[2]
			name = obj[1]
			obj = obj[0]
		if isinstance(obj,string_types):
			obj = import_string(obj)
			if name is NotGiven:
				name = getattr(obj,'NAME',name)
			if doc is NotGiven:
				doc = getattr(obj,'DOC',doc)

		objs.append((obj,name,doc))

	db.create_all()
	try:
		root = root_site.add_default_permissions
	except NoData:
		return

	for obj,name,doc in objs:
		obj = ObjType.get(obj) # will create the record
		_upd(obj,(('name',name),('doc',doc)), force=force)
		if obj._is_new or force:
			root(obj)
Пример #53
0
    def dispatch(self, request):
        """Dispatches a request. This instantiates and calls a
        :class:`tipfy.RequestHandler` based on the matched :class:`Rule`.

        :param request:
            A :class:`tipfy.app.Request` instance.
        :param match:
            A tuple ``(rule, rule_args)`` with the matched rule and rule
            arguments.
        :param method:
            A method to be used instead of using the request or handler method.
        :returns:
            A :class:`tipfy.app.Response` instance.
        """
        rule, rule_args = self.match(request)
        handler = rule.handler
        if isinstance(handler, basestring):
            if handler not in self.handlers:
                self.handlers[handler] = import_string(handler)

            rule.handler = handler = self.handlers[handler]

        rv = local.current_handler = handler(request)
        if not isinstance(rv, BaseResponse) and hasattr(rv, '__call__'):
            # If it is a callable but not a response, we call it again.
            rv = rv()

        return rv
Пример #54
0
    def load_cache(self):
        """
        Load the cache and assign the Cache interface to
        """
        BackendClass = import_string(self.cache_type)

        if self.cache_type == 'werkzeug.contrib.cache.NullCache':
            self.cache = BackendClass(self.cache_default_timeout)
        elif self.cache_type == 'werkzeug.contrib.cache.SimpleCache':
            self.cache = BackendClass(
                self.cache_threshold, self.cache_default_timeout)
        elif self.cache_type == 'werkzeug.contrib.cache.MemcachedCache':
            self.cache = BackendClass(
                self.cache_memcached_servers,
                self.cache_default_timeout,
                self.cache_key_prefix)
        elif self.cache_type == 'werkzeug.contrib.cache.GAEMemcachedCache':
            self.cache = BackendClass(
                self.cache_default_timeout,
                self.cache_key_prefix)
        elif self.cache_type == 'werkzeug.contrib.cache.FileSystemCache':
            self.cache = BackendClass(
                self.cache_dir,
                self.cache_threshold,
                self.cache_default_timeout)
        else:
            self.cache = BackendClass(**self.cache_init_kwargs)
Пример #55
0
def register_blueprints(app: flask.Flask) -> None:
    # Every sub-view needs to be imported to populate the blueprint.
    # If this is not done, we will have empty blueprints.
    # If we register every module with the ``bp`` attribute normally,
    # we would have a lot of duplicate routes, which Werkzeug doesn't filter.
    for name in find_modules('core', recursive=True):
        if not name.endswith('conftest'):
            import_string(name)

    # Now import and register each blueprint. Since each blueprint
    # is defined in the package's __init__, we scan packages this time,
    # unlike the last.
    for name in find_modules('core', include_packages=True):
        if not name.endswith('conftest'):
            mod = import_string(name)
            if hasattr(mod, 'bp'):
                app.register_blueprint(mod.bp)
Пример #56
0
 def install_app(self, app):
     install_apps = app.config.setdefault('INSTALLED_APPS', [])
     for blueprint in install_apps:
         kwargs = {}
         if isinstance(blueprint, dict):
             kwargs = blueprint['kwargs']
             blueprint = blueprint['blueprint']
         app.register_blueprint(import_string(blueprint), **kwargs)