def render(style, target, template_engine = None): module = None if not style: #try style file in project directory modname = '{0}.style'.format(sites.settings.SITE_MODULE) try: module = import_module(modname) except ImportError: pass if not module: style = style or default_style bits = style.split('.') if len(bits) == 1: modname = 'djpcms.themes.{0}'.format(style) else: raise ValueError('Style {0} not available'.format(style)) try: module = import_module(modname) except ImportError: raise ValueError('Style {0} not available'.format(style)) context = module.context.copy() context.update({'MEDIA_URL': sites.settings.MEDIA_URL}) data = context.render(template_engine) f = open(target,'w') f.write(data) f.close()
def application_map(): map = {} from django.conf import settings for app in settings.INSTALLED_APPS: sapp = app.split('.') name = sapp[-1] if app.startswith('django.'): continue if app == 'django.contrib.admin': base = 'admin' handler = djangoAdminHandler else: continue else: base = name handler = pathHandler try: module = import_module(app) except: continue path = module.__path__[0] map[base] = handler(settings.MEDIA_URL,name,path) return map
def load_command_class(app_name, name): """ Given a command name and an application name, returns the Command class instance. All errors raised by the import process (ImportError, AttributeError) are allowed to propagate. """ module = import_module('%s.management.commands.%s' % (app_name, name)) return module.Command(name)
def application_directories(package_path): app_template_dirs = [] for app in sites.settings.INSTALLED_APPS: try: mod = import_module(app) except ImportError, e: raise ImproperlyConfigured('ImportError %s: %s' % (app, e.args[0])) template_dir = os.path.join(os.path.dirname(mod.__file__), package_path) if os.path.isdir(template_dir): app_template_dirs.append(template_dir)
def make(self, name, settings = None, route = None, clearlog = True, **kwargs): '''Initialise DjpCms from a directory or a file''' import djpcms # # if not a directory it may be a file if os.path.isdir(name): appdir = name elif os.path.isfile(name): appdir = os.path.split(os.path.realpath(name))[0] else: try: mod = import_module(name) appdir = mod.__path__[0] except ImportError: raise ValueError('Could not find directory or file {0}'.format(name)) path = os.path.realpath(appdir) base,name = os.path.split(path) if base not in sys.path: sys.path.insert(0, base) # Import settings settings = settings or 'settings' if '.' in settings: settings_module_name = settings os.environ['DJANGO_SETTINGS_MODULE'] = settings else: sett = '{0}.py'.format(os.path.join(path,settings)) if os.path.isfile(sett): spath, settings = os.path.split(settings) settings_module_name = '{0}.{1}'.format(name,settings) os.environ['DJANGO_SETTINGS_MODULE'] = settings_module_name else: settings_module_name = None # IMPORTANT! NEED TO IMPORT HERE TO PREVENT DJANGO TO IMPORT FIRST settings = get_settings(settings_module_name, SITE_DIRECTORY = path, SITE_MODULE = name, **kwargs) # If no settings available get the current one if self._settings is None: self._settings = settings # Add template media directory to template directories path = os.path.join(djpcms.__path__[0],'media','djpcms') if path not in settings.TEMPLATE_DIRS: settings.TEMPLATE_DIRS += path, djpcms.init_logging(clearlog) self.logger = logging.getLogger('ApplicationSites') return self._create_site(route,settings)
def __init__(self, settings_module_name, **kwargs): self.__dict__['_values'] = {} self.__dict__['_settings'] = [] self.__dict__['settings_module_name'] = settings_module_name self.fill(djpcms_defaults) if self.settings_module_name: settings_module = import_module(settings_module_name) self.fill(settings_module) self.update(kwargs) ajax = self.HTML_CLASSES if not ajax: self.HTML_CLASSES = ajaxhtml()
def build_suite(app_module): '''Create a test suite for the provided application module. Look into the test module if it exists otherwise do nothing.''' suite = TestSuite() app_path = app_module.__name__.split('.')[:-1] try: test_module = import_module('{0}.tests'.format('.'.join(app_path))) except ImportError: test_module = None if test_module: suite.addTest(unittest.defaultTestLoader.loadTestsFromModule(test_module)) return suite
def find_template_loader(self, code, args): bits = code.split('.') module, attr = '.'.join(bits[:-1]),bits[-1] try: mod = import_module(module) except ImportError as e: raise ImproperlyConfigured('Error importing template source loader {0}: "{1}"'.format(module, e)) try: TemplateLoader = getattr(mod, attr) except AttributeError as e: raise ImproperlyConfigured('No template loader attribute {0} in {1}: "{2}"'.format(attr, module, e)) fargs = [arg if not hasattr(arg,'__call__') else arg() for arg in args] return TemplateLoader(*fargs)
def get_admins(INSTALLED_APPS): for apps in INSTALLED_APPS: if apps.startswith('django.'): continue try: mname = apps.split('.')[-1] admin = import_module('{0}.admin'.format(apps)) urls = getattr(admin,'admin_urls',None) if not urls: continue name = getattr(admin,'NAME',mname) route = getattr(admin,'ROUTE',mname) yield (name, route, urls) except ImportError: continue
def render(site, theme, apps, mediaurl, dump_variables): LOGGER.info('Building theme "%s"' % theme) module = None applications = list(apps or site.settings.INSTALLED_APPS) imported = {} mediaurl = mediaurl or site.settings.MEDIA_URL if site.settings.SITE_MODULE not in applications: applications.append(site.settings.SITE_MODULE) # Import applications styles if available for app in applications: modname = '{0}.style'.format(app) if modname in imported: continue try: imported[modname] = import_module(modname) LOGGER.info('Successfully imported style from "{0}".'\ .format(modname)) except ImportError as e: # We need to check if the fily actually exists log = False try: appm = import_module(app) except ImportError: log = True else: path = getattr(appm, '__path__', None) if path: pdir = os.path.join(path[0], 'style') pfil = pdir + '.py' if os.path.exists(pdir) or os.path.exists(pfil): log = True if log: LOGGER.error('Cannot import application {0}: "{1}"'\ .format(app,e)) #mediaurl = mediaurl return dump_theme(theme, dump_variables=dump_variables)
def load(): '''Load markup applications''' global _loaded if not _loaded: path = os.path.split(os.path.abspath(__file__))[0] for d in os.listdir(path): if os.path.isdir(os.path.join(path,d)): try: appmod = import_module('djpcms.contrib.flowrepo.markups.{0}'.format(d)) app = appmod.app except ImportError, e: pass else: app.setup() add(d,app.name,app) _loaded = True
def get_settings(name=None, settings=None, **params): '''Extra configuration parameters,can be passed as key-value pairs: :parameter name: file or directory name which specifies the application root-directory. :parameter settings: optional settings file name specified as a dotted path relative ro the application directory. Default ``None`` :parameter params: key-value pairs which override the values in the settings file. ''' name = Path(name if name is not None else os.getcwd()) if name.isdir(): appdir = name elif name.isfile(): appdir = name.realpath().parent else: try: mod = import_module(name) appdir = Path(mod.__path__[0]) except ImportError: raise ValueError( 'Could not find directory or file {0}'.format(name)) site_path = appdir.realpath() base, name = site_path.split() if base not in sys.path: sys.path.insert(0, str(base)) # Import settings if settings: if '.' in settings: settings_module_name = settings else: sett = '{0}.py'.format(os.path.join(site_path, settings)) if os.path.isfile(sett): settings_module_name = '{0}.{1}'.format(name, settings) else: settings_module_name = settings else: settings_module_name = None return Config(settings_module_name, SITE_DIRECTORY=site_path, SITE_MODULE=name, **params)
def load(): '''Load markup applications.''' global _loaded if not _loaded: path = os.path.split(os.path.abspath(__file__))[0] for name in os.listdir(path): if not (name.startswith('_') or name.endswith('.pyc')): name = name.split('.')[0] if name == 'base': continue try: appmod = import_module('djpcms.utils.markups.'+name) except: pass else: add(appmod.Application()) _loaded = True
def load(): '''Load markup applications.''' global _loaded if not _loaded: path = os.path.split(os.path.abspath(__file__))[0] for name in os.listdir(path): if not (name.startswith('_') or name.endswith('.pyc')): name = name.split('.')[0] if name == 'base': continue try: appmod = import_module('djpcms.utils.markups.' + name) except: pass else: add(appmod.Application()) _loaded = True
def get_commands(self): if not hasattr(self,'_commands'): self._commands = gc = {} # Find and load the management module for each installed app. for app_name in self.settings.INSTALLED_APPS: command_module = app_name if app_name == 'djpcms': command_module = 'djpcms.cms' try: mod = import_module(command_module+'.management') if hasattr(mod,'__path__'): path = mod.__path__[0] gc.update(dict(((name, command_module) for name in find_commands(path)))) except ImportError: pass # No management module return self._commands
def get_settings(name=None, settings=None, **params): '''Extra configuration parameters,can be passed as key-value pairs: :parameter name: file or directory name which specifies the application root-directory. :parameter settings: optional settings file name specified as a dotted path relative ro the application directory. Default ``None`` :parameter params: key-value pairs which override the values in the settings file. ''' name = Path(name if name is not None else os.getcwd()) if name.isdir(): appdir = name elif name.isfile(): appdir = name.realpath().parent else: try: mod = import_module(name) appdir = Path(mod.__path__[0]) except ImportError: raise ValueError( 'Could not find directory or file {0}'.format(name)) site_path = appdir.realpath() base, name = site_path.split() if base not in sys.path: sys.path.insert(0, str(base)) # Import settings if settings: if '.' in settings: settings_module_name = settings else: sett = '{0}.py'.format(os.path.join(site_path,settings)) if os.path.isfile(sett): settings_module_name = '{0}.{1}'.format(name, settings) else: settings_module_name = settings else: settings_module_name = None return Config(settings_module_name, SITE_DIRECTORY=site_path, SITE_MODULE=name, **params)
def get_commands(self): if not hasattr(self, '_commands'): self._commands = gc = {} # Find and load the management module for each installed app. for app_name in self.settings.INSTALLED_APPS: command_module = app_name if app_name == 'djpcms': command_module = 'djpcms.cms' try: mod = import_module(command_module + '.management') if hasattr(mod, '__path__'): path = mod.__path__[0] gc.update( dict(((name, command_module) for name in find_commands(path)))) except ImportError: pass # No management module return self._commands
def application_map(applications, safe=True): '''Very very useful function for finding static media directories. It looks for the ``media`` directory in each installed application.''' map = {} for app in applications: sapp = app.split('.') name = sapp[-1] try: module = import_module(app) except: if not safe: raise continue path = getattr(module, '__path__', None) if path: handler = getattr(module, 'mediaPath', pathHandler) h = handler(name, path[0]) if os.path.exists(h.mpath): map[name] = h return map
def __init__(self, settings_module_name, **kwargs): self.__dict__['_values'] = {} self.__dict__['settings_module_name'] = settings_module_name self.fill(defaults) path = '' if self.settings_module_name: settings_module = import_module(settings_module_name) path = settings_module.__file__ if path.endswith('.pyc'): path = path[:-1] self.fill(settings_module) self.__dict__['path'] = path self.update(kwargs) site_module = self.get('SITE_MODULE') apps = ['djpcms'] for app in self.INSTALLED_APPS: if app not in apps and app != site_module: apps.append(app) if site_module: apps.append(site_module) self.INSTALLED_APPS = tuple(apps)
def _load(self): """Registers an instance of :class:`djpcms.views.appsite.Application` to the site. If a model is already registered, this will raise AlreadyRegistered.""" name = self.settings.APPLICATION_URL_MODULE appurls = () if name: app_module = import_module(name) appurls = app_module.appurls self.load_initial() for application in appurls: self.register(application) url = self.make_url urls = () # Add in each model's views. for app in self._nameregistry.values(): baseurl = app.baseurl if baseurl: urls += url('^{0}(.*)'.format(baseurl[1:]), app, name = app.name), return urls
def __init__(self, settings_module_name, **kwargs): self.__dict__["_values"] = {} self.__dict__["settings_module_name"] = settings_module_name self.fill(defaults) path = "" if self.settings_module_name: settings_module = import_module(settings_module_name) path = settings_module.__file__ if path.endswith(".pyc"): path = path[:-1] self.fill(settings_module) self.__dict__["path"] = path self.update(kwargs) site_module = self.get("SITE_MODULE") apps = ["djpcms"] for app in self.INSTALLED_APPS: if app not in apps and app != site_module: apps.append(app) if site_module: apps.append(site_module) self.INSTALLED_APPS = tuple(apps)
def setup_environment(self): '''Set up the the site.''' for app in self.settings.INSTALLED_APPS: try: mod = import_module(app+'.request') for name in dir(mod): processor = getattr(mod, name) if getattr(processor, 'request_processor', False): self.request_processors.append(processor) except ImportError: pass # No management module if self.root == self: for wrapper in orms.model_wrappers.values(): wrapper.setup_environment(self) add_default_handlers(self) appurls = self.APPLICATION_URLS if appurls: if not hasattr(appurls, '__call__'): if isinstance(appurls, str): appurls = module_attribute(appurls,safe=False) if hasattr(appurls,'__call__'): appurls = appurls(self) self.routes.extend(copy(appurls)) return len(self)
def setup_environment(self): '''Set up the the site.''' for app in self.settings.INSTALLED_APPS: try: mod = import_module(app + '.request') for name in dir(mod): processor = getattr(mod, name) if getattr(processor, 'request_processor', False): self.request_processors.append(processor) except ImportError: pass # No management module if self.root == self: for wrapper in orms.model_wrappers.values(): wrapper.setup_environment(self) add_default_handlers(self) appurls = self.APPLICATION_URLS if appurls: if not hasattr(appurls, '__call__'): if isinstance(appurls, str): appurls = module_attribute(appurls, safe=False) if hasattr(appurls, '__call__'): appurls = appurls(self) self.routes.extend(copy(appurls)) return len(self)
site_urls.append((r'^%s' % admin_url_prefix[1:], include(admin.site.urls))) except: pass ####################################################################################### # MEDIA FILES ONLY IF REQUESTED if settings.SERVE_STATIC_FILES and settings.MEDIA_URL: murl = settings.MEDIA_URL.lstrip("/") # Add application media directories if they exists for app in settings.INSTALLED_APPS: if app.startswith('django.'): continue try: module = import_module(app) except: continue path = module.__path__[0] app = app.split('.')[-1] mediapath = os.path.join(path,'media',app) if os.path.isdir(mediapath): site_urls.append(url(r'^%s%s/(?P<path>.*)$' % (murl,app), 'django.views.static.serve', {'document_root': mediapath, 'show_indexes': True} )) mediaroot = settings.MEDIA_ROOT mediasite = os.path.join(mediaroot,'site') site_urls.append(url(r'^%s(?P<path>.*)$' % murl, #r'^{0}site/(?P<path>.*)$'.format(murl), 'django.views.static.serve',
def check(self, name): try: import_module(name) self.libs.append(name) except ImportError: return None