def execute(): # Arguments parser options, args = get_option_parser(basic_option_list, cls=BasicOptionParser, add_help_option=False) settings.project_settings = import_anything(options.settings) # Command parsing subcommand = get_subcommand(sys.argv[1]) command_class = None # Find the command in the command directories for path in commands.get_commands(): if path.endswith('.'+subcommand): try: command_class = import_anything(path+'.Command') break except ImportError: pass # If the command doesn't exist... if not command_class: print('Command not found.') sys.exit(1) # Arguments parser options, args = get_option_parser(command_class.option_list) if options.run_with_pdb: pdb.set_trace() kwargs = dict([(opt.dest, getattr(options, opt.dest, opt.default)) for opt in command_class.option_list]) # Running the command cmd = command_class(settings.project_settings) cmd.execute(*args[2:], **kwargs)
def execute(self, *args, **kwargs): commands = [] # Finds command classes in available modules for cmd in get_commands(): module = import_anything(cmd) cls = import_anything('Command', module) commands.append((cmd.split('.')[-1], module, cls)) commands.sort(lambda a,b: cmp(a[0], b[0])) # Prints their details print('Available commands:') for cmd, module, cls in commands: print('\n%s' % cmd) help = '' if getattr(cls, 'help', None): help = cls.help elif cls.__doc__: help = cls.__doc__ if help: help = textwrap.wrap(help, 80) print(' ' + '\n '.join(help))
def process_request(self, request): request.site = None # Try using site detecting function if app_settings.DETECTING_FUNCTION: try: func = import_anything(app_settings.DETECTING_FUNCTION) site_or_mirror = func(request) if isinstance(site_or_mirror, SiteMirror): request.site = site_or_mirror['site'] if app_settings.MIRROR_PERMANENT_REDIRECT: scheme = 'https' if (request.is_secure() or site_or_mirror['https_is_default']) else 'http' new_hostname = site_or_mirror['site']['hostname'] if request.META.get('SERVER_PORT', 80) != 80: new_hostname += ':%s'%request.META['SERVER_PORT'] return HttpResponsePermanentRedirect('%s://%s/'%(scheme, new_hostname)) else: request.site = site_or_mirror except ImportError: pass # Treats the inactive site if ((not request.site or not request.site['is_active']) and not app_settings.ACCEPT_INACTIVE_SITE and app_settings.INACTIVE_SITE_VIEW): view = import_anything(INACTIVE_SITE_VIEW) return view(request) # Creates a new site if there is no site existing if Site.query().count() == 0 and app_settings.CREATE_SITE_IF_EMPTY: request.site = Site(_save=True, name='localhost', hostname='localhost', default=True, active=True)
def process_response(self, request, response): if isinstance(response, ErrorHttpResponse): view_name = app_settings.ERROR_HANDLERS[response.status_code] if response.status_code in app_settings.ERROR_HANDLERS else None view = import_anything(view_name) if view_name else import_anything(app_settings.ERROR_HANDLERS['other']) response.content = view(request, status_code=response.status_code, status_string=response.status_string, traceback_string=traceback.format_exc()).content return response
def reverse(name_or_view, args=None, kwargs=None, service='public'): """ Returns the URL string for a given URL name, view name or view object and named and no-named arguments. This function cannot stay in the same module of parser and defining functions because it imports the project (could start a circular reference). """ args = args or [] kwargs = kwargs or {} if args and kwargs: raise ValueError("It's not possible to find a URL by *args and **kwargs both informed.") # Tries to import name_or_view if it's a valid object path if isinstance(name_or_view, basestring): try: name_or_view = import_anything(name_or_view) except ImportError: pass urls = settings.SERVICES[service]['urls'] if isinstance(urls, basestring): urls = import_anything(urls) def strip_url(path): if path.startswith('^'): path = path[1:] if path.endswith('$'): path = path[:-1] return path def find_url(_name_or_view, _url_patterns, _args, _kwargs): for _url in _url_patterns: if isinstance(_url.children_urls, (tuple, list)): try: path = find_url(_name_or_view, _url.children_urls, _args, _kwargs) except NoReverseMatch: continue if path is not None: return strip_url(_url.exp) + path elif _name_or_view in (_url.view, _url.name): return strip_url(_url.exp) raise NoReverseMatch('URL "%s" wasn\'t found with args %s and kwargs %s'%( name_or_view, args or '()', kwargs or '{}')) # Finds the URL for the requested arguments full_path = '/' + find_url(name_or_view, urls.url_patterns, args, kwargs) return replace_groups(full_path, args, kwargs)
def process_request(self, request): if app_settings.CHOOSING_FUNCTION: try: path, func_name = app_settings.CHOOSING_FUNCTION.rsplit('.', 1) except ValueError: raise ImproperlyConfigured("Setting THEMES_CHOOSING_FUNCTION has '%s' with a unknown function path."%app_settings.CHOOSING_FUNCTION) try: mod = import_anything(path) except ImportError: raise ImproperlyConfigured("Module '%s' wasn't found."%path) try: func = getattr(mod, func_name) except AttributeError: raise ImproperlyConfigured("Module '%s' hasn't a function called."%func_name) request.theme = func(request) if not getattr(request, 'theme', None): if getattr(request, 'site', None) and request.site['theme']: request.theme = request.site['theme'] else: try: request.theme = Theme.query().get(is_default=True) except Theme.DoesNotExist: request.theme = None
def get_commands(): global _commands if _commands is not None: return _commands _commands = [] for module in get_commands_modules(): if isinstance(module, basestring): module = import_anything(module) for file_path in glob.glob(os.path.join(module.__path__[0], '*.py')): f_dir, f_name = os.path.split(file_path) if f_name.startswith('__init__.'): continue # Reading file to confirm that's a command fp = file(file_path) content = fp.read() fp.close() if EXP_COMMAND.search(content): _commands.append('%s.%s'%(module.__name__, os.path.splitext(f_name)[0])) return _commands
def get_storage_class(import_path=None): if import_path is None: import_path = settings.DEFAULT_FILE_STORAGE try: return import_anything(import_path) except ImportError as e: raise ImproperlyConfigured('Storage module "%s" does not define a "%s" class.' % (module, classname))
def save_attachments(self, obj): try: engine_str = self.Attachments.engine except AttributeError: engine_str = app_settings.DEFAULT_ENGINE engine_cls = import_anything(engine_str) engine_cls().save_form(self, obj)
def query(cls, **kwargs): query_class = import_anything(cls._meta.query) query = query_class(model=cls) if kwargs: query = query.filter(**kwargs) return query
def get_connection(name): if name not in app_settings.CONNECTIONS: raise MailingConnectionNotFound('Mailing connection "%s" was not found in MAILING_CONNECTIONS setting.' % name) engine_class = import_anything(app_settings.CONNECTIONS[name]["engine"]) kwargs = app_settings.CONNECTIONS[name].copy() kwargs.pop("engine") return engine_class(**kwargs)
def load_middleware(self): self._middleware_instances = [] for path in (self.middleware_classes or settings.MIDDLEWARE_CLASSES): cls = import_anything(path) inst = cls() inst.service = self self._middleware_instances.append(inst)
def get_app(name): """Returns application module for a given name""" try: entry = settings.INSTALLED_APPS[name] path = entry if isinstance(entry, basestring) else entry[0] mod = import_anything(path) mod._app_in_london = name mod._installed_entry = entry try: mod._models = import_anything('models', mod) except ImportError: mod._models = None return mod except (ImportError, KeyError): raise ApplicationNotFound('Application "%s" was not found.'%name)
def make_m2m_related_queryset(model, related_field_name): """ Factory method to make a queryset class based on the model queryset and the ManyToManyRelatedQuerySet, so it gets a new instance to return. This is important to return a queryset with all model's queryset methods and the ManyToManyRelatedQuerySet methods as well. """ model_queryset_class = import_anything(model._meta.query) new_class = type('%s%sRelatedQuerySet'%(model.__name__, related_field_name), (ManyToManyRelatedQuerySet, model_queryset_class), {}) return new_class(model, related_field_name)
def get_service(settings, name): """ Finds the service dictionary in settings and returns a service instance. """ service_dict = settings.SERVICES[name].copy() service_class = import_anything(service_dict.pop("handler")) service_inst = service_class(**service_dict) service_inst.name = name return service_inst
def include(module): """ Includes a module object or a module path containing another url_patterns to parse a group of URLs. """ module = import_anything(module) if isinstance(module, basestring) else module if isinstance(module, (list, tuple)): return module else: return module.url_patterns
def get_model(path): """Returns the model class for a given path in "app.Model" format.""" try: return import_anything(path) except ImportError: pass path = '.'.join(path.split('.', 1)[-2:]) if path in _registered_models: return _registered_models[path] else: raise ImportError('Model "%s" was not found.'%path)
def get_global_contexts(request, **kwargs): """ Function responsible for find all template context processors from settings and return them to the global template context. """ context = {} for path in settings.TEMPLATE_CONTEXT_PROCESSORS: func = import_anything(path) context.update(func(request)) return context
def parse_view(self): self.children_urls = None self.view = None if isinstance(self.path[1], (tuple, list)): self.children_urls = self.path[1] elif callable(self.path[1]): self.view = self.path[1] elif not isinstance(self.path[0], basestring) and isinstance(self.path[1], basestring): self.view = getattr(self.path[0], self.path[1]) else: self.view = import_anything(self.path)
def load_handler(path, *args, **kwargs): """ Given a path to a handler, return an instance of that handler. E.g.:: >>> load_handler('london.core.files.uploadhandler.TemporaryFileUploadHandler', request) <TemporaryFileUploadHandler object at 0x...> """ try: return import_anything(path)(*args, **kwargs) except ImportError as e: raise ImproperlyConfigured('Module "%s" does not define a "%s" upload handler backend' % (module, attr))
def get_engine_class(path): if isinstance(path, basestring): module, attr = path.rsplit(".", 1) try: mod = import_anything(module) except ImportError as e: raise ImproperlyConfigured('Template engine "%s" was not found.' % path) try: return getattr(mod, attr) except AttributeError: raise ImproperlyConfigured('Template engine "%s" was not found.' % path)
def append(self, obj, new=True): if self.related_class: if isinstance(obj, dict): obj = self.related_class(_nested_into=self.parent, **obj) elif not isinstance(obj, self.related_class): cls_name = '%s.%s'%(self.related_class.__module__, self.related_class.__name__) raise TypeError('Invalid object type "%s". Must be an instance from "%s"'%(repr(obj.__class__), cls_name)) else: if isinstance(obj, dict): obj = import_anything(items['_class'])(_nested_into=self.parent, **obj) self._items.append(obj) return obj
def load_from_applications(self, *apps): """ Loads applications given as arguments or all of installed applications if empty. """ apps = apps or load_apps() for mod in apps: try: rest_mod = import_anything('rest', mod) except ImportError as e: continue for attr in dir(rest_mod): cls = getattr(rest_mod, attr) if isinstance(cls, type) and issubclass(cls, BaseModule): self.register_module(getattr(rest_mod, attr))
def get_pool(): """Returns the instance of the current notifications pool in the system. It is able to recognize the setting was changed and then to create a new instance for the new class.""" global _pool if getattr(settings, "NOTIFICATIONS_POOL", None): pool_path = settings.NOTIFICATIONS_POOL else: from london.apps.notifications import app_settings pool_path = app_settings.DEFAULT_POOL if not _pool or _pool._string_setting != pool_path: _pool = import_anything(pool_path)() _pool._string_setting = pool_path return _pool
def import_and_get_loader(s): try: path, loader_name = s.rsplit(".", 1) except ValueError: raise ImproperlyConfigured("Invalid TEMPLATE_LOADER '%s'." % s) try: mod = import_anything(path) except ImportError: raise ImproperlyConfigured("Module '%s' wasn't found." % path) try: loader = getattr(mod, loader_name) except AttributeError: raise ImproperlyConfigured("Loader '%s' not found." % loader_name) return loader()
def resolve_url(path_info, urls): """ Finds the right URL from a list of URLs for a given path_info """ if isinstance(urls, (tuple, list)): url_patterns = urls else: if isinstance(urls, basestring): urls = import_anything(urls) url_patterns = urls.url_patterns for url in url_patterns: ret_url, args, kwargs = url.resolve(path_info) if ret_url: return ret_url, args, kwargs raise URLNotFound('URL for "%s" doesn\'t exist.'%path_info)
def get_connection(name='default', force_reopen=False): """ Opens and/or returns a connection by name. """ conn = _connections.get(name, None) if conn and force_reopen: if conn._connection: conn._connection.disconnect() del _connections[name] conn = None if not conn or not conn.is_open(): db_params = settings.DATABASES[name] engine_class = import_anything(db_params['engine']) conn = _connections[name] = engine_class(**db_params) return conn
def iter_format_modules(lang): """ Does the heavy lifting of finding format modules. """ if check_for_language(lang): format_locations = ['london.conf.locale.%s'] if settings.FORMAT_MODULE_PATH: format_locations.append(settings.FORMAT_MODULE_PATH + '.%s') format_locations.reverse() locale = to_locale(lang) locales = [locale] if '_' in locale: locales.append(locale.split('_')[0]) for location in format_locations: for loc in locales: try: yield import_anything(location % loc) except ImportError: pass
def load_storage(self, conf): # Loads default storages if not specific if not self.storages: import app_settings self.storages = app_settings.STORAGES # Supports reference by string key if isinstance(conf, basestring): conf = self.storages[conf] # Creates the instance if a configuration dict was given if isinstance(conf, dict): cls = import_anything(conf['engine']) kwargs = {} kwargs.update(conf) kwargs.pop('engine') return cls(**kwargs) return conf
def get_template_env(theme=None): """ Creates and return the templates environment for multiple sources. """ # Initializes the current environment custom_loaders = [] if settings.TEMPLATE_LOADERS: def import_and_get_loader(s): try: path, loader_name = s.rsplit(".", 1) except ValueError: raise ImproperlyConfigured("Invalid TEMPLATE_LOADER '%s'." % s) try: mod = import_anything(path) except ImportError: raise ImproperlyConfigured("Module '%s' wasn't found." % path) try: loader = getattr(mod, loader_name) except AttributeError: raise ImproperlyConfigured("Loader '%s' not found." % loader_name) return loader() custom_loaders = [import_and_get_loader(loader) for loader in settings.TEMPLATE_LOADERS] loaders = reduce(lambda a, b: a + b, get_template_loaders.send()) loader = ChoiceLoader(custom_loaders + loaders) template_env = Environment(loader=loader, extensions=settings.TEMPLATE_EXTENSIONS) template_env.theme = theme # Loads template filters for path in settings.TEMPLATE_FILTERS: mod = import_anything(path) for attr in dir(mod): item = getattr(mod, attr) if getattr(item, "environmentfilter", False): template_env.filters[attr] = item return template_env