def register_extensions(cls, *extensions): if not hasattr(cls, '_feincms_extensions'): cls._feincms_extensions = set() here = cls.__module__.split('.')[:-1] here_path = '.'.join(here + ['extensions']) common_path = '.'.join(here[:-1] + ['extensions']) for ext in extensions: if ext in cls._feincms_extensions: continue try: if isinstance(ext, basestring): try: fn = get_object(ext + '.register') except ImportError: try: fn = get_object('%s.%s.register' % (here_path, ext)) except ImportError: fn = get_object('%s.%s.register' % (common_path, ext)) # Not a string, so take our chances and just try to access "register" else: fn = ext.register cls.register_extension(fn) cls._feincms_extensions.add(ext) except Exception, e: raise ImproperlyConfigured( "%s.register_extensions('%s') raised an '%s' exception" % (cls.__name__, ext, e.message))
def register_extensions(cls, *extensions): if not hasattr(cls, '_feincms_extensions'): cls._feincms_extensions = set() here = cls.__module__.split('.')[:-1] here_path = '.'.join(here + ['extensions']) common_path = '.'.join(here[:-1] + ['extensions']) for ext in extensions: if ext in cls._feincms_extensions: continue try: if isinstance(ext, basestring): try: fn = get_object(ext + '.register') except ImportError: try: fn = get_object('%s.%s.register' % ( here_path, ext ) ) except ImportError: fn = get_object('%s.%s.register' % ( common_path, ext ) ) # Not a string, so take our chances and just try to access "register" else: fn = ext.register cls.register_extension(fn) cls._feincms_extensions.add(ext) except Exception, e: raise ImproperlyConfigured("%s.register_extensions('%s') raised an '%s' exception" % (cls.__name__, ext, e.message))
def register_extensions(cls, *extensions): """ Register all extensions passed as arguments. Extensions should be specified as a string to the python module containing the extension. If it is a bundled extension of FeinCMS, you do not need to specify the full python module path -- only specifying the last part (f.e. ``'seo'`` or ``'translations'``) is sufficient. """ if not hasattr(cls, '_feincms_extensions'): cls._feincms_extensions = set() here = cls.__module__.split('.')[:-1] paths = [ '.'.join(here + ['extensions']), '.'.join(here[:-1] + ['extensions']), 'feincms.module.extensions', ] for ext in extensions: if ext in cls._feincms_extensions: continue fn = None if isinstance(ext, basestring): try: fn = get_object(ext + '.register') except ImportError: for path in paths: try: fn = get_object('%s.%s.register' % (path, ext)) if fn: warnings.warn( 'Using short names for extensions has been deprecated' ' and will be removed in FeinCMS v1.8.' ' Please provide the full python path to the extension' ' %s instead (%s.%s).' % (ext, path, ext), DeprecationWarning, stacklevel=2) break except ImportError: pass if not fn: raise ImproperlyConfigured, '%s is not a valid extension for %s' % ( ext, cls.__name__) # Not a string, maybe a callable? elif hasattr(ext, '__call__'): fn = ext # Take our chances and just try to access "register" else: fn = ext.register cls.register_extension(fn) cls._feincms_extensions.add(ext)
def test_get_object(self): from feincms.utils import get_object self.assertRaises(AttributeError, lambda: get_object('feincms.does_not_exist')) self.assertRaises(ImportError, lambda: get_object('feincms.does_not_exist.fn')) self.assertEqual(get_object, get_object('feincms.utils.get_object'))
def initialize_type(cls, cleanse=False): if cleanse: # If cleanse is True use default cleanse method if cleanse == True: import warnings warnings.warn("Please pass a callable instead. cleanse=True is" " being deprecated in favor of explicitly specifying the" " cleansing function. To continue using the same" " functionality, pip install feincms-cleanse and pass" " cleanse=feincms_cleanse.cleanse_html to the" " create_content_type call." " Support for cleanse=True will be removed in FeinCMS v1.8.", DeprecationWarning, stacklevel=2) from feincms.utils.html.cleanse import cleanse_html cls.cleanse = cleanse_html # Otherwise use passed callable else: cls.cleanse = cleanse # TODO: Move this into somewhere more generic: if settings.FEINCMS_TIDY_HTML: # Make sure we can load the tidy function without dependency failures: try: get_object(settings.FEINCMS_TIDY_FUNCTION) except ImportError, e: raise ImproperlyConfigured("FEINCMS_TIDY_HTML is enabled but the HTML tidy function %s could not be imported: %s" % (settings.FEINCMS_TIDY_FUNCTION, e))
def test_get_object(self): self.assertRaises(AttributeError, lambda: get_object('feincms.does_not_exist')) self.assertRaises(ImportError, lambda: get_object('feincms.does_not_exist.fn')) self.assertEqual(get_object, get_object('feincms.utils.get_object'))
def initialize_type(cls): # TODO: Move this into somewhere more generic: if settings.FEINCMS_TIDY_HTML: # Make sure we can load the tidy function without dependency failures: try: get_object(settings.FEINCMS_TIDY_FUNCTION) except ImportError, e: raise ImproperlyConfigured("FEINCMS_TIDY_HTML is enabled but the HTML tidy function %s could not be imported: %s" % (settings.FEINCMS_TIDY_FUNCTION, e))
def register_extensions(cls, *extensions): """ Register all extensions passed as arguments. Extensions should be specified as a string to the python module containing the extension. If it is a bundled extension of FeinCMS, you do not need to specify the full python module path -- only specifying the last part (f.e. ``'seo'`` or ``'translations'``) is sufficient. """ if not hasattr(cls, '_feincms_extensions'): cls._feincms_extensions = set() here = cls.__module__.split('.')[:-1] paths = [ '.'.join(here + ['extensions']), '.'.join(here[:-1] + ['extensions']), 'feincms.module.extensions', ] for ext in extensions: if ext in cls._feincms_extensions: continue fn = None if isinstance(ext, basestring): try: fn = get_object(ext + '.register') except ImportError: for path in paths: try: fn = get_object('%s.%s.register' % (path, ext)) if fn: break except ImportError: pass if not fn: raise ImproperlyConfigured, '%s is not a valid extension for %s' % ( ext, cls.__name__) # Not a string, maybe a callable? elif hasattr(ext, '__call__'): fn = ext # Take our chances and just try to access "register" else: fn = ext.register cls.register_extension(fn) cls._feincms_extensions.add(ext)
def initialize_type(cls, cleanse=False): cls.cleanse = cleanse # TODO: Move this into somewhere more generic: if settings.FEINCMS_TIDY_HTML: # Make sure we can load the tidy function without dependency failures: try: get_object(settings.FEINCMS_TIDY_FUNCTION) except ImportError, e: raise ImproperlyConfigured( "FEINCMS_TIDY_HTML is enabled but the HTML tidy function %s could not be imported: %s" % (settings.FEINCMS_TIDY_FUNCTION, e))
def initialize_type(cls, cleanse=False, tinymce_config=None): cls.cleanse = cleanse if tinymce_config is not None: cls.feincms_item_editor_includes['head'] = [tinymce_config] # TODO: Move this into somewhere more generic: if settings.FEINCMS_TIDY_HTML: # Make sure we can load the tidy function without dependency failures: try: get_object(settings.FEINCMS_TIDY_FUNCTION) except ImportError, e: raise ImproperlyConfigured("FEINCMS_TIDY_HTML is enabled but the HTML tidy function %s could not be imported: %s" % (settings.FEINCMS_TIDY_FUNCTION, e))
def register_extensions(cls, *extensions): """ Register all extensions passed as arguments. Extensions should be specified as a string to the python module containing the extension. If it is a bundled extension of FeinCMS, you do not need to specify the full python module path -- only specifying the last part (f.e. ``'seo'`` or ``'translations'``) is sufficient. """ if not hasattr(cls, '_feincms_extensions'): cls._feincms_extensions = set() here = cls.__module__.split('.')[:-1] paths = [ '.'.join(here + ['extensions']), '.'.join(here[:-1] + ['extensions']), 'feincms.module.extensions', ] for ext in extensions: if ext in cls._feincms_extensions: continue fn = None if isinstance(ext, basestring): try: fn = get_object(ext + '.register') except ImportError: for path in paths: try: fn = get_object('%s.%s.register' % (path, ext)) if fn: break except ImportError, e: pass if not fn: raise ImproperlyConfigured, '%s is not a valid extension for %s' % ( ext, cls.__name__) # Not a string, so take our chances and just try to access "register" else: fn = ext.register cls.register_extension(fn) cls._feincms_extensions.add(ext)
def register_extensions(cls, *extensions): if not hasattr(cls, '_feincms_extensions'): cls._feincms_extensions = set() for ext in extensions: if ext in cls._feincms_extensions: continue try: fn = get_object(ext + '.register') except ImportError: fn = get_object('feincms.module.page.extensions.%s.register' % ext) fn(cls, PageAdmin) cls._feincms_extensions.add(ext)
def clean(self): cleaned_data = super(RichTextContentAdminForm, self).clean() if settings.FEINCMS_TIDY_HTML: text, errors, warnings = get_object(settings.FEINCMS_TIDY_FUNCTION)(cleaned_data['text']) # Ick, but we need to be able to update text and seen_tidy_warnings: self.data = self.data.copy() # We always replace the HTML with the tidied version: cleaned_data['text'] = text self.data['%s-text' % self.prefix] = text if settings.FEINCMS_TIDY_SHOW_WARNINGS and (errors or warnings): if settings.FEINCMS_TIDY_ALLOW_WARNINGS_OVERRIDE: # Convert the ignore input from hidden to Checkbox so the user can change it: self.fields['seen_tidy_warnings'].widget = forms.CheckboxInput() if errors or not (settings.FEINCMS_TIDY_ALLOW_WARNINGS_OVERRIDE and cleaned_data['seen_tidy_warnings']): self._errors["text"] = ErrorList([mark_safe( _("HTML validation produced %(count)d warnings. Please review the updated content below before continuing: %(messages)s") % { "count": len(warnings) + len(errors), "messages": '<ul><li>%s</li></ul>' % "</li><li>".join(map(escape, errors + warnings)) } )]) # If we're allowed to ignore warnings and we don't have any # errors we'll set our hidden form field to allow the user to # ignore warnings on the next submit: if not errors and settings.FEINCMS_TIDY_ALLOW_WARNINGS_OVERRIDE: self.data["%s-seen_tidy_warnings" % self.prefix] = True return cleaned_data
def clean(self, value, model_instance): value = super(HTMLField, self).clean(value, model_instance) if settings.FEINCMS_TIDY_HTML: value, errors, warnings = get_object(settings.FEINCMS_TIDY_FUNCTION)(value ) return value
def initialize_type(cls, cleanse=None): def to_instance_method(func): def func_im(self, *args, **kwargs): return func(*args, **kwargs) return func_im if cleanse: cls.cleanse = to_instance_method(cleanse) # TODO: Move this into somewhere more generic: if settings.FEINCMS_TIDY_HTML: # Make sure we can load the tidy function without dependency failures: try: get_object(settings.FEINCMS_TIDY_FUNCTION) except ImportError as e: raise ImproperlyConfigured("FEINCMS_TIDY_HTML is enabled but the HTML tidy function %s could not be imported: %s" % (settings.FEINCMS_TIDY_FUNCTION, e))
def save_content(request): """ content save handler Returns a HttpResponse whose content is JSON to tell if the operation succeeded. """ result = {"result": False} if request.method == "POST": if request.POST["content"]: page_items = loads(request.POST["content"]) for content_key, item in page_items.iteritems(): # TODO: move to model/form cleaning content = item["value"] if settings.FEINCMS_TIDY_HTML: content, errors, warnings = get_object(settings.FEINCMS_TIDY_FUNCTION)(content) matches = re.search("^page-page-richtextcontent-(\d+)-(\d+)$", content_key) if matches: page_id, content_id = matches.group(1), matches.group(2) # TODO: replace with more flexible solution (not tied to the RichTextContent model), as done in _frontend_editing_view RTC = Page.content_type_for(RichTextContent) rtc = RTC.objects.get(id=content_id, parent__id=page_id) rtc.text = content rtc.save() # TODO: this should be done differently; being able to handle every page-item separartly (see formsets) result = {"result": True} return HttpResponse(dumps(result), content_type="application/json")
def __init__(self, *args, **kwargs): super(ApplicationContentItemEditorForm, self).__init__( *args, **kwargs) instance = kwargs.get("instance", None) if instance: try: # TODO use urlconf_path from POST if set # urlconf_path = request.POST.get('...urlconf_path', # instance.urlconf_path) self.app_config = cls.ALL_APPS_CONFIG[ instance.urlconf_path]['config'] except KeyError: self.app_config = {} self.custom_fields = {} admin_fields = self.app_config.get('admin_fields', {}) if isinstance(admin_fields, dict): self.custom_fields.update(admin_fields) else: get_fields = get_object(admin_fields) self.custom_fields.update( get_fields(self, *args, **kwargs)) params = self.instance.parameters for k, v in self.custom_fields.items(): v.initial = params.get(k) self.fields[k] = v if k in params: self.fields[k].initial = params[k]
def initialize_type(cls, cleanse=False): if cleanse: # If cleanse is True use default cleanse method if cleanse == True: from feincms.utils.html.cleanse import cleanse_html cls.cleanse = cleanse_html # Otherwise use passed callable else: cls.cleanse = cleanse # TODO: Move this into somewhere more generic: if settings.FEINCMS_TIDY_HTML: # Make sure we can load the tidy function without dependency failures: try: get_object(settings.FEINCMS_TIDY_FUNCTION) except ImportError, e: raise ImproperlyConfigured("FEINCMS_TIDY_HTML is enabled but the HTML tidy function %s could not be imported: %s" % (settings.FEINCMS_TIDY_FUNCTION, e))
def register_extensions(cls, *extensions): """ Register all extensions passed as arguments. Extensions should be specified as a string to the python module containing the extension. If it is a bundled extension of FeinCMS, you do not need to specify the full python module path -- only specifying the last part (f.e. ``'seo'`` or ``'translations'``) is sufficient. """ if not hasattr(cls, '_extensions'): cls._extensions = [] cls._extensions_seen = [] for ext in extensions: if ext in cls._extensions: continue extension = None if isinstance(ext, six.string_types): try: extension = get_object(ext) except (AttributeError, ImportError, ValueError): if not extension: raise ImproperlyConfigured( '%s is not a valid extension for %s' % ( ext, cls.__name__)) if hasattr(extension, 'Extension'): extension = extension.Extension elif hasattr(extension, 'register'): extension = extension.register elif hasattr(extension, '__call__'): pass else: raise ImproperlyConfigured( '%s is not a valid extension for %s' % ( ext, cls.__name__)) if extension in cls._extensions_seen: continue cls._extensions_seen.append(extension) if hasattr(extension, 'handle_model'): cls._extensions.append(extension(cls)) else: warnings.warn( '%r is a extension in legacy format.' ' Support for legacy extensions will be removed in' ' FeinCMS v1.9. Convert your extensions to' ' feincms.extensions.Extension now.' % extension, DeprecationWarning) cls._extensions.append(LegacyExtension(cls, extension=extension))
def extended_navigation(self, **kwargs): if not self.navigation_extension: return self.children.in_navigation() cls = get_object(self.navigation_extension, fail_silently=True) if not cls or not callable(cls): return self.children.in_navigation() return cls().children(self, **kwargs)
def register_extensions(cls, *extensions): """ Register all extensions passed as arguments. Extensions should be specified as a string to the python module containing the extension. If it is a bundled extension of FeinCMS, you do not need to specify the full python module path -- only specifying the last part (f.e. ``'seo'`` or ``'translations'``) is sufficient. """ if not hasattr(cls, '_extensions'): cls._extensions = [] cls._extensions_seen = [] for ext in extensions: if ext in cls._extensions: continue extension = None if inspect.isclass(ext) and issubclass(ext, Extension): extension = ext elif isinstance(ext, six.string_types): try: extension = get_object(ext) except (AttributeError, ImportError, ValueError): if not extension: raise ImproperlyConfigured( '%s is not a valid extension for %s' % ( ext, cls.__name__)) if hasattr(extension, 'Extension'): extension = extension.Extension elif hasattr(extension, 'register'): extension = extension.register elif hasattr(extension, '__call__'): pass else: raise ImproperlyConfigured( '%s is not a valid extension for %s' % ( ext, cls.__name__)) if extension in cls._extensions_seen: continue cls._extensions_seen.append(extension) if hasattr(extension, 'handle_model'): cls._extensions.append(extension(cls)) else: raise ImproperlyConfigured( '%r is an invalid extension.' % extension)
def register_extensions(cls, *extensions): """ Register all extensions passed as arguments. Extensions should be specified as a string to the python module containing the extension. If it is a bundled extension of FeinCMS, you do not need to specify the full python module path -- only specifying the last part (f.e. ``'seo'`` or ``'translations'``) is sufficient. """ if not hasattr(cls, "_extensions"): cls._extensions = [] cls._extensions_seen = [] for ext in extensions: if ext in cls._extensions: continue extension = None if inspect.isclass(ext) and issubclass(ext, Extension): extension = ext elif isinstance(ext, six.string_types): try: extension = get_object(ext) except (AttributeError, ImportError, ValueError): if not extension: raise ImproperlyConfigured( "%s is not a valid extension for %s" % (ext, cls.__name__)) if hasattr(extension, "Extension"): extension = extension.Extension elif hasattr(extension, "register"): extension = extension.register elif hasattr(extension, "__call__"): pass else: raise ImproperlyConfigured( "%s is not a valid extension for %s" % (ext, cls.__name__)) if extension in cls._extensions_seen: continue cls._extensions_seen.append(extension) if hasattr(extension, "handle_model"): cls._extensions.append(extension(cls)) else: raise ImproperlyConfigured("%r is an invalid extension." % extension)
def register_extensions(cls, *extensions): if not hasattr(cls, '_feincms_extensions'): cls._feincms_extensions = set() for ext in extensions: if ext in cls._feincms_extensions: continue fn = get_object('feincms.module.blog.extensions.%s.register' % ext) fn(cls, EntryAdmin) cls._feincms_extensions.add(ext)
def initialize_type(cls, cleanse=None): def to_instance_method(func): def func_im(self, *args, **kwargs): return func(*args, **kwargs) return func_im if cleanse: cls.cleanse = to_instance_method(cleanse) # TODO: Move this into somewhere more generic: if settings.FEINCMS_TIDY_HTML: # Make sure we can load the tidy function without dependency # failures: try: get_object(settings.FEINCMS_TIDY_FUNCTION) except ImportError as e: raise ImproperlyConfigured( "FEINCMS_TIDY_HTML is enabled but the HTML tidy function" " %s could not be imported: %s" % ( settings.FEINCMS_TIDY_FUNCTION, e))
def oembed_provider(self, url, kwargs): """ Helper method returning the oEmbed provider function """ if not self._oembed_provider_fn: self._oembed_provider_fn = get_object(getattr(settings, 'OEMBED_PROVIDER', 'feincms_oembed.providers.embedly_oembed_provider', )) return self._oembed_provider_fn(url, kwargs)
def register_extensions(cls, *extensions): if not hasattr(cls, '_feincms_extensions'): cls._feincms_extensions = set() here = cls.__module__.split('.')[:-1] here_path = '.'.join(here + ['extensions']) common_path = '.'.join(here[:-1] + ['extensions']) for ext in extensions: if ext in cls._feincms_extensions: continue try: fn = get_object(ext + '.register') except ImportError: try: fn = get_object('%s.%s.register' % ( here_path, ext ) ) except ImportError: fn = get_object('%s.%s.register' % ( common_path, ext ) ) cls.register_extension(fn) cls._feincms_extensions.add(ext)
def initialize_type(cls, cleanse=False): def to_instance_method(func): def func_im(self, *args, **kwargs): return func(*args, **kwargs) return func_im if cleanse: # If cleanse is True use default cleanse method if cleanse == True: import warnings warnings.warn( "Please pass a callable instead. cleanse=True is" " being deprecated in favor of explicitly specifying the" " cleansing function. To continue using the same" " functionality, pip install feincms-cleanse and pass" " cleanse=feincms_cleanse.cleanse_html to the" " create_content_type call." " Support for cleanse=True will be removed in FeinCMS v1.8.", DeprecationWarning, stacklevel=2) from feincms.utils.html.cleanse import cleanse_html cls.cleanse = to_instance_method(cleanse_html) # Otherwise use passed callable else: cls.cleanse = to_instance_method(cleanse) # TODO: Move this into somewhere more generic: if settings.FEINCMS_TIDY_HTML: # Make sure we can load the tidy function without dependency failures: try: get_object(settings.FEINCMS_TIDY_FUNCTION) except ImportError, e: raise ImproperlyConfigured( "FEINCMS_TIDY_HTML is enabled but the HTML tidy function %s could not be imported: %s" % (settings.FEINCMS_TIDY_FUNCTION, e))
def extended_navigation(self, **kwargs): if not self.navigation_extension: return self.children.in_navigation() cls = None try: cls = extension._extensions[self.navigation_extension] except KeyError: cls = get_object(self.navigation_extension, fail_silently=True) extension._extensions[self.navigation_extension] = cls if cls: return cls().children(self, **kwargs) return self.children.in_navigation()
def register_extensions(cls, *extensions): """ Register all extensions passed as arguments. Extensions should be specified as a string to the python module containing the extension. If it is a bundled extension of FeinCMS, you do not need to specify the full python module path -- only specifying the last part (f.e. ``'seo'`` or ``'translations'``) is sufficient. """ if not hasattr(cls, '_feincms_extensions'): cls._feincms_extensions = set() here = cls.__module__.split('.')[:-1] here_path = '.'.join(here + ['extensions']) common_path = '.'.join(here[:-1] + ['extensions']) for ext in extensions: if ext in cls._feincms_extensions: continue if isinstance(ext, basestring): try: fn = get_object(ext + '.register') except ImportError: try: fn = get_object('%s.%s.register' % ( here_path, ext ) ) except ImportError: fn = get_object('%s.%s.register' % ( common_path, ext ) ) # Not a string, so take our chances and just try to access "register" else: fn = ext.register cls.register_extension(fn) cls._feincms_extensions.add(ext)
def __init__(self, *args, **kwargs): super(ApplicationContentItemEditorForm, self).__init__(*args, **kwargs) instance = kwargs.get("instance", None) if instance: try: self.app_config = cls.ALL_APPS_CONFIG[instance.urlconf_path]['config'] except KeyError: self.app_config = {} self.custom_fields = {} admin_fields = self.app_config.get('admin_fields', {}) if isinstance(admin_fields, dict): self.custom_fields.update(admin_fields) else: get_fields = get_object(admin_fields) self.custom_fields.update(get_fields(self, *args, **kwargs)) for k, v in self.custom_fields.items(): self.fields[k] = v
def test_get_object(self): self.assertRaises(AttributeError, lambda: get_object("feincms.does_not_exist")) self.assertRaises(ImportError, lambda: get_object("feincms.does_not_exist.fn")) self.assertEqual(get_object, get_object("feincms.utils.get_object"))
def process(self, request, **kw): page_url = self.parent.get_absolute_url() # Provide a way for appcontent items to customize URL processing by # altering the perceived path of the page: if "path_mapper" in self.app_config: path_mapper = get_object(self.app_config["path_mapper"]) path, page_url = path_mapper(request.path, page_url, appcontent_parameters=self.parameters) else: path = request._feincms_extra_context['extra_path'] # Resolve the module holding the application urls. urlconf_path = self.app_config.get('urls', self.urlconf_path) try: fn, args, kwargs = resolve(path, urlconf_path) except (ValueError, Resolver404): raise Resolver404( str('Not found (resolving %r in %r failed)') % (path, urlconf_path)) # Variables from the ApplicationContent parameters are added to request # so we can expose them to our templates via the appcontent_parameters # context_processor request._feincms_extra_context.update(self.parameters) # Save the application configuration for reuse elsewhere request._feincms_extra_context.update({ 'app_config': dict( self.app_config, urlconf_path=self.urlconf_path, ), }) view_wrapper = self.app_config.get("view_wrapper", None) if view_wrapper: fn = partial(get_object(view_wrapper), view=fn, appcontent_parameters=self.parameters) output = fn(request, *args, **kwargs) if isinstance(output, HttpResponse): if self.send_directly(request, output): return output elif output.status_code == 200: # If the response supports deferred rendering, render the # response right now. We do not handle template response # middleware. if hasattr(output, 'render') and callable(output.render): output.render() self.rendered_result = mark_safe( output.content.decode('utf-8')) self.rendered_headers = {} # Copy relevant headers for later perusal for h in ('Cache-Control', 'Last-Modified', 'Expires'): if h in output: self.rendered_headers.setdefault(h, []).append(output[h]) elif isinstance(output, tuple) and 'view' in kw: kw['view'].template_name = output[0] kw['view'].request._feincms_extra_context.update(output[1]) else: self.rendered_result = mark_safe(output) return True # successful
def process(self, request, **kw): page_url = self.parent.get_absolute_url() if "path_mapper" in self.app_config: path_mapper = get_object(self.app_config["path_mapper"]) path, page_url = path_mapper( request.path, page_url, appcontent_parameters=self.parameters ) else: path = request._feincms_extra_context['extra_path'] # Resolve the module holding the application urls. urlconf_path = self.app_config.get('urls', self.urlconf_path) try: fn, args, kwargs = resolve(path, urlconf_path) except (ValueError, Resolver404): raise Resolver404(str('Not found (resolving %r in %r failed)') % ( path, urlconf_path)) # Variables from the ApplicationContent parameters are added to request # so we can expose them to our templates via the appcontent_parameters # context_processor request._feincms_extra_context.update(self.parameters) request._feincms_extra_context.update({'widget': self}) # Save the application configuration for reuse elsewhere request._feincms_extra_context.update({ 'app_config': dict( self.app_config, urlconf_path=self.urlconf_path, ), }) view_wrapper = self.app_config.get("view_wrapper", None) if view_wrapper: fn = partial( get_object(view_wrapper), view=fn, appcontent_parameters=self.parameters ) output = fn(request, *args, **kwargs) # handle django rest framework as external application if hasattr(output, 'renderer_context'): output.context_data = output.renderer_context output.standalone = True if isinstance(output, HttpResponse): # update context if hasattr(output, 'context_data'): output.context_data['widget'] = self else: output.context_data = {'widget': self} if self.send_directly(request, output): return output elif output.status_code == 200: if self.unpack(request, output) and 'view' in kw: # Handling of @unpack and UnpackTemplateResponse kw['view'].template_name = output.template_name kw['view'].request._feincms_extra_context.update( output.context_data) else: # If the response supports deferred rendering, render the # response right now. We do not handle template response # middleware. if hasattr(output, 'render') and callable(output.render): output.render() self.rendered_result = mark_safe( output.content.decode('utf-8')) self.rendered_headers = {} # Copy relevant headers for later perusal for h in ('Cache-Control', 'Last-Modified', 'Expires'): if h in output: self.rendered_headers.setdefault( h, []).append(output[h]) elif isinstance(output, tuple) and 'view' in kw: kw['view'].template_name = output[0] kw['view'].request._feincms_extra_context.update(output[1]) # our hack # no template and view change and save content for our widget context = output[1] context['widget'] = self self.rendered_result = render_to_string( output[0], RequestContext(request, context)) else: self.rendered_result = mark_safe(output) # here is the magic ! # return renderered parent template ! context = RequestContext(request, {}) return render_to_response( self.parent.theme.template, context )
def _register_handler(self, handler): handler = get_object(handler) # parse strings if not hasattr(handler, '__call__'): raise AttributeError('Handler %s has no method "__call__". Needs one.' % handler) self.handlers.append(handler)
def register_extensions(cls, *extensions): """ Register all extensions passed as arguments. Extensions should be specified as a string to the python module containing the extension. If it is a bundled extension of FeinCMS, you do not need to specify the full python module path -- only specifying the last part (f.e. ``'seo'`` or ``'translations'``) is sufficient. """ if not hasattr(cls, '_extensions'): cls._extensions = [] cls._extensions_seen = [] here = cls.__module__.split('.')[:-1] search_paths = [ '.'.join(here + ['extensions']), '.'.join(here[:-1] + ['extensions']), 'feincms.module.extensions', ] for ext in extensions: if ext in cls._extensions: continue extension = None if isinstance(ext, basestring): paths = [ext, '%s.register' % ext] for path in search_paths: paths.extend([ '%s.%s.register' % (path, ext), '%s.%s' % (path, ext), ]) for idx, path in enumerate(paths): try: extension = get_object(path) if idx >= 2: warnings.warn( 'Using short names for extensions has been' ' deprecated and will be removed in' ' FeinCMS v1.8. Please provide the full' ' python path to the extension' ' %s instead (%s).' % ( ext, re.sub(r'\.register$', '', path), ), DeprecationWarning, stacklevel=2) break except (AttributeError, ImportError, ValueError): pass if not extension: raise ImproperlyConfigured( '%s is not a valid extension for %s' % ( ext, cls.__name__)) if hasattr(extension, 'Extension'): extension = extension.Extension elif hasattr(extension, 'register'): extension = extension.register elif hasattr(extension, '__call__'): pass else: raise ImproperlyConfigured( '%s is not a valid extension for %s' % ( ext, cls.__name__)) if extension in cls._extensions_seen: continue cls._extensions_seen.append(extension) if hasattr(extension, 'handle_model'): cls._extensions.append(extension(cls)) else: cls._extensions.append(LegacyExtension(cls, extension=extension))
def warn(self, *args, **kwargs): self.log(level=self.WARN, *args, **kwargs) def err(self, *args, **kwargs): self.log(level=self.ERR, *args, **kwargs) def do_log(self, subsys, level, *args): # Don't actually log anything. Override this in subclasses pass # ------------------------------------------------------------------------ class LogStdout(LogBase): """ Example logging class, logs to stdout. """ subsys = { LogBase.ANY: '*', LogBase.DB: '#', LogBase.CACHE: '@', LogBase.AUTH: '!' } def do_log(self, subsys, level, *args): from datetime import datetime now = datetime.now().isoformat() print 'LOG:', now, self.subsys[subsys], ', '.join(args) # ------------------------------------------------------------------------ # Instanciate the logger, yeah! logger = get_object(settings.FEINCMS_LOGGING_CLASS)() # ------------------------------------------------------------------------
def process(self, request, **kwargs): page_url = self.parent.get_absolute_url() # Get the rest of the URL # Provide a way for appcontent items to customize URL processing by # altering the perceived path of the page: if "path_mapper" in self.app_config: path_mapper = get_object(self.app_config["path_mapper"]) path, page_url = path_mapper( request.path, page_url, appcontent_parameters=self.parameters ) else: path = request._feincms_extra_context['extra_path'] # Resolve the module holding the application urls. urlconf_path = self.app_config.get('urls', self.urlconf_path) # Change the prefix and urlconf for the monkey-patched reverse function ... _local.urlconf = (urlconf_path, page_url) try: fn, args, kwargs = resolve(path, urlconf_path) except (ValueError, Resolver404): del _local.urlconf raise Resolver404 #: Variables from the ApplicationContent parameters are added to request # so we can expose them to our templates via the appcontent_parameters # context_processor request._feincms_extra_context.update(self.parameters) view_wrapper = self.app_config.get("view_wrapper", None) if view_wrapper: fn = partial( get_object(view_wrapper), view=fn, appcontent_parameters=self.parameters ) try: output = fn(request, *args, **kwargs) if isinstance(output, HttpResponse): if self.send_directly(request, output): return output elif output.status_code == 200: # If the response supports deferred rendering, render the # response right now. We do not handle template response # middleware. if hasattr(output, 'render') and callable(output.render): output.render() self.rendered_result = mark_safe(output.content.decode('utf-8')) self.rendered_headers = {} # Copy relevant headers for later perusal for h in ('Cache-Control', 'Last-Modified', 'Expires'): if h in output: self.rendered_headers.setdefault(h, []).append(output[h]) else: self.rendered_result = mark_safe(output) finally: # We want exceptions to propagate, but we cannot allow the # modifications to reverse() to stay here. del _local.urlconf return True # successful
def process(self, request, **kw): page_url = self.parent.get_absolute_url() # Provide a way for appcontent items to customize URL processing by # altering the perceived path of the page: if "path_mapper" in self.app_config: path_mapper = get_object(self.app_config["path_mapper"]) path, page_url = path_mapper( request.path, page_url, appcontent_parameters=self.parameters ) else: path = request._feincms_extra_context['extra_path'] # Resolve the module holding the application urls. urlconf_path = self.app_config.get('urls', self.urlconf_path) try: fn, args, kwargs = resolve(path, urlconf_path) except (ValueError, Resolver404): raise Resolver404('Not found (resolving %r in %r failed)' % ( path, urlconf_path)) # Variables from the ApplicationContent parameters are added to request # so we can expose them to our templates via the appcontent_parameters # context_processor request._feincms_extra_context.update(self.parameters) # Save the application configuration for reuse elsewhere request._feincms_extra_context.update({ 'app_config': dict( self.app_config, urlconf_path=self.urlconf_path, ), }) view_wrapper = self.app_config.get("view_wrapper", None) if view_wrapper: fn = partial( get_object(view_wrapper), view=fn, appcontent_parameters=self.parameters ) output = fn(request, *args, **kwargs) if isinstance(output, HttpResponse): if self.send_directly(request, output): return output elif output.status_code == 200: # If the response supports deferred rendering, render the # response right now. We do not handle template response # middleware. if hasattr(output, 'render') and callable(output.render): output.render() self.rendered_result = mark_safe( output.content.decode('utf-8')) self.rendered_headers = {} # Copy relevant headers for later perusal for h in ('Cache-Control', 'Last-Modified', 'Expires'): if h in output: self.rendered_headers.setdefault( h, []).append(output[h]) elif isinstance(output, tuple) and 'view' in kw: kw['view'].template_name = output[0] kw['view'].request._feincms_extra_context.update(output[1]) else: self.rendered_result = mark_safe(output) return True # successful
class UpcomingContent(models.Model): class Meta: abstract = True verbose_name = _("upcoming") def render(self, **kwargs): ctx = {'events': get_upcoming_events(kwargs['user'])} ctx.update(kwargs) return render_to_string("upcoming.html", ctx) Page.create_content_type(UpcomingContent, regions=("special",)) Page.create_content_type( get_object("feincms.content.richtext.models.RichTextContent"), regions=common_regions) from feincms.content.medialibrary.models import MediaFileContent Page.create_content_type(MediaFileContent, TYPE_CHOICES=( ('default', _('Default')), ('left', _('Left')), ('right', _('Right')), ('download', _('Download')), ), regions=common_regions ) from feincms.content.rss.models import RSSContent Page.create_content_type(RSSContent, regions=common_regions)
def register_extensions(cls, *extensions): """ Register all extensions passed as arguments. Extensions should be specified as a string to the python module containing the extension. If it is a bundled extension of FeinCMS, you do not need to specify the full python module path -- only specifying the last part (f.e. ``'seo'`` or ``'translations'``) is sufficient. """ if not hasattr(cls, '_extensions'): cls._extensions = [] cls._extensions_seen = [] here = cls.__module__.split('.')[:-1] search_paths = [ '.'.join(here + ['extensions']), '.'.join(here[:-1] + ['extensions']), 'feincms.module.extensions', ] for ext in extensions: if ext in cls._extensions: continue extension = None if isinstance(ext, basestring): paths = [ext, '%s.register' % ext] for path in search_paths: paths.extend([ '%s.%s.register' % (path, ext), '%s.%s' % (path, ext), ]) for idx, path in enumerate(paths): try: extension = get_object(path) if idx >= 2: warnings.warn( 'Using short names for extensions has been' ' deprecated and will be removed in' ' FeinCMS v1.8. Please provide the full' ' python path to the extension' ' %s instead (%s).' % ( ext, re.sub(r'\.register$', '', path), ), DeprecationWarning, stacklevel=2) break except (AttributeError, ImportError, ValueError): pass if not extension: raise ImproperlyConfigured( '%s is not a valid extension for %s' % (ext, cls.__name__)) if hasattr(extension, 'Extension'): extension = extension.Extension elif hasattr(extension, 'register'): extension = extension.register elif hasattr(extension, '__call__'): pass else: raise ImproperlyConfigured( '%s is not a valid extension for %s' % (ext, cls.__name__)) if extension in cls._extensions_seen: continue cls._extensions_seen.append(extension) if hasattr(extension, 'handle_model'): cls._extensions.append(extension(cls)) else: cls._extensions.append( LegacyExtension(cls, extension=extension))
def get_extension_class(extension): extension = get_object(extension) if isinstance(extension, types.ModuleType): return getattr(extension, 'Extension') return extension
def admin_thumbnail(mediafile, dimensions='100x100'): global _cached_thumbnailer if not _cached_thumbnailer: _cached_thumbnailer = get_object( settings.FEINCMS_MEDIALIBRARY_THUMBNAIL) return _cached_thumbnailer(mediafile, dimensions=dimensions)