def get_method(self, string): """Returns a lazily-evaluated callable.""" if not string: return None if hasattr(string, '__call__'): return string package, reference = string.split(':', 1) prop = None if '.' in reference: reference, prop = reference.rsplit('.', 1) obj = load_object('%s:%s' % (package, reference)) if not prop: def lazy(*args, **kw): return obj(*args, **kw) return lazy def lazy(*args, **kw): return getattr(obj, prop)(*args, **kw) return lazy
def database(app, config): # Determine if a database engine has been requested, and load the appropriate middleware. if not config.get('db.connections', None): return app try: for connection in array(config.get('db.connections')): connection = connection.strip(',') engine = config.get('db.%s.engine' % (connection,), 'sqlalchemy') try: if '.' in engine and ':' in engine: engine = load_object(engine) else: try: engine = [i for i in pkg_resources.iter_entry_points(group='webcore.db.engines', name=engine)][0].load() except IndexError: raise Exception('No engine registered with the name: %s' % (engine,)) except: log.exception("Unable to load engine middleware: %r.", engine) raise try: model = config.get('db.%s.model' % (connection,)) model = load_object(model) if isinstance(model, basestring) else model except: log.exception("Unable to load application model: %r.", model) raise try: session = config.get('db.%s.session' % (connection,), '%s:session' % (config.get('db.%s.model' % (connection,)),)) session = load_object(session) if isinstance(session, basestring) else session except: log.info("No session defined for the %s database connection.", connection) app = engine(app, 'db.%s' % (connection,), model, session, **config) return app except: log.exception("Error initializing database connections.") raise
def _load(spec, group): if not isinstance(spec, basestring): # It's already an object, just use it. return spec if ':' in spec: # Load the Python package(s) and target object. return load_object(spec) # Load the entry point. for entrypoint in pkg_resources.iter_entry_points(group, spec): return entrypoint.load()
def ready(self): super(SQLAlchemyMiddleware, self).ready() populate = getattr(self.model, 'populate', None) if hasattr(populate, '__call__'): warnings.warn("Use of the hard-coded 'populate' callback is deprecated.\n" "Use the 'ready' callback instead.", DeprecationWarning) for table in self.model.metadata.sorted_tables: event.listen(table, 'after_create', self.populate_table) cb = self.config.get(self.prefix + '.ready', None) if cb is not None: cb = load_object(cb) if isinstance(cb, basestring) else cb if hasattr(cb, '__call__'): cb(self._session)
def factory(cls, gconfig=dict(), root=None, **config): """Build a full-stack framework around this WSGI application.""" log = __import__('logging').getLogger(__name__ + ':factory') log.info("Preparing WebCore WSGI middleware stack.") # Define the configuration earlier to allow the root controller's __init__ to use it. web.core.config = gconfig.copy() web.core.config.update(config) config = web.core.config root = config.get('web.root', root) log.debug("Root configured as %r.", root) # Find, build, and configure our basic Application instance. if isinstance(root, basestring): config['web.root.package'] = root.split('.', 1)[0] log.debug("Loading root controller from '%s'.", root) root = load_object(root) if isinstance(root, type): root = root() if not isinstance(root, Dialect) and not hasattr(root, '__call__'): raise ValueError("The root controller must be defined using package dot-colon-notation or direct reference and must be either a WSGI app or Dialect.") config['web.root'] = root app = cls(root, config) base_app = app for mware in cls.middleware(): app = mware(app, config) base_app.app = app log.info("WebCore WSGI middleware stack ready.") return app
def MongoEngineMiddleware(application, prefix, model, session=None, **config): url = config.get('%s.url' % (prefix,), 'mongo://localhost') log.info("Connecting MongoEngine to '%s'.", _safe_uri_replace.sub(r'\1://\2@', url)) connection = dict(tz_aware=True) scheme, parts = url.split('://', 1) parts, db = parts.split('/', 1) auth, host = parts.split('@', 1) if '@' in parts else (None, parts) if scheme != 'mongo': raise Exception('The URL must begin with \'mongo://\'!') connection['host'], connection['port'] = host.split(':') if ':' in host else (host, '27017') connection['port'] = int(connection['port']) if auth: # pragma: no cover connection['username'], _, connection['password'] = auth.partition(':') log.debug("Connecting to %s database with connection information: %r", db, connection) model.__dict__['connection'] = mongoengine.connect(db, **connection) prepare = getattr(model, 'prepare', None) if hasattr(prepare, '__call__'): warnings.warn("Use of the hard-coded 'prepare' callback is deprecated.\n" "Use the 'ready' callback instead.", DeprecationWarning) prepare() cb = config.get(prefix + '.ready', None) if cb is not None: cb = load_object(cb) if isinstance(cb, basestring) else cb if hasattr(cb, '__call__'): cb() return application
def MongoMiddleware(application, prefix, model, session=None, **config): url = config.get('%s.url' % (prefix,), 'mongo://localhost') log.info("Connecting Mongo to '%s'.", _safe_uri_replace.sub(r'\1://\2@', url)) scheme, parts = url.split('://', 1) parts, db = parts.split('/', 1) auth, host = parts.split('@', 1) if '@' in parts else (None, parts) if scheme != 'mongo': raise Exception('The URL must begin with \'mongo://\'!') host, port = host.split(':') if ':' in host else (host, '27017') log.debug("Connection: %r", (scheme, auth.split(':', 1) if auth else [None, None], host, port, db)) model.__dict__['connection'] = Connection(host if host else 'localhost', int(port)) model.__dict__['db'] = model.connection[db] if auth and not model.db.authenticate(*auth.split(':', 1)): raise Exception("Error attempting to authenticate to MongoDB.") prepare = getattr(model, 'prepare', None) if hasattr(prepare, '__call__'): warnings.warn("Use of the hard-coded 'prepare' callback is deprecated.\n" "Use the 'ready' callback instead.", DeprecationWarning) prepare() cb = config.get(prefix + '.ready', None) if cb is not None: cb = load_object(cb) if isinstance(cb, basestring) else cb if hasattr(cb, '__call__'): cb(model.db) return application
def marrowhttpd(factory, host=None, port=8080, fork=1, verbose=False, quiet=False, **options): """Marrow HTTP/1.1 Server This script allows you to use a factory function to configure middleware, application settings, and filters. Specify the dot-notation path (e.g. mypkg.myapp:factory) as the first positional argument. To demonstrate the server use "marrow.server.http.testing:hello" as the factory. This factory accepts one argument, --name, allowing you to personalize the response. You can specify an unlimited number of --name=value arguments which will be passed to the factory. """ if verbose and quiet: print("Can not set verbose and quiet simultaneously.") return 1 try: factory = load_object(factory) except: print("Error loading factory: %s", factory) return 2 logging.basicConfig(level=logging.DEBUG if verbose else logging.WARN if quiet else logging.INFO) HTTPServer(host, port, fork=fork, **factory(**options)).start()
def load(area): return load_object("brave.core.{}.controller:{}Controller".format(area, area.title()))()
def load(area): return load_object("brave.core.{}.controller:{}Controller".format( area, area.title()))()
def test_load_object(self): self.failUnless(load_object('marrow.util.bunch:Bunch') is Bunch) self.assertRaises(AttributeError, lambda: load_object('marrow.util.bunch:Foo')) self.assertRaises(ImportError, lambda: load_object('marrow.foo:Bar'))
def construct_python_object(self, node): value = str(self.construct_scalar(node)) return load_object(value)