repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
sequencelengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
sequencelengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
django-fluent/django-fluent-contents
fluent_contents/models/managers.py
ContentItemQuerySet.parent
def parent(self, parent_object, limit_parent_language=True): """ Return all content items which are associated with a given parent object. """ lookup = get_parent_lookup_kwargs(parent_object) # Filter the items by default, giving the expected "objects for this parent" items # when the parent already holds the language state. if limit_parent_language: language_code = get_parent_language_code(parent_object) if language_code: lookup['language_code'] = language_code return self.filter(**lookup)
python
def parent(self, parent_object, limit_parent_language=True): """ Return all content items which are associated with a given parent object. """ lookup = get_parent_lookup_kwargs(parent_object) # Filter the items by default, giving the expected "objects for this parent" items # when the parent already holds the language state. if limit_parent_language: language_code = get_parent_language_code(parent_object) if language_code: lookup['language_code'] = language_code return self.filter(**lookup)
[ "def", "parent", "(", "self", ",", "parent_object", ",", "limit_parent_language", "=", "True", ")", ":", "lookup", "=", "get_parent_lookup_kwargs", "(", "parent_object", ")", "# Filter the items by default, giving the expected \"objects for this parent\" items", "# when the parent already holds the language state.", "if", "limit_parent_language", ":", "language_code", "=", "get_parent_language_code", "(", "parent_object", ")", "if", "language_code", ":", "lookup", "[", "'language_code'", "]", "=", "language_code", "return", "self", ".", "filter", "(", "*", "*", "lookup", ")" ]
Return all content items which are associated with a given parent object.
[ "Return", "all", "content", "items", "which", "are", "associated", "with", "a", "given", "parent", "object", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/models/managers.py#L80-L93
django-fluent/django-fluent-contents
fluent_contents/models/managers.py
ContentItemQuerySet.move_to_placeholder
def move_to_placeholder(self, placeholder, sort_order=None): """ .. versionadded: 1.0.2 Move the entire queryset to a new object. Returns a queryset with the newly created objects. """ qs = self.all() # Get clone for item in qs: # Change the item directly in the resultset. item.move_to_placeholder(placeholder, sort_order=sort_order) if sort_order is not None: sort_order += 1 return qs
python
def move_to_placeholder(self, placeholder, sort_order=None): """ .. versionadded: 1.0.2 Move the entire queryset to a new object. Returns a queryset with the newly created objects. """ qs = self.all() # Get clone for item in qs: # Change the item directly in the resultset. item.move_to_placeholder(placeholder, sort_order=sort_order) if sort_order is not None: sort_order += 1 return qs
[ "def", "move_to_placeholder", "(", "self", ",", "placeholder", ",", "sort_order", "=", "None", ")", ":", "qs", "=", "self", ".", "all", "(", ")", "# Get clone", "for", "item", "in", "qs", ":", "# Change the item directly in the resultset.", "item", ".", "move_to_placeholder", "(", "placeholder", ",", "sort_order", "=", "sort_order", ")", "if", "sort_order", "is", "not", "None", ":", "sort_order", "+=", "1", "return", "qs" ]
.. versionadded: 1.0.2 Move the entire queryset to a new object. Returns a queryset with the newly created objects.
[ "..", "versionadded", ":", "1", ".", "0", ".", "2", "Move", "the", "entire", "queryset", "to", "a", "new", "object", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/models/managers.py#L107-L120
django-fluent/django-fluent-contents
fluent_contents/models/managers.py
ContentItemQuerySet.copy_to_placeholder
def copy_to_placeholder(self, placeholder, sort_order=None): """ .. versionadded: 1.0 Copy the entire queryset to a new object. Returns a queryset with the newly created objects. """ qs = self.all() # Get clone for item in qs: # Change the item directly in the resultset. item.copy_to_placeholder(placeholder, sort_order=sort_order, in_place=True) if sort_order is not None: sort_order += 1 return qs
python
def copy_to_placeholder(self, placeholder, sort_order=None): """ .. versionadded: 1.0 Copy the entire queryset to a new object. Returns a queryset with the newly created objects. """ qs = self.all() # Get clone for item in qs: # Change the item directly in the resultset. item.copy_to_placeholder(placeholder, sort_order=sort_order, in_place=True) if sort_order is not None: sort_order += 1 return qs
[ "def", "copy_to_placeholder", "(", "self", ",", "placeholder", ",", "sort_order", "=", "None", ")", ":", "qs", "=", "self", ".", "all", "(", ")", "# Get clone", "for", "item", "in", "qs", ":", "# Change the item directly in the resultset.", "item", ".", "copy_to_placeholder", "(", "placeholder", ",", "sort_order", "=", "sort_order", ",", "in_place", "=", "True", ")", "if", "sort_order", "is", "not", "None", ":", "sort_order", "+=", "1", "return", "qs" ]
.. versionadded: 1.0 Copy the entire queryset to a new object. Returns a queryset with the newly created objects.
[ "..", "versionadded", ":", "1", ".", "0", "Copy", "the", "entire", "queryset", "to", "a", "new", "object", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/models/managers.py#L124-L137
django-fluent/django-fluent-contents
fluent_contents/models/managers.py
ContentItemManager.parent
def parent(self, parent_object, limit_parent_language=True): """ Return all content items which are associated with a given parent object. """ return self.all().parent(parent_object, limit_parent_language)
python
def parent(self, parent_object, limit_parent_language=True): """ Return all content items which are associated with a given parent object. """ return self.all().parent(parent_object, limit_parent_language)
[ "def", "parent", "(", "self", ",", "parent_object", ",", "limit_parent_language", "=", "True", ")", ":", "return", "self", ".", "all", "(", ")", ".", "parent", "(", "parent_object", ",", "limit_parent_language", ")" ]
Return all content items which are associated with a given parent object.
[ "Return", "all", "content", "items", "which", "are", "associated", "with", "a", "given", "parent", "object", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/models/managers.py#L158-L162
django-fluent/django-fluent-contents
fluent_contents/models/managers.py
ContentItemManager.create_for_placeholder
def create_for_placeholder(self, placeholder, sort_order=1, language_code=None, **kwargs): """ Create a Content Item with the given parameters If the language_code is not provided, the language code of the parent will be used. This may perform an additional database query, unless the :class:`~fluent_contents.models.managers.PlaceholderManager` methods were used to construct the object, such as :func:`~fluent_contents.models.managers.PlaceholderManager.create_for_object` or :func:`~fluent_contents.models.managers.PlaceholderManager.get_by_slot` """ if language_code is None: # Could also use get_language() or appsettings.FLUENT_CONTENTS_DEFAULT_LANGUAGE_CODE # thus avoid the risk of performing an extra query here to the parent. # However, this identical behavior to BaseContentItemFormSet, # and the parent can be set already via Placeholder.objects.create_for_object() language_code = get_parent_language_code(placeholder.parent) obj = self.create( placeholder=placeholder, parent_type_id=placeholder.parent_type_id, parent_id=placeholder.parent_id, sort_order=sort_order, language_code=language_code, **kwargs ) # Fill the reverse caches obj.placeholder = placeholder parent = getattr(placeholder, '_parent_cache', None) # by GenericForeignKey (_meta.virtual_fields[0].cache_attr) if parent is not None: obj.parent = parent return obj
python
def create_for_placeholder(self, placeholder, sort_order=1, language_code=None, **kwargs): """ Create a Content Item with the given parameters If the language_code is not provided, the language code of the parent will be used. This may perform an additional database query, unless the :class:`~fluent_contents.models.managers.PlaceholderManager` methods were used to construct the object, such as :func:`~fluent_contents.models.managers.PlaceholderManager.create_for_object` or :func:`~fluent_contents.models.managers.PlaceholderManager.get_by_slot` """ if language_code is None: # Could also use get_language() or appsettings.FLUENT_CONTENTS_DEFAULT_LANGUAGE_CODE # thus avoid the risk of performing an extra query here to the parent. # However, this identical behavior to BaseContentItemFormSet, # and the parent can be set already via Placeholder.objects.create_for_object() language_code = get_parent_language_code(placeholder.parent) obj = self.create( placeholder=placeholder, parent_type_id=placeholder.parent_type_id, parent_id=placeholder.parent_id, sort_order=sort_order, language_code=language_code, **kwargs ) # Fill the reverse caches obj.placeholder = placeholder parent = getattr(placeholder, '_parent_cache', None) # by GenericForeignKey (_meta.virtual_fields[0].cache_attr) if parent is not None: obj.parent = parent return obj
[ "def", "create_for_placeholder", "(", "self", ",", "placeholder", ",", "sort_order", "=", "1", ",", "language_code", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "language_code", "is", "None", ":", "# Could also use get_language() or appsettings.FLUENT_CONTENTS_DEFAULT_LANGUAGE_CODE", "# thus avoid the risk of performing an extra query here to the parent.", "# However, this identical behavior to BaseContentItemFormSet,", "# and the parent can be set already via Placeholder.objects.create_for_object()", "language_code", "=", "get_parent_language_code", "(", "placeholder", ".", "parent", ")", "obj", "=", "self", ".", "create", "(", "placeholder", "=", "placeholder", ",", "parent_type_id", "=", "placeholder", ".", "parent_type_id", ",", "parent_id", "=", "placeholder", ".", "parent_id", ",", "sort_order", "=", "sort_order", ",", "language_code", "=", "language_code", ",", "*", "*", "kwargs", ")", "# Fill the reverse caches", "obj", ".", "placeholder", "=", "placeholder", "parent", "=", "getattr", "(", "placeholder", ",", "'_parent_cache'", ",", "None", ")", "# by GenericForeignKey (_meta.virtual_fields[0].cache_attr)", "if", "parent", "is", "not", "None", ":", "obj", ".", "parent", "=", "parent", "return", "obj" ]
Create a Content Item with the given parameters If the language_code is not provided, the language code of the parent will be used. This may perform an additional database query, unless the :class:`~fluent_contents.models.managers.PlaceholderManager` methods were used to construct the object, such as :func:`~fluent_contents.models.managers.PlaceholderManager.create_for_object` or :func:`~fluent_contents.models.managers.PlaceholderManager.get_by_slot`
[ "Create", "a", "Content", "Item", "with", "the", "given", "parameters" ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/models/managers.py#L164-L196
django-fluent/django-fluent-contents
fluent_contents/admin/placeholderfield.py
PlaceholderFieldAdmin.get_placeholder_data
def get_placeholder_data(self, request, obj=None): """ Return the data of the placeholder fields. """ # Return all placeholder fields in the model. if not hasattr(self.model, '_meta_placeholder_fields'): return [] data = [] for name, field in self.model._meta_placeholder_fields.items(): assert isinstance(field, PlaceholderField) data.append(PlaceholderData( slot=field.slot, title=field.verbose_name.capitalize(), fallback_language=None, # Information cant' be known by "render_placeholder" in the template. )) return data
python
def get_placeholder_data(self, request, obj=None): """ Return the data of the placeholder fields. """ # Return all placeholder fields in the model. if not hasattr(self.model, '_meta_placeholder_fields'): return [] data = [] for name, field in self.model._meta_placeholder_fields.items(): assert isinstance(field, PlaceholderField) data.append(PlaceholderData( slot=field.slot, title=field.verbose_name.capitalize(), fallback_language=None, # Information cant' be known by "render_placeholder" in the template. )) return data
[ "def", "get_placeholder_data", "(", "self", ",", "request", ",", "obj", "=", "None", ")", ":", "# Return all placeholder fields in the model.", "if", "not", "hasattr", "(", "self", ".", "model", ",", "'_meta_placeholder_fields'", ")", ":", "return", "[", "]", "data", "=", "[", "]", "for", "name", ",", "field", "in", "self", ".", "model", ".", "_meta_placeholder_fields", ".", "items", "(", ")", ":", "assert", "isinstance", "(", "field", ",", "PlaceholderField", ")", "data", ".", "append", "(", "PlaceholderData", "(", "slot", "=", "field", ".", "slot", ",", "title", "=", "field", ".", "verbose_name", ".", "capitalize", "(", ")", ",", "fallback_language", "=", "None", ",", "# Information cant' be known by \"render_placeholder\" in the template.", ")", ")", "return", "data" ]
Return the data of the placeholder fields.
[ "Return", "the", "data", "of", "the", "placeholder", "fields", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/admin/placeholderfield.py#L55-L72
django-fluent/django-fluent-contents
fluent_contents/admin/placeholderfield.py
PlaceholderFieldAdmin.get_all_allowed_plugins
def get_all_allowed_plugins(self): """ Return which plugins are allowed by the placeholder fields. """ # Get all allowed plugins of the various placeholders together. if not hasattr(self.model, '_meta_placeholder_fields'): # No placeholder fields in the model, no need for inlines. return [] plugins = [] for name, field in self.model._meta_placeholder_fields.items(): assert isinstance(field, PlaceholderField) if field.plugins is None: # no limitations, so all is allowed return extensions.plugin_pool.get_plugins() else: plugins += field.plugins return list(set(plugins))
python
def get_all_allowed_plugins(self): """ Return which plugins are allowed by the placeholder fields. """ # Get all allowed plugins of the various placeholders together. if not hasattr(self.model, '_meta_placeholder_fields'): # No placeholder fields in the model, no need for inlines. return [] plugins = [] for name, field in self.model._meta_placeholder_fields.items(): assert isinstance(field, PlaceholderField) if field.plugins is None: # no limitations, so all is allowed return extensions.plugin_pool.get_plugins() else: plugins += field.plugins return list(set(plugins))
[ "def", "get_all_allowed_plugins", "(", "self", ")", ":", "# Get all allowed plugins of the various placeholders together.", "if", "not", "hasattr", "(", "self", ".", "model", ",", "'_meta_placeholder_fields'", ")", ":", "# No placeholder fields in the model, no need for inlines.", "return", "[", "]", "plugins", "=", "[", "]", "for", "name", ",", "field", "in", "self", ".", "model", ".", "_meta_placeholder_fields", ".", "items", "(", ")", ":", "assert", "isinstance", "(", "field", ",", "PlaceholderField", ")", "if", "field", ".", "plugins", "is", "None", ":", "# no limitations, so all is allowed", "return", "extensions", ".", "plugin_pool", ".", "get_plugins", "(", ")", "else", ":", "plugins", "+=", "field", ".", "plugins", "return", "list", "(", "set", "(", "plugins", ")", ")" ]
Return which plugins are allowed by the placeholder fields.
[ "Return", "which", "plugins", "are", "allowed", "by", "the", "placeholder", "fields", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/admin/placeholderfield.py#L74-L92
django-fluent/django-fluent-contents
fluent_contents/plugins/markup/models.py
_create_markup_model
def _create_markup_model(fixed_language): """ Create a new MarkupItem model that saves itself in a single language. """ title = backend.LANGUAGE_NAMES.get(fixed_language) or fixed_language objects = MarkupLanguageManager(fixed_language) def save(self, *args, **kwargs): self.language = fixed_language MarkupItem.save(self, *args, **kwargs) class Meta: verbose_name = title verbose_name_plural = _('%s items') % title proxy = True classname = "{0}MarkupItem".format(fixed_language.capitalize()) new_class = type(str(classname), (MarkupItem,), { '__module__': MarkupItem.__module__, 'objects': objects, 'save': save, 'Meta': Meta, }) # Make easily browsable return new_class
python
def _create_markup_model(fixed_language): """ Create a new MarkupItem model that saves itself in a single language. """ title = backend.LANGUAGE_NAMES.get(fixed_language) or fixed_language objects = MarkupLanguageManager(fixed_language) def save(self, *args, **kwargs): self.language = fixed_language MarkupItem.save(self, *args, **kwargs) class Meta: verbose_name = title verbose_name_plural = _('%s items') % title proxy = True classname = "{0}MarkupItem".format(fixed_language.capitalize()) new_class = type(str(classname), (MarkupItem,), { '__module__': MarkupItem.__module__, 'objects': objects, 'save': save, 'Meta': Meta, }) # Make easily browsable return new_class
[ "def", "_create_markup_model", "(", "fixed_language", ")", ":", "title", "=", "backend", ".", "LANGUAGE_NAMES", ".", "get", "(", "fixed_language", ")", "or", "fixed_language", "objects", "=", "MarkupLanguageManager", "(", "fixed_language", ")", "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "language", "=", "fixed_language", "MarkupItem", ".", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "class", "Meta", ":", "verbose_name", "=", "title", "verbose_name_plural", "=", "_", "(", "'%s items'", ")", "%", "title", "proxy", "=", "True", "classname", "=", "\"{0}MarkupItem\"", ".", "format", "(", "fixed_language", ".", "capitalize", "(", ")", ")", "new_class", "=", "type", "(", "str", "(", "classname", ")", ",", "(", "MarkupItem", ",", ")", ",", "{", "'__module__'", ":", "MarkupItem", ".", "__module__", ",", "'objects'", ":", "objects", ",", "'save'", ":", "save", ",", "'Meta'", ":", "Meta", ",", "}", ")", "# Make easily browsable", "return", "new_class" ]
Create a new MarkupItem model that saves itself in a single language.
[ "Create", "a", "new", "MarkupItem", "model", "that", "saves", "itself", "in", "a", "single", "language", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/plugins/markup/models.py#L71-L98
django-fluent/django-fluent-contents
fluent_contents/models/fields.py
PlaceholderField.formfield
def formfield(self, **kwargs): """ Returns a :class:`PlaceholderFormField` instance for this database Field. """ defaults = { 'label': capfirst(self.verbose_name), 'help_text': self.help_text, 'required': not self.blank, } defaults.update(kwargs) return PlaceholderFormField(slot=self.slot, plugins=self._plugins, **defaults)
python
def formfield(self, **kwargs): """ Returns a :class:`PlaceholderFormField` instance for this database Field. """ defaults = { 'label': capfirst(self.verbose_name), 'help_text': self.help_text, 'required': not self.blank, } defaults.update(kwargs) return PlaceholderFormField(slot=self.slot, plugins=self._plugins, **defaults)
[ "def", "formfield", "(", "self", ",", "*", "*", "kwargs", ")", ":", "defaults", "=", "{", "'label'", ":", "capfirst", "(", "self", ".", "verbose_name", ")", ",", "'help_text'", ":", "self", ".", "help_text", ",", "'required'", ":", "not", "self", ".", "blank", ",", "}", "defaults", ".", "update", "(", "kwargs", ")", "return", "PlaceholderFormField", "(", "slot", "=", "self", ".", "slot", ",", "plugins", "=", "self", ".", "_plugins", ",", "*", "*", "defaults", ")" ]
Returns a :class:`PlaceholderFormField` instance for this database Field.
[ "Returns", "a", ":", "class", ":", "PlaceholderFormField", "instance", "for", "this", "database", "Field", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/models/fields.py#L175-L185
django-fluent/django-fluent-contents
fluent_contents/models/fields.py
PlaceholderField.contribute_to_class
def contribute_to_class(self, cls, name, **kwargs): """ Internal Django method to associate the field with the Model; it assigns the descriptor. """ super(PlaceholderField, self).contribute_to_class(cls, name, **kwargs) # overwrites what instance.<colname> returns; give direct access to the placeholder setattr(cls, name, PlaceholderFieldDescriptor(self.slot)) # Make placeholder fields easy to find # Can't assign this to cls._meta because that gets overwritten by every level of model inheritance. if not hasattr(cls, '_meta_placeholder_fields'): cls._meta_placeholder_fields = {} cls._meta_placeholder_fields[name] = self # Configure the revere relation if possible. # TODO: make sure reverse queries work properly if django.VERSION >= (1, 11): rel = self.remote_field else: rel = self.rel if rel.related_name is None: # Make unique for model (multiple models can use same slotnane) rel.related_name = '{app}_{model}_{slot}_FIXME'.format( app=cls._meta.app_label, model=cls._meta.object_name.lower(), slot=self.slot ) # Remove attribute must exist for the delete page. Currently it's not actively used. # The regular ForeignKey assigns a ForeignRelatedObjectsDescriptor to it for example. # In this case, the PlaceholderRelation is already the reverse relation. # Being able to move forward from the Placeholder to the derived models does not have that much value. setattr(rel.to, self.rel.related_name, None)
python
def contribute_to_class(self, cls, name, **kwargs): """ Internal Django method to associate the field with the Model; it assigns the descriptor. """ super(PlaceholderField, self).contribute_to_class(cls, name, **kwargs) # overwrites what instance.<colname> returns; give direct access to the placeholder setattr(cls, name, PlaceholderFieldDescriptor(self.slot)) # Make placeholder fields easy to find # Can't assign this to cls._meta because that gets overwritten by every level of model inheritance. if not hasattr(cls, '_meta_placeholder_fields'): cls._meta_placeholder_fields = {} cls._meta_placeholder_fields[name] = self # Configure the revere relation if possible. # TODO: make sure reverse queries work properly if django.VERSION >= (1, 11): rel = self.remote_field else: rel = self.rel if rel.related_name is None: # Make unique for model (multiple models can use same slotnane) rel.related_name = '{app}_{model}_{slot}_FIXME'.format( app=cls._meta.app_label, model=cls._meta.object_name.lower(), slot=self.slot ) # Remove attribute must exist for the delete page. Currently it's not actively used. # The regular ForeignKey assigns a ForeignRelatedObjectsDescriptor to it for example. # In this case, the PlaceholderRelation is already the reverse relation. # Being able to move forward from the Placeholder to the derived models does not have that much value. setattr(rel.to, self.rel.related_name, None)
[ "def", "contribute_to_class", "(", "self", ",", "cls", ",", "name", ",", "*", "*", "kwargs", ")", ":", "super", "(", "PlaceholderField", ",", "self", ")", ".", "contribute_to_class", "(", "cls", ",", "name", ",", "*", "*", "kwargs", ")", "# overwrites what instance.<colname> returns; give direct access to the placeholder", "setattr", "(", "cls", ",", "name", ",", "PlaceholderFieldDescriptor", "(", "self", ".", "slot", ")", ")", "# Make placeholder fields easy to find", "# Can't assign this to cls._meta because that gets overwritten by every level of model inheritance.", "if", "not", "hasattr", "(", "cls", ",", "'_meta_placeholder_fields'", ")", ":", "cls", ".", "_meta_placeholder_fields", "=", "{", "}", "cls", ".", "_meta_placeholder_fields", "[", "name", "]", "=", "self", "# Configure the revere relation if possible.", "# TODO: make sure reverse queries work properly", "if", "django", ".", "VERSION", ">=", "(", "1", ",", "11", ")", ":", "rel", "=", "self", ".", "remote_field", "else", ":", "rel", "=", "self", ".", "rel", "if", "rel", ".", "related_name", "is", "None", ":", "# Make unique for model (multiple models can use same slotnane)", "rel", ".", "related_name", "=", "'{app}_{model}_{slot}_FIXME'", ".", "format", "(", "app", "=", "cls", ".", "_meta", ".", "app_label", ",", "model", "=", "cls", ".", "_meta", ".", "object_name", ".", "lower", "(", ")", ",", "slot", "=", "self", ".", "slot", ")", "# Remove attribute must exist for the delete page. Currently it's not actively used.", "# The regular ForeignKey assigns a ForeignRelatedObjectsDescriptor to it for example.", "# In this case, the PlaceholderRelation is already the reverse relation.", "# Being able to move forward from the Placeholder to the derived models does not have that much value.", "setattr", "(", "rel", ".", "to", ",", "self", ".", "rel", ".", "related_name", ",", "None", ")" ]
Internal Django method to associate the field with the Model; it assigns the descriptor.
[ "Internal", "Django", "method", "to", "associate", "the", "field", "with", "the", "Model", ";", "it", "assigns", "the", "descriptor", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/models/fields.py#L187-L221
django-fluent/django-fluent-contents
fluent_contents/models/fields.py
PlaceholderField.plugins
def plugins(self): """ Get the set of plugins that this field may display. """ from fluent_contents import extensions if self._plugins is None: return extensions.plugin_pool.get_plugins() else: try: return extensions.plugin_pool.get_plugins_by_name(*self._plugins) except extensions.PluginNotFound as e: raise extensions.PluginNotFound(str(e) + " Update the plugin list of '{0}.{1}' field or FLUENT_CONTENTS_PLACEHOLDER_CONFIG['{2}'] setting.".format(self.model._meta.object_name, self.name, self.slot))
python
def plugins(self): """ Get the set of plugins that this field may display. """ from fluent_contents import extensions if self._plugins is None: return extensions.plugin_pool.get_plugins() else: try: return extensions.plugin_pool.get_plugins_by_name(*self._plugins) except extensions.PluginNotFound as e: raise extensions.PluginNotFound(str(e) + " Update the plugin list of '{0}.{1}' field or FLUENT_CONTENTS_PLACEHOLDER_CONFIG['{2}'] setting.".format(self.model._meta.object_name, self.name, self.slot))
[ "def", "plugins", "(", "self", ")", ":", "from", "fluent_contents", "import", "extensions", "if", "self", ".", "_plugins", "is", "None", ":", "return", "extensions", ".", "plugin_pool", ".", "get_plugins", "(", ")", "else", ":", "try", ":", "return", "extensions", ".", "plugin_pool", ".", "get_plugins_by_name", "(", "*", "self", ".", "_plugins", ")", "except", "extensions", ".", "PluginNotFound", "as", "e", ":", "raise", "extensions", ".", "PluginNotFound", "(", "str", "(", "e", ")", "+", "\" Update the plugin list of '{0}.{1}' field or FLUENT_CONTENTS_PLACEHOLDER_CONFIG['{2}'] setting.\"", ".", "format", "(", "self", ".", "model", ".", "_meta", ".", "object_name", ",", "self", ".", "name", ",", "self", ".", "slot", ")", ")" ]
Get the set of plugins that this field may display.
[ "Get", "the", "set", "of", "plugins", "that", "this", "field", "may", "display", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/models/fields.py#L224-L235
django-fluent/django-fluent-contents
fluent_contents/models/fields.py
PlaceholderField.value_from_object
def value_from_object(self, obj): """ Internal Django method, used to return the placeholder ID when exporting the model instance. """ try: # not using self.attname, access the descriptor instead. placeholder = getattr(obj, self.name) except Placeholder.DoesNotExist: return None # Still allow ModelForm / admin to open and create a new Placeholder if the table was truncated. return placeholder.id if placeholder else None
python
def value_from_object(self, obj): """ Internal Django method, used to return the placeholder ID when exporting the model instance. """ try: # not using self.attname, access the descriptor instead. placeholder = getattr(obj, self.name) except Placeholder.DoesNotExist: return None # Still allow ModelForm / admin to open and create a new Placeholder if the table was truncated. return placeholder.id if placeholder else None
[ "def", "value_from_object", "(", "self", ",", "obj", ")", ":", "try", ":", "# not using self.attname, access the descriptor instead.", "placeholder", "=", "getattr", "(", "obj", ",", "self", ".", "name", ")", "except", "Placeholder", ".", "DoesNotExist", ":", "return", "None", "# Still allow ModelForm / admin to open and create a new Placeholder if the table was truncated.", "return", "placeholder", ".", "id", "if", "placeholder", "else", "None" ]
Internal Django method, used to return the placeholder ID when exporting the model instance.
[ "Internal", "Django", "method", "used", "to", "return", "the", "placeholder", "ID", "when", "exporting", "the", "model", "instance", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/models/fields.py#L237-L247
django-fluent/django-fluent-contents
fluent_contents/rendering/search.py
SearchRenderingPipe.can_use_cached_output
def can_use_cached_output(self, contentitem): """ Read the cached output - only when search needs it. """ return contentitem.plugin.search_output and not contentitem.plugin.search_fields \ and super(SearchRenderingPipe, self).can_use_cached_output(contentitem)
python
def can_use_cached_output(self, contentitem): """ Read the cached output - only when search needs it. """ return contentitem.plugin.search_output and not contentitem.plugin.search_fields \ and super(SearchRenderingPipe, self).can_use_cached_output(contentitem)
[ "def", "can_use_cached_output", "(", "self", ",", "contentitem", ")", ":", "return", "contentitem", ".", "plugin", ".", "search_output", "and", "not", "contentitem", ".", "plugin", ".", "search_fields", "and", "super", "(", "SearchRenderingPipe", ",", "self", ")", ".", "can_use_cached_output", "(", "contentitem", ")" ]
Read the cached output - only when search needs it.
[ "Read", "the", "cached", "output", "-", "only", "when", "search", "needs", "it", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/rendering/search.py#L28-L33
django-fluent/django-fluent-contents
fluent_contents/rendering/search.py
SearchRenderingPipe.render_item
def render_item(self, contentitem): """ Render the item - but render as search text instead. """ plugin = contentitem.plugin if not plugin.search_output and not plugin.search_fields: # Only render items when the item was output will be indexed. raise SkipItem if not plugin.search_output: output = ContentItemOutput('', cacheable=False) else: output = super(SearchRenderingPipe, self).render_item(contentitem) if plugin.search_fields: # Just add the results into the output, but avoid caching that somewhere. output.html += plugin.get_search_text(contentitem) output.cacheable = False return output
python
def render_item(self, contentitem): """ Render the item - but render as search text instead. """ plugin = contentitem.plugin if not plugin.search_output and not plugin.search_fields: # Only render items when the item was output will be indexed. raise SkipItem if not plugin.search_output: output = ContentItemOutput('', cacheable=False) else: output = super(SearchRenderingPipe, self).render_item(contentitem) if plugin.search_fields: # Just add the results into the output, but avoid caching that somewhere. output.html += plugin.get_search_text(contentitem) output.cacheable = False return output
[ "def", "render_item", "(", "self", ",", "contentitem", ")", ":", "plugin", "=", "contentitem", ".", "plugin", "if", "not", "plugin", ".", "search_output", "and", "not", "plugin", ".", "search_fields", ":", "# Only render items when the item was output will be indexed.", "raise", "SkipItem", "if", "not", "plugin", ".", "search_output", ":", "output", "=", "ContentItemOutput", "(", "''", ",", "cacheable", "=", "False", ")", "else", ":", "output", "=", "super", "(", "SearchRenderingPipe", ",", "self", ")", ".", "render_item", "(", "contentitem", ")", "if", "plugin", ".", "search_fields", ":", "# Just add the results into the output, but avoid caching that somewhere.", "output", ".", "html", "+=", "plugin", ".", "get_search_text", "(", "contentitem", ")", "output", ".", "cacheable", "=", "False", "return", "output" ]
Render the item - but render as search text instead.
[ "Render", "the", "item", "-", "but", "render", "as", "search", "text", "instead", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/rendering/search.py#L35-L54
django-fluent/django-fluent-contents
fluent_contents/admin/contentitems.py
get_content_item_inlines
def get_content_item_inlines(plugins=None, base=BaseContentItemInline): """ Dynamically generate genuine django inlines for all registered content item types. When the `plugins` parameter is ``None``, all plugin inlines are returned. """ COPY_FIELDS = ( 'form', 'raw_id_fields', 'filter_vertical', 'filter_horizontal', 'radio_fields', 'prepopulated_fields', 'formfield_overrides', 'readonly_fields', ) if plugins is None: plugins = extensions.plugin_pool.get_plugins() inlines = [] for plugin in plugins: # self.model._supported_...() # Avoid errors that are hard to trace if not isinstance(plugin, extensions.ContentPlugin): raise TypeError("get_content_item_inlines() expects to receive ContentPlugin instances, not {0}".format(plugin)) ContentItemType = plugin.model # Create a new Type that inherits CmsPageItemInline # Read the static fields of the ItemType to override default appearance. # This code is based on FeinCMS, (c) Simon Meers, BSD licensed class_name = '%s_AutoInline' % ContentItemType.__name__ attrs = { '__module__': plugin.__class__.__module__, 'model': ContentItemType, # Add metadata properties for template 'name': plugin.verbose_name, 'plugin': plugin, 'type_name': plugin.type_name, 'extra_fieldsets': plugin.fieldsets, 'cp_admin_form_template': plugin.admin_form_template, 'cp_admin_init_template': plugin.admin_init_template, } # Copy a restricted set of admin fields to the inline model too. for name in COPY_FIELDS: if getattr(plugin, name): attrs[name] = getattr(plugin, name) inlines.append(type(class_name, (base,), attrs)) # For consistency, enforce ordering inlines.sort(key=lambda inline: inline.name.lower()) return inlines
python
def get_content_item_inlines(plugins=None, base=BaseContentItemInline): """ Dynamically generate genuine django inlines for all registered content item types. When the `plugins` parameter is ``None``, all plugin inlines are returned. """ COPY_FIELDS = ( 'form', 'raw_id_fields', 'filter_vertical', 'filter_horizontal', 'radio_fields', 'prepopulated_fields', 'formfield_overrides', 'readonly_fields', ) if plugins is None: plugins = extensions.plugin_pool.get_plugins() inlines = [] for plugin in plugins: # self.model._supported_...() # Avoid errors that are hard to trace if not isinstance(plugin, extensions.ContentPlugin): raise TypeError("get_content_item_inlines() expects to receive ContentPlugin instances, not {0}".format(plugin)) ContentItemType = plugin.model # Create a new Type that inherits CmsPageItemInline # Read the static fields of the ItemType to override default appearance. # This code is based on FeinCMS, (c) Simon Meers, BSD licensed class_name = '%s_AutoInline' % ContentItemType.__name__ attrs = { '__module__': plugin.__class__.__module__, 'model': ContentItemType, # Add metadata properties for template 'name': plugin.verbose_name, 'plugin': plugin, 'type_name': plugin.type_name, 'extra_fieldsets': plugin.fieldsets, 'cp_admin_form_template': plugin.admin_form_template, 'cp_admin_init_template': plugin.admin_init_template, } # Copy a restricted set of admin fields to the inline model too. for name in COPY_FIELDS: if getattr(plugin, name): attrs[name] = getattr(plugin, name) inlines.append(type(class_name, (base,), attrs)) # For consistency, enforce ordering inlines.sort(key=lambda inline: inline.name.lower()) return inlines
[ "def", "get_content_item_inlines", "(", "plugins", "=", "None", ",", "base", "=", "BaseContentItemInline", ")", ":", "COPY_FIELDS", "=", "(", "'form'", ",", "'raw_id_fields'", ",", "'filter_vertical'", ",", "'filter_horizontal'", ",", "'radio_fields'", ",", "'prepopulated_fields'", ",", "'formfield_overrides'", ",", "'readonly_fields'", ",", ")", "if", "plugins", "is", "None", ":", "plugins", "=", "extensions", ".", "plugin_pool", ".", "get_plugins", "(", ")", "inlines", "=", "[", "]", "for", "plugin", "in", "plugins", ":", "# self.model._supported_...()", "# Avoid errors that are hard to trace", "if", "not", "isinstance", "(", "plugin", ",", "extensions", ".", "ContentPlugin", ")", ":", "raise", "TypeError", "(", "\"get_content_item_inlines() expects to receive ContentPlugin instances, not {0}\"", ".", "format", "(", "plugin", ")", ")", "ContentItemType", "=", "plugin", ".", "model", "# Create a new Type that inherits CmsPageItemInline", "# Read the static fields of the ItemType to override default appearance.", "# This code is based on FeinCMS, (c) Simon Meers, BSD licensed", "class_name", "=", "'%s_AutoInline'", "%", "ContentItemType", ".", "__name__", "attrs", "=", "{", "'__module__'", ":", "plugin", ".", "__class__", ".", "__module__", ",", "'model'", ":", "ContentItemType", ",", "# Add metadata properties for template", "'name'", ":", "plugin", ".", "verbose_name", ",", "'plugin'", ":", "plugin", ",", "'type_name'", ":", "plugin", ".", "type_name", ",", "'extra_fieldsets'", ":", "plugin", ".", "fieldsets", ",", "'cp_admin_form_template'", ":", "plugin", ".", "admin_form_template", ",", "'cp_admin_init_template'", ":", "plugin", ".", "admin_init_template", ",", "}", "# Copy a restricted set of admin fields to the inline model too.", "for", "name", "in", "COPY_FIELDS", ":", "if", "getattr", "(", "plugin", ",", "name", ")", ":", "attrs", "[", "name", "]", "=", "getattr", "(", "plugin", ",", "name", ")", "inlines", ".", "append", "(", "type", "(", "class_name", ",", "(", "base", ",", ")", ",", "attrs", ")", ")", "# For consistency, enforce ordering", "inlines", ".", "sort", "(", "key", "=", "lambda", "inline", ":", "inline", ".", "name", ".", "lower", "(", ")", ")", "return", "inlines" ]
Dynamically generate genuine django inlines for all registered content item types. When the `plugins` parameter is ``None``, all plugin inlines are returned.
[ "Dynamically", "generate", "genuine", "django", "inlines", "for", "all", "registered", "content", "item", "types", ".", "When", "the", "plugins", "parameter", "is", "None", "all", "plugin", "inlines", "are", "returned", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/admin/contentitems.py#L151-L198
django-fluent/django-fluent-contents
fluent_contents/plugins/oembeditem/backend.py
get_oembed_providers
def get_oembed_providers(): """ Get the list of OEmbed providers. """ global _provider_list, _provider_lock if _provider_list is not None: return _provider_list # Allow only one thread to build the list, or make request to embed.ly. _provider_lock.acquire() try: # And check whether that already succeeded when the lock is granted. if _provider_list is None: _provider_list = _build_provider_list() finally: # Always release if there are errors _provider_lock.release() return _provider_list
python
def get_oembed_providers(): """ Get the list of OEmbed providers. """ global _provider_list, _provider_lock if _provider_list is not None: return _provider_list # Allow only one thread to build the list, or make request to embed.ly. _provider_lock.acquire() try: # And check whether that already succeeded when the lock is granted. if _provider_list is None: _provider_list = _build_provider_list() finally: # Always release if there are errors _provider_lock.release() return _provider_list
[ "def", "get_oembed_providers", "(", ")", ":", "global", "_provider_list", ",", "_provider_lock", "if", "_provider_list", "is", "not", "None", ":", "return", "_provider_list", "# Allow only one thread to build the list, or make request to embed.ly.", "_provider_lock", ".", "acquire", "(", ")", "try", ":", "# And check whether that already succeeded when the lock is granted.", "if", "_provider_list", "is", "None", ":", "_provider_list", "=", "_build_provider_list", "(", ")", "finally", ":", "# Always release if there are errors", "_provider_lock", ".", "release", "(", ")", "return", "_provider_list" ]
Get the list of OEmbed providers.
[ "Get", "the", "list", "of", "OEmbed", "providers", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/plugins/oembeditem/backend.py#L26-L44
django-fluent/django-fluent-contents
fluent_contents/plugins/oembeditem/backend.py
_build_provider_list
def _build_provider_list(): """ Construct the provider registry, using the app settings. """ registry = None if appsettings.FLUENT_OEMBED_SOURCE == 'basic': registry = bootstrap_basic() elif appsettings.FLUENT_OEMBED_SOURCE == 'embedly': params = {} if appsettings.MICAWBER_EMBEDLY_KEY: params['key'] = appsettings.MICAWBER_EMBEDLY_KEY registry = bootstrap_embedly(**params) elif appsettings.FLUENT_OEMBED_SOURCE == 'noembed': registry = bootstrap_noembed(nowrap=1) elif appsettings.FLUENT_OEMBED_SOURCE == 'list': # Fill list manually in the settings, e.g. to have a fixed set of supported secure providers. registry = ProviderRegistry() for regex, provider in appsettings.FLUENT_OEMBED_PROVIDER_LIST: registry.register(regex, Provider(provider)) else: raise ImproperlyConfigured("Invalid value of FLUENT_OEMBED_SOURCE, only 'basic', 'list', 'noembed' or 'embedly' is supported.") # Add any extra providers defined in the settings for regex, provider in appsettings.FLUENT_OEMBED_EXTRA_PROVIDERS: registry.register(regex, Provider(provider)) return registry
python
def _build_provider_list(): """ Construct the provider registry, using the app settings. """ registry = None if appsettings.FLUENT_OEMBED_SOURCE == 'basic': registry = bootstrap_basic() elif appsettings.FLUENT_OEMBED_SOURCE == 'embedly': params = {} if appsettings.MICAWBER_EMBEDLY_KEY: params['key'] = appsettings.MICAWBER_EMBEDLY_KEY registry = bootstrap_embedly(**params) elif appsettings.FLUENT_OEMBED_SOURCE == 'noembed': registry = bootstrap_noembed(nowrap=1) elif appsettings.FLUENT_OEMBED_SOURCE == 'list': # Fill list manually in the settings, e.g. to have a fixed set of supported secure providers. registry = ProviderRegistry() for regex, provider in appsettings.FLUENT_OEMBED_PROVIDER_LIST: registry.register(regex, Provider(provider)) else: raise ImproperlyConfigured("Invalid value of FLUENT_OEMBED_SOURCE, only 'basic', 'list', 'noembed' or 'embedly' is supported.") # Add any extra providers defined in the settings for regex, provider in appsettings.FLUENT_OEMBED_EXTRA_PROVIDERS: registry.register(regex, Provider(provider)) return registry
[ "def", "_build_provider_list", "(", ")", ":", "registry", "=", "None", "if", "appsettings", ".", "FLUENT_OEMBED_SOURCE", "==", "'basic'", ":", "registry", "=", "bootstrap_basic", "(", ")", "elif", "appsettings", ".", "FLUENT_OEMBED_SOURCE", "==", "'embedly'", ":", "params", "=", "{", "}", "if", "appsettings", ".", "MICAWBER_EMBEDLY_KEY", ":", "params", "[", "'key'", "]", "=", "appsettings", ".", "MICAWBER_EMBEDLY_KEY", "registry", "=", "bootstrap_embedly", "(", "*", "*", "params", ")", "elif", "appsettings", ".", "FLUENT_OEMBED_SOURCE", "==", "'noembed'", ":", "registry", "=", "bootstrap_noembed", "(", "nowrap", "=", "1", ")", "elif", "appsettings", ".", "FLUENT_OEMBED_SOURCE", "==", "'list'", ":", "# Fill list manually in the settings, e.g. to have a fixed set of supported secure providers.", "registry", "=", "ProviderRegistry", "(", ")", "for", "regex", ",", "provider", "in", "appsettings", ".", "FLUENT_OEMBED_PROVIDER_LIST", ":", "registry", ".", "register", "(", "regex", ",", "Provider", "(", "provider", ")", ")", "else", ":", "raise", "ImproperlyConfigured", "(", "\"Invalid value of FLUENT_OEMBED_SOURCE, only 'basic', 'list', 'noembed' or 'embedly' is supported.\"", ")", "# Add any extra providers defined in the settings", "for", "regex", ",", "provider", "in", "appsettings", ".", "FLUENT_OEMBED_EXTRA_PROVIDERS", ":", "registry", ".", "register", "(", "regex", ",", "Provider", "(", "provider", ")", ")", "return", "registry" ]
Construct the provider registry, using the app settings.
[ "Construct", "the", "provider", "registry", "using", "the", "app", "settings", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/plugins/oembeditem/backend.py#L47-L73
django-fluent/django-fluent-contents
fluent_contents/plugins/oembeditem/backend.py
get_oembed_data
def get_oembed_data(url, max_width=None, max_height=None, **params): """ Fetch the OEmbed object, return the response as dictionary. """ if max_width: params['maxwidth'] = max_width if max_height: params['maxheight'] = max_height registry = get_oembed_providers() return registry.request(url, **params)
python
def get_oembed_data(url, max_width=None, max_height=None, **params): """ Fetch the OEmbed object, return the response as dictionary. """ if max_width: params['maxwidth'] = max_width if max_height: params['maxheight'] = max_height registry = get_oembed_providers() return registry.request(url, **params)
[ "def", "get_oembed_data", "(", "url", ",", "max_width", "=", "None", ",", "max_height", "=", "None", ",", "*", "*", "params", ")", ":", "if", "max_width", ":", "params", "[", "'maxwidth'", "]", "=", "max_width", "if", "max_height", ":", "params", "[", "'maxheight'", "]", "=", "max_height", "registry", "=", "get_oembed_providers", "(", ")", "return", "registry", ".", "request", "(", "url", ",", "*", "*", "params", ")" ]
Fetch the OEmbed object, return the response as dictionary.
[ "Fetch", "the", "OEmbed", "object", "return", "the", "response", "as", "dictionary", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/plugins/oembeditem/backend.py#L84-L92
django-fluent/django-fluent-contents
fluent_contents/templatetags/placeholder_admin_tags.py
group_plugins_into_categories
def group_plugins_into_categories(plugins): """ Return all plugins, grouped by category. The structure is a {"Categorynane": [list of plugin classes]} """ if not plugins: return {} plugins = sorted(plugins, key=lambda p: p.verbose_name) categories = {} for plugin in plugins: title = str(plugin.category or u"") # enforce resolving ugettext_lazy proxies. if title not in categories: categories[title] = [] categories[title].append(plugin) return categories
python
def group_plugins_into_categories(plugins): """ Return all plugins, grouped by category. The structure is a {"Categorynane": [list of plugin classes]} """ if not plugins: return {} plugins = sorted(plugins, key=lambda p: p.verbose_name) categories = {} for plugin in plugins: title = str(plugin.category or u"") # enforce resolving ugettext_lazy proxies. if title not in categories: categories[title] = [] categories[title].append(plugin) return categories
[ "def", "group_plugins_into_categories", "(", "plugins", ")", ":", "if", "not", "plugins", ":", "return", "{", "}", "plugins", "=", "sorted", "(", "plugins", ",", "key", "=", "lambda", "p", ":", "p", ".", "verbose_name", ")", "categories", "=", "{", "}", "for", "plugin", "in", "plugins", ":", "title", "=", "str", "(", "plugin", ".", "category", "or", "u\"\"", ")", "# enforce resolving ugettext_lazy proxies.", "if", "title", "not", "in", "categories", ":", "categories", "[", "title", "]", "=", "[", "]", "categories", "[", "title", "]", ".", "append", "(", "plugin", ")", "return", "categories" ]
Return all plugins, grouped by category. The structure is a {"Categorynane": [list of plugin classes]}
[ "Return", "all", "plugins", "grouped", "by", "category", ".", "The", "structure", "is", "a", "{", "Categorynane", ":", "[", "list", "of", "plugin", "classes", "]", "}" ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/templatetags/placeholder_admin_tags.py#L37-L53
django-fluent/django-fluent-contents
fluent_contents/templatetags/placeholder_admin_tags.py
plugin_categories_to_choices
def plugin_categories_to_choices(categories): """ Return a tuple of plugin model choices, suitable for a select field. Each tuple is a ("TypeName", "Title") value. """ choices = [] for category, items in categories.items(): if items: plugin_tuples = tuple((plugin.type_name, plugin.verbose_name) for plugin in items) if category: choices.append((category, plugin_tuples)) else: choices += plugin_tuples choices.sort(key=lambda item: item[0]) return choices
python
def plugin_categories_to_choices(categories): """ Return a tuple of plugin model choices, suitable for a select field. Each tuple is a ("TypeName", "Title") value. """ choices = [] for category, items in categories.items(): if items: plugin_tuples = tuple((plugin.type_name, plugin.verbose_name) for plugin in items) if category: choices.append((category, plugin_tuples)) else: choices += plugin_tuples choices.sort(key=lambda item: item[0]) return choices
[ "def", "plugin_categories_to_choices", "(", "categories", ")", ":", "choices", "=", "[", "]", "for", "category", ",", "items", "in", "categories", ".", "items", "(", ")", ":", "if", "items", ":", "plugin_tuples", "=", "tuple", "(", "(", "plugin", ".", "type_name", ",", "plugin", ".", "verbose_name", ")", "for", "plugin", "in", "items", ")", "if", "category", ":", "choices", ".", "append", "(", "(", "category", ",", "plugin_tuples", ")", ")", "else", ":", "choices", "+=", "plugin_tuples", "choices", ".", "sort", "(", "key", "=", "lambda", "item", ":", "item", "[", "0", "]", ")", "return", "choices" ]
Return a tuple of plugin model choices, suitable for a select field. Each tuple is a ("TypeName", "Title") value.
[ "Return", "a", "tuple", "of", "plugin", "model", "choices", "suitable", "for", "a", "select", "field", ".", "Each", "tuple", "is", "a", "(", "TypeName", "Title", ")", "value", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/templatetags/placeholder_admin_tags.py#L66-L81
django-fluent/django-fluent-contents
fluent_contents/rendering/utils.py
add_media
def add_media(dest, media): """ Optimized version of django.forms.Media.__add__() that doesn't create new objects. """ if django.VERSION >= (2, 2): dest._css_lists += media._css_lists dest._js_lists += media._js_lists elif django.VERSION >= (2, 0): combined = dest + media dest._css = combined._css dest._js = combined._js else: dest.add_css(media._css) dest.add_js(media._js)
python
def add_media(dest, media): """ Optimized version of django.forms.Media.__add__() that doesn't create new objects. """ if django.VERSION >= (2, 2): dest._css_lists += media._css_lists dest._js_lists += media._js_lists elif django.VERSION >= (2, 0): combined = dest + media dest._css = combined._css dest._js = combined._js else: dest.add_css(media._css) dest.add_js(media._js)
[ "def", "add_media", "(", "dest", ",", "media", ")", ":", "if", "django", ".", "VERSION", ">=", "(", "2", ",", "2", ")", ":", "dest", ".", "_css_lists", "+=", "media", ".", "_css_lists", "dest", ".", "_js_lists", "+=", "media", ".", "_js_lists", "elif", "django", ".", "VERSION", ">=", "(", "2", ",", "0", ")", ":", "combined", "=", "dest", "+", "media", "dest", ".", "_css", "=", "combined", ".", "_css", "dest", ".", "_js", "=", "combined", ".", "_js", "else", ":", "dest", ".", "add_css", "(", "media", ".", "_css", ")", "dest", ".", "add_js", "(", "media", ".", "_js", ")" ]
Optimized version of django.forms.Media.__add__() that doesn't create new objects.
[ "Optimized", "version", "of", "django", ".", "forms", ".", "Media", ".", "__add__", "()", "that", "doesn", "t", "create", "new", "objects", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/rendering/utils.py#L25-L38
django-fluent/django-fluent-contents
fluent_contents/rendering/utils.py
get_dummy_request
def get_dummy_request(language=None): """ Returns a Request instance populated with cms specific attributes. """ if settings.ALLOWED_HOSTS and settings.ALLOWED_HOSTS != "*": host = settings.ALLOWED_HOSTS[0] else: host = Site.objects.get_current().domain request = RequestFactory().get("/", HTTP_HOST=host) request.session = {} request.LANGUAGE_CODE = language or settings.LANGUAGE_CODE # Needed for plugin rendering. request.current_page = None if 'django.contrib.auth' in settings.INSTALLED_APPS: from django.contrib.auth.models import AnonymousUser request.user = AnonymousUser() return request
python
def get_dummy_request(language=None): """ Returns a Request instance populated with cms specific attributes. """ if settings.ALLOWED_HOSTS and settings.ALLOWED_HOSTS != "*": host = settings.ALLOWED_HOSTS[0] else: host = Site.objects.get_current().domain request = RequestFactory().get("/", HTTP_HOST=host) request.session = {} request.LANGUAGE_CODE = language or settings.LANGUAGE_CODE # Needed for plugin rendering. request.current_page = None if 'django.contrib.auth' in settings.INSTALLED_APPS: from django.contrib.auth.models import AnonymousUser request.user = AnonymousUser() return request
[ "def", "get_dummy_request", "(", "language", "=", "None", ")", ":", "if", "settings", ".", "ALLOWED_HOSTS", "and", "settings", ".", "ALLOWED_HOSTS", "!=", "\"*\"", ":", "host", "=", "settings", ".", "ALLOWED_HOSTS", "[", "0", "]", "else", ":", "host", "=", "Site", ".", "objects", ".", "get_current", "(", ")", ".", "domain", "request", "=", "RequestFactory", "(", ")", ".", "get", "(", "\"/\"", ",", "HTTP_HOST", "=", "host", ")", "request", ".", "session", "=", "{", "}", "request", ".", "LANGUAGE_CODE", "=", "language", "or", "settings", ".", "LANGUAGE_CODE", "# Needed for plugin rendering.", "request", ".", "current_page", "=", "None", "if", "'django.contrib.auth'", "in", "settings", ".", "INSTALLED_APPS", ":", "from", "django", ".", "contrib", ".", "auth", ".", "models", "import", "AnonymousUser", "request", ".", "user", "=", "AnonymousUser", "(", ")", "return", "request" ]
Returns a Request instance populated with cms specific attributes.
[ "Returns", "a", "Request", "instance", "populated", "with", "cms", "specific", "attributes", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/rendering/utils.py#L51-L71
django-fluent/django-fluent-contents
fluent_contents/rendering/utils.py
get_render_language
def get_render_language(contentitem): """ Tell which language should be used to render the content item. """ plugin = contentitem.plugin if plugin.render_ignore_item_language \ or (plugin.cache_output and plugin.cache_output_per_language): # Render the template in the current language. # The cache also stores the output under the current language code. # # It would make sense to apply this for fallback content too, # but that would be ambiguous however because the parent_object could also be a fallback, # and that case can't be detected here. Hence, better be explicit when desiring multi-lingual content. return get_language() # Avoid switching the content, else: # Render the template in the ContentItem language. # This makes sure that {% trans %} tag output matches the language of the model field data. return contentitem.language_code
python
def get_render_language(contentitem): """ Tell which language should be used to render the content item. """ plugin = contentitem.plugin if plugin.render_ignore_item_language \ or (plugin.cache_output and plugin.cache_output_per_language): # Render the template in the current language. # The cache also stores the output under the current language code. # # It would make sense to apply this for fallback content too, # but that would be ambiguous however because the parent_object could also be a fallback, # and that case can't be detected here. Hence, better be explicit when desiring multi-lingual content. return get_language() # Avoid switching the content, else: # Render the template in the ContentItem language. # This makes sure that {% trans %} tag output matches the language of the model field data. return contentitem.language_code
[ "def", "get_render_language", "(", "contentitem", ")", ":", "plugin", "=", "contentitem", ".", "plugin", "if", "plugin", ".", "render_ignore_item_language", "or", "(", "plugin", ".", "cache_output", "and", "plugin", ".", "cache_output_per_language", ")", ":", "# Render the template in the current language.", "# The cache also stores the output under the current language code.", "#", "# It would make sense to apply this for fallback content too,", "# but that would be ambiguous however because the parent_object could also be a fallback,", "# and that case can't be detected here. Hence, better be explicit when desiring multi-lingual content.", "return", "get_language", "(", ")", "# Avoid switching the content,", "else", ":", "# Render the template in the ContentItem language.", "# This makes sure that {% trans %} tag output matches the language of the model field data.", "return", "contentitem", ".", "language_code" ]
Tell which language should be used to render the content item.
[ "Tell", "which", "language", "should", "be", "used", "to", "render", "the", "content", "item", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/rendering/utils.py#L74-L92
django-fluent/django-fluent-contents
fluent_contents/rendering/utils.py
optimize_logger_level
def optimize_logger_level(logger, log_level): """ At runtime, when logging is not active, replace the .debug() call with a no-op. """ function_name = _log_functions[log_level] if getattr(logger, function_name) is _dummy_log: return False is_level_logged = logger.isEnabledFor(log_level) if not is_level_logged: setattr(logger, function_name, _dummy_log) return is_level_logged
python
def optimize_logger_level(logger, log_level): """ At runtime, when logging is not active, replace the .debug() call with a no-op. """ function_name = _log_functions[log_level] if getattr(logger, function_name) is _dummy_log: return False is_level_logged = logger.isEnabledFor(log_level) if not is_level_logged: setattr(logger, function_name, _dummy_log) return is_level_logged
[ "def", "optimize_logger_level", "(", "logger", ",", "log_level", ")", ":", "function_name", "=", "_log_functions", "[", "log_level", "]", "if", "getattr", "(", "logger", ",", "function_name", ")", "is", "_dummy_log", ":", "return", "False", "is_level_logged", "=", "logger", ".", "isEnabledFor", "(", "log_level", ")", "if", "not", "is_level_logged", ":", "setattr", "(", "logger", ",", "function_name", ",", "_dummy_log", ")", "return", "is_level_logged" ]
At runtime, when logging is not active, replace the .debug() call with a no-op.
[ "At", "runtime", "when", "logging", "is", "not", "active", "replace", "the", ".", "debug", "()", "call", "with", "a", "no", "-", "op", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/rendering/utils.py#L159-L172
django-fluent/django-fluent-contents
fluent_contents/utils/search.py
get_search_field_values
def get_search_field_values(contentitem): """ Extract the search fields from the model. """ plugin = contentitem.plugin values = [] for field_name in plugin.search_fields: value = getattr(contentitem, field_name) # Just assume all strings may contain HTML. # Not checking for just the PluginHtmlField here. if value and isinstance(value, six.string_types): value = get_cleaned_string(value) values.append(value) return values
python
def get_search_field_values(contentitem): """ Extract the search fields from the model. """ plugin = contentitem.plugin values = [] for field_name in plugin.search_fields: value = getattr(contentitem, field_name) # Just assume all strings may contain HTML. # Not checking for just the PluginHtmlField here. if value and isinstance(value, six.string_types): value = get_cleaned_string(value) values.append(value) return values
[ "def", "get_search_field_values", "(", "contentitem", ")", ":", "plugin", "=", "contentitem", ".", "plugin", "values", "=", "[", "]", "for", "field_name", "in", "plugin", ".", "search_fields", ":", "value", "=", "getattr", "(", "contentitem", ",", "field_name", ")", "# Just assume all strings may contain HTML.", "# Not checking for just the PluginHtmlField here.", "if", "value", "and", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", ":", "value", "=", "get_cleaned_string", "(", "value", ")", "values", ".", "append", "(", "value", ")", "return", "values" ]
Extract the search fields from the model.
[ "Extract", "the", "search", "fields", "from", "the", "model", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/utils/search.py#L9-L25
django-fluent/django-fluent-contents
example/simplecms/admin.py
PageAdmin.get_urls
def get_urls(self): """ Introduce more urls """ urls = super(PageAdmin, self).get_urls() my_urls = [ url(r'^get_layout/$', self.admin_site.admin_view(self.get_layout_view)) ] return my_urls + urls
python
def get_urls(self): """ Introduce more urls """ urls = super(PageAdmin, self).get_urls() my_urls = [ url(r'^get_layout/$', self.admin_site.admin_view(self.get_layout_view)) ] return my_urls + urls
[ "def", "get_urls", "(", "self", ")", ":", "urls", "=", "super", "(", "PageAdmin", ",", "self", ")", ".", "get_urls", "(", ")", "my_urls", "=", "[", "url", "(", "r'^get_layout/$'", ",", "self", ".", "admin_site", ".", "admin_view", "(", "self", ".", "get_layout_view", ")", ")", "]", "return", "my_urls", "+", "urls" ]
Introduce more urls
[ "Introduce", "more", "urls" ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/example/simplecms/admin.py#L53-L61
django-fluent/django-fluent-contents
example/simplecms/admin.py
PageAdmin.get_layout_view
def get_layout_view(self, request): """ Return the metadata about a layout """ template_name = request.GET['name'] # Check if template is allowed, avoid parsing random templates templates = dict(appconfig.SIMPLECMS_TEMPLATE_CHOICES) if template_name not in templates: jsondata = {'success': False, 'error': 'Template not found'} status = 404 else: # Extract placeholders from the template, and pass to the client. template = get_template(template_name) placeholders = get_template_placeholder_data(template) jsondata = { 'placeholders': [p.as_dict() for p in placeholders], } status = 200 jsonstr = json.dumps(jsondata) return HttpResponse(jsonstr, content_type='application/json', status=status)
python
def get_layout_view(self, request): """ Return the metadata about a layout """ template_name = request.GET['name'] # Check if template is allowed, avoid parsing random templates templates = dict(appconfig.SIMPLECMS_TEMPLATE_CHOICES) if template_name not in templates: jsondata = {'success': False, 'error': 'Template not found'} status = 404 else: # Extract placeholders from the template, and pass to the client. template = get_template(template_name) placeholders = get_template_placeholder_data(template) jsondata = { 'placeholders': [p.as_dict() for p in placeholders], } status = 200 jsonstr = json.dumps(jsondata) return HttpResponse(jsonstr, content_type='application/json', status=status)
[ "def", "get_layout_view", "(", "self", ",", "request", ")", ":", "template_name", "=", "request", ".", "GET", "[", "'name'", "]", "# Check if template is allowed, avoid parsing random templates", "templates", "=", "dict", "(", "appconfig", ".", "SIMPLECMS_TEMPLATE_CHOICES", ")", "if", "template_name", "not", "in", "templates", ":", "jsondata", "=", "{", "'success'", ":", "False", ",", "'error'", ":", "'Template not found'", "}", "status", "=", "404", "else", ":", "# Extract placeholders from the template, and pass to the client.", "template", "=", "get_template", "(", "template_name", ")", "placeholders", "=", "get_template_placeholder_data", "(", "template", ")", "jsondata", "=", "{", "'placeholders'", ":", "[", "p", ".", "as_dict", "(", ")", "for", "p", "in", "placeholders", "]", ",", "}", "status", "=", "200", "jsonstr", "=", "json", ".", "dumps", "(", "jsondata", ")", "return", "HttpResponse", "(", "jsonstr", ",", "content_type", "=", "'application/json'", ",", "status", "=", "status", ")" ]
Return the metadata about a layout
[ "Return", "the", "metadata", "about", "a", "layout" ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/example/simplecms/admin.py#L63-L85
django-fluent/django-fluent-contents
fluent_contents/plugins/text/filters/softhyphen.py
softhyphen_filter
def softhyphen_filter(textitem, html): """ Apply soft hyphenation to the text, which inserts ``&shy;`` markers. """ language = textitem.language_code # Make sure the Django language code gets converted to what django-softhypen 1.0.2 needs. if language == 'en': language = 'en-us' elif '-' not in language: language = "{0}-{0}".format(language) return hyphenate(html, language=language)
python
def softhyphen_filter(textitem, html): """ Apply soft hyphenation to the text, which inserts ``&shy;`` markers. """ language = textitem.language_code # Make sure the Django language code gets converted to what django-softhypen 1.0.2 needs. if language == 'en': language = 'en-us' elif '-' not in language: language = "{0}-{0}".format(language) return hyphenate(html, language=language)
[ "def", "softhyphen_filter", "(", "textitem", ",", "html", ")", ":", "language", "=", "textitem", ".", "language_code", "# Make sure the Django language code gets converted to what django-softhypen 1.0.2 needs.", "if", "language", "==", "'en'", ":", "language", "=", "'en-us'", "elif", "'-'", "not", "in", "language", ":", "language", "=", "\"{0}-{0}\"", ".", "format", "(", "language", ")", "return", "hyphenate", "(", "html", ",", "language", "=", "language", ")" ]
Apply soft hyphenation to the text, which inserts ``&shy;`` markers.
[ "Apply", "soft", "hyphenation", "to", "the", "text", "which", "inserts", "&shy", ";", "markers", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/plugins/text/filters/softhyphen.py#L10-L22
django-fluent/django-fluent-contents
fluent_contents/rendering/main.py
get_cached_placeholder_output
def get_cached_placeholder_output(parent_object, placeholder_name): """ Return cached output for a placeholder, if available. This avoids fetching the Placeholder object. """ if not PlaceholderRenderingPipe.may_cache_placeholders(): return None language_code = get_parent_language_code(parent_object) cache_key = get_placeholder_cache_key_for_parent(parent_object, placeholder_name, language_code) return cache.get(cache_key)
python
def get_cached_placeholder_output(parent_object, placeholder_name): """ Return cached output for a placeholder, if available. This avoids fetching the Placeholder object. """ if not PlaceholderRenderingPipe.may_cache_placeholders(): return None language_code = get_parent_language_code(parent_object) cache_key = get_placeholder_cache_key_for_parent(parent_object, placeholder_name, language_code) return cache.get(cache_key)
[ "def", "get_cached_placeholder_output", "(", "parent_object", ",", "placeholder_name", ")", ":", "if", "not", "PlaceholderRenderingPipe", ".", "may_cache_placeholders", "(", ")", ":", "return", "None", "language_code", "=", "get_parent_language_code", "(", "parent_object", ")", "cache_key", "=", "get_placeholder_cache_key_for_parent", "(", "parent_object", ",", "placeholder_name", ",", "language_code", ")", "return", "cache", ".", "get", "(", "cache_key", ")" ]
Return cached output for a placeholder, if available. This avoids fetching the Placeholder object.
[ "Return", "cached", "output", "for", "a", "placeholder", "if", "available", ".", "This", "avoids", "fetching", "the", "Placeholder", "object", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/rendering/main.py#L14-L24
django-fluent/django-fluent-contents
fluent_contents/rendering/main.py
render_placeholder
def render_placeholder(request, placeholder, parent_object=None, template_name=None, cachable=None, limit_parent_language=True, fallback_language=None): """ Render a :class:`~fluent_contents.models.Placeholder` object. Returns a :class:`~fluent_contents.models.ContentItemOutput` object which contains the HTML output and :class:`~django.forms.Media` object. This function also caches the complete output of the placeholder when all individual items are cacheable. :param request: The current request object. :type request: :class:`~django.http.HttpRequest` :param placeholder: The placeholder object. :type placeholder: :class:`~fluent_contents.models.Placeholder` :param parent_object: Optional, the parent object of the placeholder (already implied by the placeholder) :param template_name: Optional template name used to concatenate the placeholder output. :type template_name: str | None :param cachable: Whether the output is cachable, otherwise the full output will not be cached. Default: False when using a template, True otherwise. :type cachable: bool | None :param limit_parent_language: Whether the items should be limited to the parent language. :type limit_parent_language: bool :param fallback_language: The fallback language to use if there are no items in the current language. Passing ``True`` uses the default :ref:`FLUENT_CONTENTS_DEFAULT_LANGUAGE_CODE`. :type fallback_language: bool/str :rtype: :class:`~fluent_contents.models.ContentItemOutput` """ output = PlaceholderRenderingPipe(request).render_placeholder( placeholder=placeholder, parent_object=parent_object, template_name=template_name, cachable=cachable, limit_parent_language=limit_parent_language, fallback_language=fallback_language ) # Wrap the result after it's stored in the cache. if markers.is_edit_mode(request): output.html = markers.wrap_placeholder_output(output.html, placeholder) return output
python
def render_placeholder(request, placeholder, parent_object=None, template_name=None, cachable=None, limit_parent_language=True, fallback_language=None): """ Render a :class:`~fluent_contents.models.Placeholder` object. Returns a :class:`~fluent_contents.models.ContentItemOutput` object which contains the HTML output and :class:`~django.forms.Media` object. This function also caches the complete output of the placeholder when all individual items are cacheable. :param request: The current request object. :type request: :class:`~django.http.HttpRequest` :param placeholder: The placeholder object. :type placeholder: :class:`~fluent_contents.models.Placeholder` :param parent_object: Optional, the parent object of the placeholder (already implied by the placeholder) :param template_name: Optional template name used to concatenate the placeholder output. :type template_name: str | None :param cachable: Whether the output is cachable, otherwise the full output will not be cached. Default: False when using a template, True otherwise. :type cachable: bool | None :param limit_parent_language: Whether the items should be limited to the parent language. :type limit_parent_language: bool :param fallback_language: The fallback language to use if there are no items in the current language. Passing ``True`` uses the default :ref:`FLUENT_CONTENTS_DEFAULT_LANGUAGE_CODE`. :type fallback_language: bool/str :rtype: :class:`~fluent_contents.models.ContentItemOutput` """ output = PlaceholderRenderingPipe(request).render_placeholder( placeholder=placeholder, parent_object=parent_object, template_name=template_name, cachable=cachable, limit_parent_language=limit_parent_language, fallback_language=fallback_language ) # Wrap the result after it's stored in the cache. if markers.is_edit_mode(request): output.html = markers.wrap_placeholder_output(output.html, placeholder) return output
[ "def", "render_placeholder", "(", "request", ",", "placeholder", ",", "parent_object", "=", "None", ",", "template_name", "=", "None", ",", "cachable", "=", "None", ",", "limit_parent_language", "=", "True", ",", "fallback_language", "=", "None", ")", ":", "output", "=", "PlaceholderRenderingPipe", "(", "request", ")", ".", "render_placeholder", "(", "placeholder", "=", "placeholder", ",", "parent_object", "=", "parent_object", ",", "template_name", "=", "template_name", ",", "cachable", "=", "cachable", ",", "limit_parent_language", "=", "limit_parent_language", ",", "fallback_language", "=", "fallback_language", ")", "# Wrap the result after it's stored in the cache.", "if", "markers", ".", "is_edit_mode", "(", "request", ")", ":", "output", ".", "html", "=", "markers", ".", "wrap_placeholder_output", "(", "output", ".", "html", ",", "placeholder", ")", "return", "output" ]
Render a :class:`~fluent_contents.models.Placeholder` object. Returns a :class:`~fluent_contents.models.ContentItemOutput` object which contains the HTML output and :class:`~django.forms.Media` object. This function also caches the complete output of the placeholder when all individual items are cacheable. :param request: The current request object. :type request: :class:`~django.http.HttpRequest` :param placeholder: The placeholder object. :type placeholder: :class:`~fluent_contents.models.Placeholder` :param parent_object: Optional, the parent object of the placeholder (already implied by the placeholder) :param template_name: Optional template name used to concatenate the placeholder output. :type template_name: str | None :param cachable: Whether the output is cachable, otherwise the full output will not be cached. Default: False when using a template, True otherwise. :type cachable: bool | None :param limit_parent_language: Whether the items should be limited to the parent language. :type limit_parent_language: bool :param fallback_language: The fallback language to use if there are no items in the current language. Passing ``True`` uses the default :ref:`FLUENT_CONTENTS_DEFAULT_LANGUAGE_CODE`. :type fallback_language: bool/str :rtype: :class:`~fluent_contents.models.ContentItemOutput`
[ "Render", "a", ":", "class", ":", "~fluent_contents", ".", "models", ".", "Placeholder", "object", ".", "Returns", "a", ":", "class", ":", "~fluent_contents", ".", "models", ".", "ContentItemOutput", "object", "which", "contains", "the", "HTML", "output", "and", ":", "class", ":", "~django", ".", "forms", ".", "Media", "object", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/rendering/main.py#L27-L65
django-fluent/django-fluent-contents
fluent_contents/rendering/main.py
render_content_items
def render_content_items(request, items, template_name=None, cachable=None): """ Render a list of :class:`~fluent_contents.models.ContentItem` objects as HTML string. This is a variation of the :func:`render_placeholder` function. Note that the items are not filtered in any way by parent or language. The items are rendered as-is. :param request: The current request object. :type request: :class:`~django.http.HttpRequest` :param items: The list or queryset of objects to render. Passing a queryset is preferred. :type items: list or queryset of :class:`~fluent_contents.models.ContentItem`. :param template_name: Optional template name used to concatenate the placeholder output. :type template_name: Optional[str] :param cachable: Whether the output is cachable, otherwise the full output will not be cached. Default: False when using a template, True otherwise. :type cachable: Optional[bool] :rtype: :class:`~fluent_contents.models.ContentItemOutput` """ if not items: output = ContentItemOutput(mark_safe(u"<!-- no items to render -->")) else: output = RenderingPipe(request).render_items( placeholder=None, items=items, parent_object=None, template_name=template_name, cachable=cachable ) # Wrap the result after it's stored in the cache. if markers.is_edit_mode(request): output.html = markers.wrap_anonymous_output(output.html) return output
python
def render_content_items(request, items, template_name=None, cachable=None): """ Render a list of :class:`~fluent_contents.models.ContentItem` objects as HTML string. This is a variation of the :func:`render_placeholder` function. Note that the items are not filtered in any way by parent or language. The items are rendered as-is. :param request: The current request object. :type request: :class:`~django.http.HttpRequest` :param items: The list or queryset of objects to render. Passing a queryset is preferred. :type items: list or queryset of :class:`~fluent_contents.models.ContentItem`. :param template_name: Optional template name used to concatenate the placeholder output. :type template_name: Optional[str] :param cachable: Whether the output is cachable, otherwise the full output will not be cached. Default: False when using a template, True otherwise. :type cachable: Optional[bool] :rtype: :class:`~fluent_contents.models.ContentItemOutput` """ if not items: output = ContentItemOutput(mark_safe(u"<!-- no items to render -->")) else: output = RenderingPipe(request).render_items( placeholder=None, items=items, parent_object=None, template_name=template_name, cachable=cachable ) # Wrap the result after it's stored in the cache. if markers.is_edit_mode(request): output.html = markers.wrap_anonymous_output(output.html) return output
[ "def", "render_content_items", "(", "request", ",", "items", ",", "template_name", "=", "None", ",", "cachable", "=", "None", ")", ":", "if", "not", "items", ":", "output", "=", "ContentItemOutput", "(", "mark_safe", "(", "u\"<!-- no items to render -->\"", ")", ")", "else", ":", "output", "=", "RenderingPipe", "(", "request", ")", ".", "render_items", "(", "placeholder", "=", "None", ",", "items", "=", "items", ",", "parent_object", "=", "None", ",", "template_name", "=", "template_name", ",", "cachable", "=", "cachable", ")", "# Wrap the result after it's stored in the cache.", "if", "markers", ".", "is_edit_mode", "(", "request", ")", ":", "output", ".", "html", "=", "markers", ".", "wrap_anonymous_output", "(", "output", ".", "html", ")", "return", "output" ]
Render a list of :class:`~fluent_contents.models.ContentItem` objects as HTML string. This is a variation of the :func:`render_placeholder` function. Note that the items are not filtered in any way by parent or language. The items are rendered as-is. :param request: The current request object. :type request: :class:`~django.http.HttpRequest` :param items: The list or queryset of objects to render. Passing a queryset is preferred. :type items: list or queryset of :class:`~fluent_contents.models.ContentItem`. :param template_name: Optional template name used to concatenate the placeholder output. :type template_name: Optional[str] :param cachable: Whether the output is cachable, otherwise the full output will not be cached. Default: False when using a template, True otherwise. :type cachable: Optional[bool] :rtype: :class:`~fluent_contents.models.ContentItemOutput`
[ "Render", "a", "list", "of", ":", "class", ":", "~fluent_contents", ".", "models", ".", "ContentItem", "objects", "as", "HTML", "string", ".", "This", "is", "a", "variation", "of", "the", ":", "func", ":", "render_placeholder", "function", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/rendering/main.py#L68-L103
django-fluent/django-fluent-contents
fluent_contents/rendering/main.py
render_placeholder_search_text
def render_placeholder_search_text(placeholder, fallback_language=None): """ Render a :class:`~fluent_contents.models.Placeholder` object to search text. This text can be used by an indexer (e.g. haystack) to produce content search for a parent object. :param placeholder: The placeholder object. :type placeholder: :class:`~fluent_contents.models.Placeholder` :param fallback_language: The fallback language to use if there are no items in the current language. Passing ``True`` uses the default :ref:`FLUENT_CONTENTS_DEFAULT_LANGUAGE_CODE`. :type fallback_language: bool|str :rtype: str """ parent_object = placeholder.parent # this is a cached lookup thanks to PlaceholderFieldDescriptor language = get_parent_language_code(parent_object) output = SearchRenderingPipe(language).render_placeholder( placeholder=placeholder, parent_object=parent_object, fallback_language=fallback_language ) return output.html
python
def render_placeholder_search_text(placeholder, fallback_language=None): """ Render a :class:`~fluent_contents.models.Placeholder` object to search text. This text can be used by an indexer (e.g. haystack) to produce content search for a parent object. :param placeholder: The placeholder object. :type placeholder: :class:`~fluent_contents.models.Placeholder` :param fallback_language: The fallback language to use if there are no items in the current language. Passing ``True`` uses the default :ref:`FLUENT_CONTENTS_DEFAULT_LANGUAGE_CODE`. :type fallback_language: bool|str :rtype: str """ parent_object = placeholder.parent # this is a cached lookup thanks to PlaceholderFieldDescriptor language = get_parent_language_code(parent_object) output = SearchRenderingPipe(language).render_placeholder( placeholder=placeholder, parent_object=parent_object, fallback_language=fallback_language ) return output.html
[ "def", "render_placeholder_search_text", "(", "placeholder", ",", "fallback_language", "=", "None", ")", ":", "parent_object", "=", "placeholder", ".", "parent", "# this is a cached lookup thanks to PlaceholderFieldDescriptor", "language", "=", "get_parent_language_code", "(", "parent_object", ")", "output", "=", "SearchRenderingPipe", "(", "language", ")", ".", "render_placeholder", "(", "placeholder", "=", "placeholder", ",", "parent_object", "=", "parent_object", ",", "fallback_language", "=", "fallback_language", ")", "return", "output", ".", "html" ]
Render a :class:`~fluent_contents.models.Placeholder` object to search text. This text can be used by an indexer (e.g. haystack) to produce content search for a parent object. :param placeholder: The placeholder object. :type placeholder: :class:`~fluent_contents.models.Placeholder` :param fallback_language: The fallback language to use if there are no items in the current language. Passing ``True`` uses the default :ref:`FLUENT_CONTENTS_DEFAULT_LANGUAGE_CODE`. :type fallback_language: bool|str :rtype: str
[ "Render", "a", ":", "class", ":", "~fluent_contents", ".", "models", ".", "Placeholder", "object", "to", "search", "text", ".", "This", "text", "can", "be", "used", "by", "an", "indexer", "(", "e", ".", "g", ".", "haystack", ")", "to", "produce", "content", "search", "for", "a", "parent", "object", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/rendering/main.py#L106-L125
django-fluent/django-fluent-contents
fluent_contents/forms/widgets.py
PlaceholderFieldWidget.render
def render(self, name, value, attrs=None, renderer=None): """ Render the placeholder field. """ other_instance_languages = None if value and value != "-DUMMY-": if get_parent_language_code(self.parent_object): # Parent is a multilingual object, provide information # for the copy dialog. other_instance_languages = get_parent_active_language_choices( self.parent_object, exclude_current=True) context = { 'cp_plugin_list': list(self.plugins), 'placeholder_id': '', 'placeholder_slot': self.slot, 'other_instance_languages': other_instance_languages, } return mark_safe(render_to_string('admin/fluent_contents/placeholderfield/widget.html', context))
python
def render(self, name, value, attrs=None, renderer=None): """ Render the placeholder field. """ other_instance_languages = None if value and value != "-DUMMY-": if get_parent_language_code(self.parent_object): # Parent is a multilingual object, provide information # for the copy dialog. other_instance_languages = get_parent_active_language_choices( self.parent_object, exclude_current=True) context = { 'cp_plugin_list': list(self.plugins), 'placeholder_id': '', 'placeholder_slot': self.slot, 'other_instance_languages': other_instance_languages, } return mark_safe(render_to_string('admin/fluent_contents/placeholderfield/widget.html', context))
[ "def", "render", "(", "self", ",", "name", ",", "value", ",", "attrs", "=", "None", ",", "renderer", "=", "None", ")", ":", "other_instance_languages", "=", "None", "if", "value", "and", "value", "!=", "\"-DUMMY-\"", ":", "if", "get_parent_language_code", "(", "self", ".", "parent_object", ")", ":", "# Parent is a multilingual object, provide information", "# for the copy dialog.", "other_instance_languages", "=", "get_parent_active_language_choices", "(", "self", ".", "parent_object", ",", "exclude_current", "=", "True", ")", "context", "=", "{", "'cp_plugin_list'", ":", "list", "(", "self", ".", "plugins", ")", ",", "'placeholder_id'", ":", "''", ",", "'placeholder_slot'", ":", "self", ".", "slot", ",", "'other_instance_languages'", ":", "other_instance_languages", ",", "}", "return", "mark_safe", "(", "render_to_string", "(", "'admin/fluent_contents/placeholderfield/widget.html'", ",", "context", ")", ")" ]
Render the placeholder field.
[ "Render", "the", "placeholder", "field", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/forms/widgets.py#L46-L64
django-fluent/django-fluent-contents
fluent_contents/forms/widgets.py
PlaceholderFieldWidget.plugins
def plugins(self): """ Get the set of plugins that this widget should display. """ from fluent_contents import extensions # Avoid circular reference because __init__.py imports subfolders too if self._plugins is None: return extensions.plugin_pool.get_plugins() else: return extensions.plugin_pool.get_plugins_by_name(*self._plugins)
python
def plugins(self): """ Get the set of plugins that this widget should display. """ from fluent_contents import extensions # Avoid circular reference because __init__.py imports subfolders too if self._plugins is None: return extensions.plugin_pool.get_plugins() else: return extensions.plugin_pool.get_plugins_by_name(*self._plugins)
[ "def", "plugins", "(", "self", ")", ":", "from", "fluent_contents", "import", "extensions", "# Avoid circular reference because __init__.py imports subfolders too", "if", "self", ".", "_plugins", "is", "None", ":", "return", "extensions", ".", "plugin_pool", ".", "get_plugins", "(", ")", "else", ":", "return", "extensions", ".", "plugin_pool", ".", "get_plugins_by_name", "(", "*", "self", ".", "_plugins", ")" ]
Get the set of plugins that this widget should display.
[ "Get", "the", "set", "of", "plugins", "that", "this", "widget", "should", "display", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/forms/widgets.py#L67-L75
django-fluent/django-fluent-contents
fluent_contents/middleware.py
_new_render
def _new_render(response): """ Decorator for the TemplateResponse.render() function """ orig_render = response.__class__.render # No arguments, is used as bound method. def _inner_render(): try: return orig_render(response) except HttpRedirectRequest as e: return HttpResponseRedirect(e.url, status=e.status) return _inner_render
python
def _new_render(response): """ Decorator for the TemplateResponse.render() function """ orig_render = response.__class__.render # No arguments, is used as bound method. def _inner_render(): try: return orig_render(response) except HttpRedirectRequest as e: return HttpResponseRedirect(e.url, status=e.status) return _inner_render
[ "def", "_new_render", "(", "response", ")", ":", "orig_render", "=", "response", ".", "__class__", ".", "render", "# No arguments, is used as bound method.", "def", "_inner_render", "(", ")", ":", "try", ":", "return", "orig_render", "(", "response", ")", "except", "HttpRedirectRequest", "as", "e", ":", "return", "HttpResponseRedirect", "(", "e", ".", "url", ",", "status", "=", "e", ".", "status", ")", "return", "_inner_render" ]
Decorator for the TemplateResponse.render() function
[ "Decorator", "for", "the", "TemplateResponse", ".", "render", "()", "function" ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/middleware.py#L43-L56
django-fluent/django-fluent-contents
fluent_contents/middleware.py
HttpRedirectRequestMiddleware.process_exception
def process_exception(self, request, exception): """ Return a redirect response for the :class:`~fluent_contents.extensions.HttpRedirectRequest` """ if isinstance(exception, HttpRedirectRequest): return HttpResponseRedirect(exception.url, status=exception.status) else: return None
python
def process_exception(self, request, exception): """ Return a redirect response for the :class:`~fluent_contents.extensions.HttpRedirectRequest` """ if isinstance(exception, HttpRedirectRequest): return HttpResponseRedirect(exception.url, status=exception.status) else: return None
[ "def", "process_exception", "(", "self", ",", "request", ",", "exception", ")", ":", "if", "isinstance", "(", "exception", ",", "HttpRedirectRequest", ")", ":", "return", "HttpResponseRedirect", "(", "exception", ".", "url", ",", "status", "=", "exception", ".", "status", ")", "else", ":", "return", "None" ]
Return a redirect response for the :class:`~fluent_contents.extensions.HttpRedirectRequest`
[ "Return", "a", "redirect", "response", "for", "the", ":", "class", ":", "~fluent_contents", ".", "extensions", ".", "HttpRedirectRequest" ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/middleware.py#L23-L30
django-fluent/django-fluent-contents
fluent_contents/plugins/markup/backend.py
render_text
def render_text(text, language=None): """ Render the text, reuses the template filters provided by Django. """ # Get the filter text_filter = SUPPORTED_LANGUAGES.get(language, None) if not text_filter: raise ImproperlyConfigured("markup filter does not exist: {0}. Valid options are: {1}".format( language, ', '.join(list(SUPPORTED_LANGUAGES.keys())) )) # Convert. return text_filter(text)
python
def render_text(text, language=None): """ Render the text, reuses the template filters provided by Django. """ # Get the filter text_filter = SUPPORTED_LANGUAGES.get(language, None) if not text_filter: raise ImproperlyConfigured("markup filter does not exist: {0}. Valid options are: {1}".format( language, ', '.join(list(SUPPORTED_LANGUAGES.keys())) )) # Convert. return text_filter(text)
[ "def", "render_text", "(", "text", ",", "language", "=", "None", ")", ":", "# Get the filter", "text_filter", "=", "SUPPORTED_LANGUAGES", ".", "get", "(", "language", ",", "None", ")", "if", "not", "text_filter", ":", "raise", "ImproperlyConfigured", "(", "\"markup filter does not exist: {0}. Valid options are: {1}\"", ".", "format", "(", "language", ",", "', '", ".", "join", "(", "list", "(", "SUPPORTED_LANGUAGES", ".", "keys", "(", ")", ")", ")", ")", ")", "# Convert.", "return", "text_filter", "(", "text", ")" ]
Render the text, reuses the template filters provided by Django.
[ "Render", "the", "text", "reuses", "the", "template", "filters", "provided", "by", "Django", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/plugins/markup/backend.py#L61-L73
django-fluent/django-fluent-contents
fluent_contents/rendering/core.py
ResultTracker.fetch_remaining_instances
def fetch_remaining_instances(self): """Read the derived table data for all objects tracked as remaining (=not found in the cache).""" if self.remaining_items: self.remaining_items = ContentItem.objects.get_real_instances(self.remaining_items)
python
def fetch_remaining_instances(self): """Read the derived table data for all objects tracked as remaining (=not found in the cache).""" if self.remaining_items: self.remaining_items = ContentItem.objects.get_real_instances(self.remaining_items)
[ "def", "fetch_remaining_instances", "(", "self", ")", ":", "if", "self", ".", "remaining_items", ":", "self", ".", "remaining_items", "=", "ContentItem", ".", "objects", ".", "get_real_instances", "(", "self", ".", "remaining_items", ")" ]
Read the derived table data for all objects tracked as remaining (=not found in the cache).
[ "Read", "the", "derived", "table", "data", "for", "all", "objects", "tracked", "as", "remaining", "(", "=", "not", "found", "in", "the", "cache", ")", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/rendering/core.py#L98-L101
django-fluent/django-fluent-contents
fluent_contents/rendering/core.py
ResultTracker.get_output
def get_output(self, include_exceptions=False): """ Return the output in the correct ordering. :rtype: list[Tuple[contentitem, O]] """ # Order all rendered items in the correct sequence. # Don't assume the derived tables are in perfect shape, hence the dict + KeyError handling. # The derived tables could be truncated/reset or store_output() could be omitted. ordered_output = [] for item_id in self.output_ordering: contentitem = self.item_source[item_id] try: output = self.item_output[item_id] except KeyError: # The item was not rendered! if not include_exceptions: continue output = self.MISSING else: # Filter exceptions out. if not include_exceptions: if isinstance(output, Exception) or output is self.SKIPPED: continue ordered_output.append((contentitem, output)) return ordered_output
python
def get_output(self, include_exceptions=False): """ Return the output in the correct ordering. :rtype: list[Tuple[contentitem, O]] """ # Order all rendered items in the correct sequence. # Don't assume the derived tables are in perfect shape, hence the dict + KeyError handling. # The derived tables could be truncated/reset or store_output() could be omitted. ordered_output = [] for item_id in self.output_ordering: contentitem = self.item_source[item_id] try: output = self.item_output[item_id] except KeyError: # The item was not rendered! if not include_exceptions: continue output = self.MISSING else: # Filter exceptions out. if not include_exceptions: if isinstance(output, Exception) or output is self.SKIPPED: continue ordered_output.append((contentitem, output)) return ordered_output
[ "def", "get_output", "(", "self", ",", "include_exceptions", "=", "False", ")", ":", "# Order all rendered items in the correct sequence.", "# Don't assume the derived tables are in perfect shape, hence the dict + KeyError handling.", "# The derived tables could be truncated/reset or store_output() could be omitted.", "ordered_output", "=", "[", "]", "for", "item_id", "in", "self", ".", "output_ordering", ":", "contentitem", "=", "self", ".", "item_source", "[", "item_id", "]", "try", ":", "output", "=", "self", ".", "item_output", "[", "item_id", "]", "except", "KeyError", ":", "# The item was not rendered!", "if", "not", "include_exceptions", ":", "continue", "output", "=", "self", ".", "MISSING", "else", ":", "# Filter exceptions out.", "if", "not", "include_exceptions", ":", "if", "isinstance", "(", "output", ",", "Exception", ")", "or", "output", "is", "self", ".", "SKIPPED", ":", "continue", "ordered_output", ".", "append", "(", "(", "contentitem", ",", "output", ")", ")", "return", "ordered_output" ]
Return the output in the correct ordering. :rtype: list[Tuple[contentitem, O]]
[ "Return", "the", "output", "in", "the", "correct", "ordering", ".", ":", "rtype", ":", "list", "[", "Tuple", "[", "contentitem", "O", "]]" ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/rendering/core.py#L110-L137
django-fluent/django-fluent-contents
fluent_contents/rendering/core.py
RenderingPipe.render_items
def render_items(self, placeholder, items, parent_object=None, template_name=None, cachable=None): """ The main rendering sequence. """ # Unless it was done before, disable polymorphic effects. is_queryset = False if hasattr(items, "non_polymorphic"): is_queryset = True if not items.polymorphic_disabled and items._result_cache is None: items = items.non_polymorphic() # See if the queryset contained anything. # This test is moved here, to prevent earlier query execution. if not items: logger.debug("- no items in placeholder '%s'", get_placeholder_debug_name(placeholder)) return ContentItemOutput(mark_safe(u"<!-- no items in placeholder '{0}' -->".format(escape(get_placeholder_name(placeholder)))), cacheable=True) # Tracked data during rendering: result = self.result_class( request=self.request, parent_object=parent_object, placeholder=placeholder, items=items, all_cacheable=self._can_cache_merged_output(template_name, cachable), ) if self.edit_mode: result.set_uncachable() if is_queryset: # Phase 1: get cached output self._fetch_cached_output(items, result=result) result.fetch_remaining_instances() else: # The items is either a list of manually created items, or it's a QuerySet. # Can't prevent reading the subclasses only, so don't bother with caching here. result.add_remaining_list(items) # Start the actual rendering of remaining items. if result.remaining_items: # Phase 2: render remaining items self._render_uncached_items(result.remaining_items, result=result) # And merge all items together. return self.merge_output(result, items, template_name)
python
def render_items(self, placeholder, items, parent_object=None, template_name=None, cachable=None): """ The main rendering sequence. """ # Unless it was done before, disable polymorphic effects. is_queryset = False if hasattr(items, "non_polymorphic"): is_queryset = True if not items.polymorphic_disabled and items._result_cache is None: items = items.non_polymorphic() # See if the queryset contained anything. # This test is moved here, to prevent earlier query execution. if not items: logger.debug("- no items in placeholder '%s'", get_placeholder_debug_name(placeholder)) return ContentItemOutput(mark_safe(u"<!-- no items in placeholder '{0}' -->".format(escape(get_placeholder_name(placeholder)))), cacheable=True) # Tracked data during rendering: result = self.result_class( request=self.request, parent_object=parent_object, placeholder=placeholder, items=items, all_cacheable=self._can_cache_merged_output(template_name, cachable), ) if self.edit_mode: result.set_uncachable() if is_queryset: # Phase 1: get cached output self._fetch_cached_output(items, result=result) result.fetch_remaining_instances() else: # The items is either a list of manually created items, or it's a QuerySet. # Can't prevent reading the subclasses only, so don't bother with caching here. result.add_remaining_list(items) # Start the actual rendering of remaining items. if result.remaining_items: # Phase 2: render remaining items self._render_uncached_items(result.remaining_items, result=result) # And merge all items together. return self.merge_output(result, items, template_name)
[ "def", "render_items", "(", "self", ",", "placeholder", ",", "items", ",", "parent_object", "=", "None", ",", "template_name", "=", "None", ",", "cachable", "=", "None", ")", ":", "# Unless it was done before, disable polymorphic effects.", "is_queryset", "=", "False", "if", "hasattr", "(", "items", ",", "\"non_polymorphic\"", ")", ":", "is_queryset", "=", "True", "if", "not", "items", ".", "polymorphic_disabled", "and", "items", ".", "_result_cache", "is", "None", ":", "items", "=", "items", ".", "non_polymorphic", "(", ")", "# See if the queryset contained anything.", "# This test is moved here, to prevent earlier query execution.", "if", "not", "items", ":", "logger", ".", "debug", "(", "\"- no items in placeholder '%s'\"", ",", "get_placeholder_debug_name", "(", "placeholder", ")", ")", "return", "ContentItemOutput", "(", "mark_safe", "(", "u\"<!-- no items in placeholder '{0}' -->\"", ".", "format", "(", "escape", "(", "get_placeholder_name", "(", "placeholder", ")", ")", ")", ")", ",", "cacheable", "=", "True", ")", "# Tracked data during rendering:", "result", "=", "self", ".", "result_class", "(", "request", "=", "self", ".", "request", ",", "parent_object", "=", "parent_object", ",", "placeholder", "=", "placeholder", ",", "items", "=", "items", ",", "all_cacheable", "=", "self", ".", "_can_cache_merged_output", "(", "template_name", ",", "cachable", ")", ",", ")", "if", "self", ".", "edit_mode", ":", "result", ".", "set_uncachable", "(", ")", "if", "is_queryset", ":", "# Phase 1: get cached output", "self", ".", "_fetch_cached_output", "(", "items", ",", "result", "=", "result", ")", "result", ".", "fetch_remaining_instances", "(", ")", "else", ":", "# The items is either a list of manually created items, or it's a QuerySet.", "# Can't prevent reading the subclasses only, so don't bother with caching here.", "result", ".", "add_remaining_list", "(", "items", ")", "# Start the actual rendering of remaining items.", "if", "result", ".", "remaining_items", ":", "# Phase 2: render remaining items", "self", ".", "_render_uncached_items", "(", "result", ".", "remaining_items", ",", "result", "=", "result", ")", "# And merge all items together.", "return", "self", ".", "merge_output", "(", "result", ",", "items", ",", "template_name", ")" ]
The main rendering sequence.
[ "The", "main", "rendering", "sequence", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/rendering/core.py#L167-L210
django-fluent/django-fluent-contents
fluent_contents/rendering/core.py
RenderingPipe._fetch_cached_output
def _fetch_cached_output(self, items, result): """ First try to fetch all items from the cache. The items are 'non-polymorphic', so only point to their base class. If these are found, there is no need to query the derived data from the database. """ if not appsettings.FLUENT_CONTENTS_CACHE_OUTPUT or not self.use_cached_output: result.add_remaining_list(items) return for contentitem in items: result.add_ordering(contentitem) output = None try: plugin = contentitem.plugin except PluginNotFound as ex: result.store_exception(contentitem, ex) # Will deal with that later. logger.debug("- item #%s has no matching plugin: %s", contentitem.pk, str(ex)) continue # Respect the cache output setting of the plugin if self.can_use_cached_output(contentitem): result.add_plugin_timeout(plugin) output = plugin.get_cached_output(result.placeholder_name, contentitem) # Support transition to new output format. if output is not None and not isinstance(output, ContentItemOutput): output = None logger.debug("Flushed cached output of {0}#{1} to store new ContentItemOutput format (key: {2})".format( plugin.type_name, contentitem.pk, get_placeholder_name(contentitem.placeholder) )) # For debugging, ignore cached values when the template is updated. if output and settings.DEBUG: cachekey = get_rendering_cache_key(result.placeholder_name, contentitem) if is_template_updated(self.request, contentitem, cachekey): output = None if output: result.store_output(contentitem, output) else: result.add_remaining(contentitem)
python
def _fetch_cached_output(self, items, result): """ First try to fetch all items from the cache. The items are 'non-polymorphic', so only point to their base class. If these are found, there is no need to query the derived data from the database. """ if not appsettings.FLUENT_CONTENTS_CACHE_OUTPUT or not self.use_cached_output: result.add_remaining_list(items) return for contentitem in items: result.add_ordering(contentitem) output = None try: plugin = contentitem.plugin except PluginNotFound as ex: result.store_exception(contentitem, ex) # Will deal with that later. logger.debug("- item #%s has no matching plugin: %s", contentitem.pk, str(ex)) continue # Respect the cache output setting of the plugin if self.can_use_cached_output(contentitem): result.add_plugin_timeout(plugin) output = plugin.get_cached_output(result.placeholder_name, contentitem) # Support transition to new output format. if output is not None and not isinstance(output, ContentItemOutput): output = None logger.debug("Flushed cached output of {0}#{1} to store new ContentItemOutput format (key: {2})".format( plugin.type_name, contentitem.pk, get_placeholder_name(contentitem.placeholder) )) # For debugging, ignore cached values when the template is updated. if output and settings.DEBUG: cachekey = get_rendering_cache_key(result.placeholder_name, contentitem) if is_template_updated(self.request, contentitem, cachekey): output = None if output: result.store_output(contentitem, output) else: result.add_remaining(contentitem)
[ "def", "_fetch_cached_output", "(", "self", ",", "items", ",", "result", ")", ":", "if", "not", "appsettings", ".", "FLUENT_CONTENTS_CACHE_OUTPUT", "or", "not", "self", ".", "use_cached_output", ":", "result", ".", "add_remaining_list", "(", "items", ")", "return", "for", "contentitem", "in", "items", ":", "result", ".", "add_ordering", "(", "contentitem", ")", "output", "=", "None", "try", ":", "plugin", "=", "contentitem", ".", "plugin", "except", "PluginNotFound", "as", "ex", ":", "result", ".", "store_exception", "(", "contentitem", ",", "ex", ")", "# Will deal with that later.", "logger", ".", "debug", "(", "\"- item #%s has no matching plugin: %s\"", ",", "contentitem", ".", "pk", ",", "str", "(", "ex", ")", ")", "continue", "# Respect the cache output setting of the plugin", "if", "self", ".", "can_use_cached_output", "(", "contentitem", ")", ":", "result", ".", "add_plugin_timeout", "(", "plugin", ")", "output", "=", "plugin", ".", "get_cached_output", "(", "result", ".", "placeholder_name", ",", "contentitem", ")", "# Support transition to new output format.", "if", "output", "is", "not", "None", "and", "not", "isinstance", "(", "output", ",", "ContentItemOutput", ")", ":", "output", "=", "None", "logger", ".", "debug", "(", "\"Flushed cached output of {0}#{1} to store new ContentItemOutput format (key: {2})\"", ".", "format", "(", "plugin", ".", "type_name", ",", "contentitem", ".", "pk", ",", "get_placeholder_name", "(", "contentitem", ".", "placeholder", ")", ")", ")", "# For debugging, ignore cached values when the template is updated.", "if", "output", "and", "settings", ".", "DEBUG", ":", "cachekey", "=", "get_rendering_cache_key", "(", "result", ".", "placeholder_name", ",", "contentitem", ")", "if", "is_template_updated", "(", "self", ".", "request", ",", "contentitem", ",", "cachekey", ")", ":", "output", "=", "None", "if", "output", ":", "result", ".", "store_output", "(", "contentitem", ",", "output", ")", "else", ":", "result", ".", "add_remaining", "(", "contentitem", ")" ]
First try to fetch all items from the cache. The items are 'non-polymorphic', so only point to their base class. If these are found, there is no need to query the derived data from the database.
[ "First", "try", "to", "fetch", "all", "items", "from", "the", "cache", ".", "The", "items", "are", "non", "-", "polymorphic", "so", "only", "point", "to", "their", "base", "class", ".", "If", "these", "are", "found", "there", "is", "no", "need", "to", "query", "the", "derived", "data", "from", "the", "database", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/rendering/core.py#L212-L256
django-fluent/django-fluent-contents
fluent_contents/rendering/core.py
RenderingPipe.can_use_cached_output
def can_use_cached_output(self, contentitem): """ Tell whether the code should try reading cached output """ plugin = contentitem.plugin return appsettings.FLUENT_CONTENTS_CACHE_OUTPUT and plugin.cache_output and contentitem.pk
python
def can_use_cached_output(self, contentitem): """ Tell whether the code should try reading cached output """ plugin = contentitem.plugin return appsettings.FLUENT_CONTENTS_CACHE_OUTPUT and plugin.cache_output and contentitem.pk
[ "def", "can_use_cached_output", "(", "self", ",", "contentitem", ")", ":", "plugin", "=", "contentitem", ".", "plugin", "return", "appsettings", ".", "FLUENT_CONTENTS_CACHE_OUTPUT", "and", "plugin", ".", "cache_output", "and", "contentitem", ".", "pk" ]
Tell whether the code should try reading cached output
[ "Tell", "whether", "the", "code", "should", "try", "reading", "cached", "output" ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/rendering/core.py#L258-L263
django-fluent/django-fluent-contents
fluent_contents/rendering/core.py
RenderingPipe._render_uncached_items
def _render_uncached_items(self, items, result): """ Render a list of items, that didn't exist in the cache yet. """ for contentitem in items: # Render the item. # Allow derived classes to skip it. try: output = self.render_item(contentitem) except PluginNotFound as ex: result.store_exception(contentitem, ex) logger.debug("- item #%s has no matching plugin: %s", contentitem.pk, str(ex)) continue except SkipItem: result.set_skipped(contentitem) continue # Try caching it. self._try_cache_output(contentitem, output, result=result) if self.edit_mode: output.html = markers.wrap_contentitem_output(output.html, contentitem) result.store_output(contentitem, output)
python
def _render_uncached_items(self, items, result): """ Render a list of items, that didn't exist in the cache yet. """ for contentitem in items: # Render the item. # Allow derived classes to skip it. try: output = self.render_item(contentitem) except PluginNotFound as ex: result.store_exception(contentitem, ex) logger.debug("- item #%s has no matching plugin: %s", contentitem.pk, str(ex)) continue except SkipItem: result.set_skipped(contentitem) continue # Try caching it. self._try_cache_output(contentitem, output, result=result) if self.edit_mode: output.html = markers.wrap_contentitem_output(output.html, contentitem) result.store_output(contentitem, output)
[ "def", "_render_uncached_items", "(", "self", ",", "items", ",", "result", ")", ":", "for", "contentitem", "in", "items", ":", "# Render the item.", "# Allow derived classes to skip it.", "try", ":", "output", "=", "self", ".", "render_item", "(", "contentitem", ")", "except", "PluginNotFound", "as", "ex", ":", "result", ".", "store_exception", "(", "contentitem", ",", "ex", ")", "logger", ".", "debug", "(", "\"- item #%s has no matching plugin: %s\"", ",", "contentitem", ".", "pk", ",", "str", "(", "ex", ")", ")", "continue", "except", "SkipItem", ":", "result", ".", "set_skipped", "(", "contentitem", ")", "continue", "# Try caching it.", "self", ".", "_try_cache_output", "(", "contentitem", ",", "output", ",", "result", "=", "result", ")", "if", "self", ".", "edit_mode", ":", "output", ".", "html", "=", "markers", ".", "wrap_contentitem_output", "(", "output", ".", "html", ",", "contentitem", ")", "result", ".", "store_output", "(", "contentitem", ",", "output", ")" ]
Render a list of items, that didn't exist in the cache yet.
[ "Render", "a", "list", "of", "items", "that", "didn", "t", "exist", "in", "the", "cache", "yet", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/rendering/core.py#L265-L287
django-fluent/django-fluent-contents
fluent_contents/rendering/core.py
RenderingPipe.render_item
def render_item(self, contentitem): """ Render the individual item. May raise :class:`SkipItem` to ignore an item. """ render_language = get_render_language(contentitem) with smart_override(render_language): # Plugin output is likely HTML, but it should be placed in mark_safe() to raise awareness about escaping. # This is just like Django's Input.render() and unlike Node.render(). return contentitem.plugin._render_contentitem(self.request, contentitem)
python
def render_item(self, contentitem): """ Render the individual item. May raise :class:`SkipItem` to ignore an item. """ render_language = get_render_language(contentitem) with smart_override(render_language): # Plugin output is likely HTML, but it should be placed in mark_safe() to raise awareness about escaping. # This is just like Django's Input.render() and unlike Node.render(). return contentitem.plugin._render_contentitem(self.request, contentitem)
[ "def", "render_item", "(", "self", ",", "contentitem", ")", ":", "render_language", "=", "get_render_language", "(", "contentitem", ")", "with", "smart_override", "(", "render_language", ")", ":", "# Plugin output is likely HTML, but it should be placed in mark_safe() to raise awareness about escaping.", "# This is just like Django's Input.render() and unlike Node.render().", "return", "contentitem", ".", "plugin", ".", "_render_contentitem", "(", "self", ".", "request", ",", "contentitem", ")" ]
Render the individual item. May raise :class:`SkipItem` to ignore an item.
[ "Render", "the", "individual", "item", ".", "May", "raise", ":", "class", ":", "SkipItem", "to", "ignore", "an", "item", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/rendering/core.py#L289-L298
django-fluent/django-fluent-contents
fluent_contents/rendering/core.py
RenderingPipe.merge_output
def merge_output(self, result, items, template_name): """ Combine all rendered items. Allow rendering the items with a template, to inserting separators or nice start/end code. """ html_output, media = self.get_html_output(result, items) if not template_name: merged_html = mark_safe(u''.join(html_output)) else: context = { 'contentitems': list(zip(items, html_output)), 'parent_object': result.parent_object, # Can be None 'edit_mode': self.edit_mode, } context = PluginContext(self.request, context) merged_html = render_to_string(template_name, context.flatten()) return ContentItemOutput(merged_html, media, cacheable=result.all_cacheable, cache_timeout=result.all_timeout)
python
def merge_output(self, result, items, template_name): """ Combine all rendered items. Allow rendering the items with a template, to inserting separators or nice start/end code. """ html_output, media = self.get_html_output(result, items) if not template_name: merged_html = mark_safe(u''.join(html_output)) else: context = { 'contentitems': list(zip(items, html_output)), 'parent_object': result.parent_object, # Can be None 'edit_mode': self.edit_mode, } context = PluginContext(self.request, context) merged_html = render_to_string(template_name, context.flatten()) return ContentItemOutput(merged_html, media, cacheable=result.all_cacheable, cache_timeout=result.all_timeout)
[ "def", "merge_output", "(", "self", ",", "result", ",", "items", ",", "template_name", ")", ":", "html_output", ",", "media", "=", "self", ".", "get_html_output", "(", "result", ",", "items", ")", "if", "not", "template_name", ":", "merged_html", "=", "mark_safe", "(", "u''", ".", "join", "(", "html_output", ")", ")", "else", ":", "context", "=", "{", "'contentitems'", ":", "list", "(", "zip", "(", "items", ",", "html_output", ")", ")", ",", "'parent_object'", ":", "result", ".", "parent_object", ",", "# Can be None", "'edit_mode'", ":", "self", ".", "edit_mode", ",", "}", "context", "=", "PluginContext", "(", "self", ".", "request", ",", "context", ")", "merged_html", "=", "render_to_string", "(", "template_name", ",", "context", ".", "flatten", "(", ")", ")", "return", "ContentItemOutput", "(", "merged_html", ",", "media", ",", "cacheable", "=", "result", ".", "all_cacheable", ",", "cache_timeout", "=", "result", ".", "all_timeout", ")" ]
Combine all rendered items. Allow rendering the items with a template, to inserting separators or nice start/end code.
[ "Combine", "all", "rendered", "items", ".", "Allow", "rendering", "the", "items", "with", "a", "template", "to", "inserting", "separators", "or", "nice", "start", "/", "end", "code", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/rendering/core.py#L337-L356
django-fluent/django-fluent-contents
fluent_contents/rendering/core.py
RenderingPipe.get_html_output
def get_html_output(self, result, items): """ Collect all HTML from the rendered items, in the correct ordering. The media is also collected in the same ordering, in case it's handled by django-compressor for example. """ html_output = [] merged_media = Media() for contentitem, output in result.get_output(include_exceptions=True): if output is ResultTracker.MISSING: # Likely get_real_instances() didn't return an item for it. # The get_real_instances() didn't return an item for the derived table. This happens when either: # 1. that table is truncated/reset, while there is still an entry in the base ContentItem table. # A query at the derived table happens every time the page is being rendered. # 2. the model was completely removed which means there is also a stale ContentType object. class_name = _get_stale_item_class_name(contentitem) html_output.append(mark_safe(u"<!-- Missing derived model for ContentItem #{id}: {cls}. -->\n".format(id=contentitem.pk, cls=class_name))) logger.warning("Missing derived model for ContentItem #{id}: {cls}.".format(id=contentitem.pk, cls=class_name)) elif isinstance(output, Exception): html_output.append(u'<!-- error: {0} -->\n'.format(str(output))) else: html_output.append(output.html) add_media(merged_media, output.media) return html_output, merged_media
python
def get_html_output(self, result, items): """ Collect all HTML from the rendered items, in the correct ordering. The media is also collected in the same ordering, in case it's handled by django-compressor for example. """ html_output = [] merged_media = Media() for contentitem, output in result.get_output(include_exceptions=True): if output is ResultTracker.MISSING: # Likely get_real_instances() didn't return an item for it. # The get_real_instances() didn't return an item for the derived table. This happens when either: # 1. that table is truncated/reset, while there is still an entry in the base ContentItem table. # A query at the derived table happens every time the page is being rendered. # 2. the model was completely removed which means there is also a stale ContentType object. class_name = _get_stale_item_class_name(contentitem) html_output.append(mark_safe(u"<!-- Missing derived model for ContentItem #{id}: {cls}. -->\n".format(id=contentitem.pk, cls=class_name))) logger.warning("Missing derived model for ContentItem #{id}: {cls}.".format(id=contentitem.pk, cls=class_name)) elif isinstance(output, Exception): html_output.append(u'<!-- error: {0} -->\n'.format(str(output))) else: html_output.append(output.html) add_media(merged_media, output.media) return html_output, merged_media
[ "def", "get_html_output", "(", "self", ",", "result", ",", "items", ")", ":", "html_output", "=", "[", "]", "merged_media", "=", "Media", "(", ")", "for", "contentitem", ",", "output", "in", "result", ".", "get_output", "(", "include_exceptions", "=", "True", ")", ":", "if", "output", "is", "ResultTracker", ".", "MISSING", ":", "# Likely get_real_instances() didn't return an item for it.", "# The get_real_instances() didn't return an item for the derived table. This happens when either:", "# 1. that table is truncated/reset, while there is still an entry in the base ContentItem table.", "# A query at the derived table happens every time the page is being rendered.", "# 2. the model was completely removed which means there is also a stale ContentType object.", "class_name", "=", "_get_stale_item_class_name", "(", "contentitem", ")", "html_output", ".", "append", "(", "mark_safe", "(", "u\"<!-- Missing derived model for ContentItem #{id}: {cls}. -->\\n\"", ".", "format", "(", "id", "=", "contentitem", ".", "pk", ",", "cls", "=", "class_name", ")", ")", ")", "logger", ".", "warning", "(", "\"Missing derived model for ContentItem #{id}: {cls}.\"", ".", "format", "(", "id", "=", "contentitem", ".", "pk", ",", "cls", "=", "class_name", ")", ")", "elif", "isinstance", "(", "output", ",", "Exception", ")", ":", "html_output", ".", "append", "(", "u'<!-- error: {0} -->\\n'", ".", "format", "(", "str", "(", "output", ")", ")", ")", "else", ":", "html_output", ".", "append", "(", "output", ".", "html", ")", "add_media", "(", "merged_media", ",", "output", ".", "media", ")", "return", "html_output", ",", "merged_media" ]
Collect all HTML from the rendered items, in the correct ordering. The media is also collected in the same ordering, in case it's handled by django-compressor for example.
[ "Collect", "all", "HTML", "from", "the", "rendered", "items", "in", "the", "correct", "ordering", ".", "The", "media", "is", "also", "collected", "in", "the", "same", "ordering", "in", "case", "it", "s", "handled", "by", "django", "-", "compressor", "for", "example", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/rendering/core.py#L358-L381
django-fluent/django-fluent-contents
fluent_contents/rendering/core.py
PlaceholderRenderingPipe.render_placeholder
def render_placeholder(self, placeholder, parent_object=None, template_name=None, cachable=None, limit_parent_language=True, fallback_language=None): """ The main rendering sequence for placeholders. This will do all the magic for caching, and call :func:`render_items` in the end. """ placeholder_name = get_placeholder_debug_name(placeholder) logger.debug("Rendering placeholder '%s'", placeholder_name) # Determine whether the placeholder can be cached. cachable = self._can_cache_merged_output(template_name, cachable) try_cache = cachable and self.may_cache_placeholders() logger.debug("- try_cache=%s cachable=%s template_name=%s", try_cache, cachable, template_name) if parent_object is None: # To support filtering the placeholders by parent language, the parent object needs to be known. # Fortunately, the PlaceholderFieldDescriptor makes sure this doesn't require an additional query. parent_object = placeholder.parent # Fetch the placeholder output from cache. language_code = get_parent_language_code(parent_object) cache_key = None output = None if try_cache: cache_key = get_placeholder_cache_key_for_parent(parent_object, placeholder.slot, language_code) output = cache.get(cache_key) if output: logger.debug("- fetched cached output") if output is None: # Get the items, and render them items, is_fallback = self._get_placeholder_items(placeholder, parent_object, limit_parent_language, fallback_language, try_cache) output = self.render_items(placeholder, items, parent_object, template_name, cachable) if is_fallback: # Caching fallbacks is not supported yet, # content could be rendered in a different gettext language domain. output.cacheable = False # Store the full-placeholder contents in the cache. if try_cache and output.cacheable: if output.cache_timeout is not DEFAULT_TIMEOUT: # The timeout is based on the minimal timeout used in plugins. cache.set(cache_key, output, output.cache_timeout) else: # Don't want to mix into the default 0/None issue. cache.set(cache_key, output) return output
python
def render_placeholder(self, placeholder, parent_object=None, template_name=None, cachable=None, limit_parent_language=True, fallback_language=None): """ The main rendering sequence for placeholders. This will do all the magic for caching, and call :func:`render_items` in the end. """ placeholder_name = get_placeholder_debug_name(placeholder) logger.debug("Rendering placeholder '%s'", placeholder_name) # Determine whether the placeholder can be cached. cachable = self._can_cache_merged_output(template_name, cachable) try_cache = cachable and self.may_cache_placeholders() logger.debug("- try_cache=%s cachable=%s template_name=%s", try_cache, cachable, template_name) if parent_object is None: # To support filtering the placeholders by parent language, the parent object needs to be known. # Fortunately, the PlaceholderFieldDescriptor makes sure this doesn't require an additional query. parent_object = placeholder.parent # Fetch the placeholder output from cache. language_code = get_parent_language_code(parent_object) cache_key = None output = None if try_cache: cache_key = get_placeholder_cache_key_for_parent(parent_object, placeholder.slot, language_code) output = cache.get(cache_key) if output: logger.debug("- fetched cached output") if output is None: # Get the items, and render them items, is_fallback = self._get_placeholder_items(placeholder, parent_object, limit_parent_language, fallback_language, try_cache) output = self.render_items(placeholder, items, parent_object, template_name, cachable) if is_fallback: # Caching fallbacks is not supported yet, # content could be rendered in a different gettext language domain. output.cacheable = False # Store the full-placeholder contents in the cache. if try_cache and output.cacheable: if output.cache_timeout is not DEFAULT_TIMEOUT: # The timeout is based on the minimal timeout used in plugins. cache.set(cache_key, output, output.cache_timeout) else: # Don't want to mix into the default 0/None issue. cache.set(cache_key, output) return output
[ "def", "render_placeholder", "(", "self", ",", "placeholder", ",", "parent_object", "=", "None", ",", "template_name", "=", "None", ",", "cachable", "=", "None", ",", "limit_parent_language", "=", "True", ",", "fallback_language", "=", "None", ")", ":", "placeholder_name", "=", "get_placeholder_debug_name", "(", "placeholder", ")", "logger", ".", "debug", "(", "\"Rendering placeholder '%s'\"", ",", "placeholder_name", ")", "# Determine whether the placeholder can be cached.", "cachable", "=", "self", ".", "_can_cache_merged_output", "(", "template_name", ",", "cachable", ")", "try_cache", "=", "cachable", "and", "self", ".", "may_cache_placeholders", "(", ")", "logger", ".", "debug", "(", "\"- try_cache=%s cachable=%s template_name=%s\"", ",", "try_cache", ",", "cachable", ",", "template_name", ")", "if", "parent_object", "is", "None", ":", "# To support filtering the placeholders by parent language, the parent object needs to be known.", "# Fortunately, the PlaceholderFieldDescriptor makes sure this doesn't require an additional query.", "parent_object", "=", "placeholder", ".", "parent", "# Fetch the placeholder output from cache.", "language_code", "=", "get_parent_language_code", "(", "parent_object", ")", "cache_key", "=", "None", "output", "=", "None", "if", "try_cache", ":", "cache_key", "=", "get_placeholder_cache_key_for_parent", "(", "parent_object", ",", "placeholder", ".", "slot", ",", "language_code", ")", "output", "=", "cache", ".", "get", "(", "cache_key", ")", "if", "output", ":", "logger", ".", "debug", "(", "\"- fetched cached output\"", ")", "if", "output", "is", "None", ":", "# Get the items, and render them", "items", ",", "is_fallback", "=", "self", ".", "_get_placeholder_items", "(", "placeholder", ",", "parent_object", ",", "limit_parent_language", ",", "fallback_language", ",", "try_cache", ")", "output", "=", "self", ".", "render_items", "(", "placeholder", ",", "items", ",", "parent_object", ",", "template_name", ",", "cachable", ")", "if", "is_fallback", ":", "# Caching fallbacks is not supported yet,", "# content could be rendered in a different gettext language domain.", "output", ".", "cacheable", "=", "False", "# Store the full-placeholder contents in the cache.", "if", "try_cache", "and", "output", ".", "cacheable", ":", "if", "output", ".", "cache_timeout", "is", "not", "DEFAULT_TIMEOUT", ":", "# The timeout is based on the minimal timeout used in plugins.", "cache", ".", "set", "(", "cache_key", ",", "output", ",", "output", ".", "cache_timeout", ")", "else", ":", "# Don't want to mix into the default 0/None issue.", "cache", ".", "set", "(", "cache_key", ",", "output", ")", "return", "output" ]
The main rendering sequence for placeholders. This will do all the magic for caching, and call :func:`render_items` in the end.
[ "The", "main", "rendering", "sequence", "for", "placeholders", ".", "This", "will", "do", "all", "the", "magic", "for", "caching", "and", "call", ":", "func", ":", "render_items", "in", "the", "end", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/rendering/core.py#L389-L436
django-fluent/django-fluent-contents
fluent_contents/extensions/pluginpool.py
PluginPool.register
def register(self, plugin): """ Make a plugin known to the CMS. :param plugin: The plugin class, deriving from :class:`ContentPlugin`. :type plugin: :class:`ContentPlugin` The plugin will be instantiated once, just like Django does this with :class:`~django.contrib.admin.ModelAdmin` classes. If a plugin is already registered, this will raise a :class:`PluginAlreadyRegistered` exception. """ # Duck-Typing does not suffice here, avoid hard to debug problems by upfront checks. assert issubclass(plugin, ContentPlugin), "The plugin must inherit from `ContentPlugin`" assert plugin.model, "The plugin has no model defined" assert issubclass(plugin.model, ContentItem), "The plugin model must inherit from `ContentItem`" assert issubclass(plugin.form, ContentItemForm), "The plugin form must inherit from `ContentItemForm`" name = plugin.__name__ # using class here, no instance created yet. name = name.lower() if name in self.plugins: raise PluginAlreadyRegistered("{0}: a plugin with this name is already registered".format(name)) # Avoid registering 2 plugins to the exact same model. If you want to reuse code, use proxy models. if plugin.model in self._name_for_model: # Having 2 plugins for one model breaks ContentItem.plugin and the frontend code # that depends on using inline-model names instead of plugins. Good luck fixing that. # Better leave the model==plugin dependency for now. existing_plugin = self.plugins[self._name_for_model[plugin.model]] raise ModelAlreadyRegistered("Can't register the model {0} to {2}, it's already registered to {1}!".format( plugin.model.__name__, existing_plugin.name, plugin.__name__ )) # Make a single static instance, similar to ModelAdmin. plugin_instance = plugin() self.plugins[name] = plugin_instance self._name_for_model[plugin.model] = name # Track reverse for model.plugin link # Only update lazy indexes if already created if self._name_for_ctype_id is not None: self._name_for_ctype_id[plugin.type_id] = name return plugin
python
def register(self, plugin): """ Make a plugin known to the CMS. :param plugin: The plugin class, deriving from :class:`ContentPlugin`. :type plugin: :class:`ContentPlugin` The plugin will be instantiated once, just like Django does this with :class:`~django.contrib.admin.ModelAdmin` classes. If a plugin is already registered, this will raise a :class:`PluginAlreadyRegistered` exception. """ # Duck-Typing does not suffice here, avoid hard to debug problems by upfront checks. assert issubclass(plugin, ContentPlugin), "The plugin must inherit from `ContentPlugin`" assert plugin.model, "The plugin has no model defined" assert issubclass(plugin.model, ContentItem), "The plugin model must inherit from `ContentItem`" assert issubclass(plugin.form, ContentItemForm), "The plugin form must inherit from `ContentItemForm`" name = plugin.__name__ # using class here, no instance created yet. name = name.lower() if name in self.plugins: raise PluginAlreadyRegistered("{0}: a plugin with this name is already registered".format(name)) # Avoid registering 2 plugins to the exact same model. If you want to reuse code, use proxy models. if plugin.model in self._name_for_model: # Having 2 plugins for one model breaks ContentItem.plugin and the frontend code # that depends on using inline-model names instead of plugins. Good luck fixing that. # Better leave the model==plugin dependency for now. existing_plugin = self.plugins[self._name_for_model[plugin.model]] raise ModelAlreadyRegistered("Can't register the model {0} to {2}, it's already registered to {1}!".format( plugin.model.__name__, existing_plugin.name, plugin.__name__ )) # Make a single static instance, similar to ModelAdmin. plugin_instance = plugin() self.plugins[name] = plugin_instance self._name_for_model[plugin.model] = name # Track reverse for model.plugin link # Only update lazy indexes if already created if self._name_for_ctype_id is not None: self._name_for_ctype_id[plugin.type_id] = name return plugin
[ "def", "register", "(", "self", ",", "plugin", ")", ":", "# Duck-Typing does not suffice here, avoid hard to debug problems by upfront checks.", "assert", "issubclass", "(", "plugin", ",", "ContentPlugin", ")", ",", "\"The plugin must inherit from `ContentPlugin`\"", "assert", "plugin", ".", "model", ",", "\"The plugin has no model defined\"", "assert", "issubclass", "(", "plugin", ".", "model", ",", "ContentItem", ")", ",", "\"The plugin model must inherit from `ContentItem`\"", "assert", "issubclass", "(", "plugin", ".", "form", ",", "ContentItemForm", ")", ",", "\"The plugin form must inherit from `ContentItemForm`\"", "name", "=", "plugin", ".", "__name__", "# using class here, no instance created yet.", "name", "=", "name", ".", "lower", "(", ")", "if", "name", "in", "self", ".", "plugins", ":", "raise", "PluginAlreadyRegistered", "(", "\"{0}: a plugin with this name is already registered\"", ".", "format", "(", "name", ")", ")", "# Avoid registering 2 plugins to the exact same model. If you want to reuse code, use proxy models.", "if", "plugin", ".", "model", "in", "self", ".", "_name_for_model", ":", "# Having 2 plugins for one model breaks ContentItem.plugin and the frontend code", "# that depends on using inline-model names instead of plugins. Good luck fixing that.", "# Better leave the model==plugin dependency for now.", "existing_plugin", "=", "self", ".", "plugins", "[", "self", ".", "_name_for_model", "[", "plugin", ".", "model", "]", "]", "raise", "ModelAlreadyRegistered", "(", "\"Can't register the model {0} to {2}, it's already registered to {1}!\"", ".", "format", "(", "plugin", ".", "model", ".", "__name__", ",", "existing_plugin", ".", "name", ",", "plugin", ".", "__name__", ")", ")", "# Make a single static instance, similar to ModelAdmin.", "plugin_instance", "=", "plugin", "(", ")", "self", ".", "plugins", "[", "name", "]", "=", "plugin_instance", "self", ".", "_name_for_model", "[", "plugin", ".", "model", "]", "=", "name", "# Track reverse for model.plugin link", "# Only update lazy indexes if already created", "if", "self", ".", "_name_for_ctype_id", "is", "not", "None", ":", "self", ".", "_name_for_ctype_id", "[", "plugin", ".", "type_id", "]", "=", "name", "return", "plugin" ]
Make a plugin known to the CMS. :param plugin: The plugin class, deriving from :class:`ContentPlugin`. :type plugin: :class:`ContentPlugin` The plugin will be instantiated once, just like Django does this with :class:`~django.contrib.admin.ModelAdmin` classes. If a plugin is already registered, this will raise a :class:`PluginAlreadyRegistered` exception.
[ "Make", "a", "plugin", "known", "to", "the", "CMS", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/extensions/pluginpool.py#L62-L104
django-fluent/django-fluent-contents
fluent_contents/extensions/pluginpool.py
PluginPool.get_allowed_plugins
def get_allowed_plugins(self, placeholder_slot): """ Return the plugins which are supported in the given placeholder name. """ # See if there is a limit imposed. slot_config = appsettings.FLUENT_CONTENTS_PLACEHOLDER_CONFIG.get(placeholder_slot) or {} plugins = slot_config.get('plugins') if not plugins: return self.get_plugins() else: try: return self.get_plugins_by_name(*plugins) except PluginNotFound as e: raise PluginNotFound(str(e) + " Update the plugin list of the FLUENT_CONTENTS_PLACEHOLDER_CONFIG['{0}'] setting.".format(placeholder_slot))
python
def get_allowed_plugins(self, placeholder_slot): """ Return the plugins which are supported in the given placeholder name. """ # See if there is a limit imposed. slot_config = appsettings.FLUENT_CONTENTS_PLACEHOLDER_CONFIG.get(placeholder_slot) or {} plugins = slot_config.get('plugins') if not plugins: return self.get_plugins() else: try: return self.get_plugins_by_name(*plugins) except PluginNotFound as e: raise PluginNotFound(str(e) + " Update the plugin list of the FLUENT_CONTENTS_PLACEHOLDER_CONFIG['{0}'] setting.".format(placeholder_slot))
[ "def", "get_allowed_plugins", "(", "self", ",", "placeholder_slot", ")", ":", "# See if there is a limit imposed.", "slot_config", "=", "appsettings", ".", "FLUENT_CONTENTS_PLACEHOLDER_CONFIG", ".", "get", "(", "placeholder_slot", ")", "or", "{", "}", "plugins", "=", "slot_config", ".", "get", "(", "'plugins'", ")", "if", "not", "plugins", ":", "return", "self", ".", "get_plugins", "(", ")", "else", ":", "try", ":", "return", "self", ".", "get_plugins_by_name", "(", "*", "plugins", ")", "except", "PluginNotFound", "as", "e", ":", "raise", "PluginNotFound", "(", "str", "(", "e", ")", "+", "\" Update the plugin list of the FLUENT_CONTENTS_PLACEHOLDER_CONFIG['{0}'] setting.\"", ".", "format", "(", "placeholder_slot", ")", ")" ]
Return the plugins which are supported in the given placeholder name.
[ "Return", "the", "plugins", "which", "are", "supported", "in", "the", "given", "placeholder", "name", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/extensions/pluginpool.py#L113-L126
django-fluent/django-fluent-contents
fluent_contents/extensions/pluginpool.py
PluginPool.get_plugins_by_name
def get_plugins_by_name(self, *names): """ Return a list of plugins by plugin class, or name. """ self._import_plugins() plugin_instances = [] for name in names: if isinstance(name, six.string_types): try: plugin_instances.append(self.plugins[name.lower()]) except KeyError: raise PluginNotFound("No plugin named '{0}'.".format(name)) elif isinstance(name, type) and issubclass(name, ContentPlugin): # Will also allow classes instead of strings. plugin_instances.append(self.plugins[self._name_for_model[name.model]]) else: raise TypeError("get_plugins_by_name() expects a plugin name or class, not: {0}".format(name)) return plugin_instances
python
def get_plugins_by_name(self, *names): """ Return a list of plugins by plugin class, or name. """ self._import_plugins() plugin_instances = [] for name in names: if isinstance(name, six.string_types): try: plugin_instances.append(self.plugins[name.lower()]) except KeyError: raise PluginNotFound("No plugin named '{0}'.".format(name)) elif isinstance(name, type) and issubclass(name, ContentPlugin): # Will also allow classes instead of strings. plugin_instances.append(self.plugins[self._name_for_model[name.model]]) else: raise TypeError("get_plugins_by_name() expects a plugin name or class, not: {0}".format(name)) return plugin_instances
[ "def", "get_plugins_by_name", "(", "self", ",", "*", "names", ")", ":", "self", ".", "_import_plugins", "(", ")", "plugin_instances", "=", "[", "]", "for", "name", "in", "names", ":", "if", "isinstance", "(", "name", ",", "six", ".", "string_types", ")", ":", "try", ":", "plugin_instances", ".", "append", "(", "self", ".", "plugins", "[", "name", ".", "lower", "(", ")", "]", ")", "except", "KeyError", ":", "raise", "PluginNotFound", "(", "\"No plugin named '{0}'.\"", ".", "format", "(", "name", ")", ")", "elif", "isinstance", "(", "name", ",", "type", ")", "and", "issubclass", "(", "name", ",", "ContentPlugin", ")", ":", "# Will also allow classes instead of strings.", "plugin_instances", ".", "append", "(", "self", ".", "plugins", "[", "self", ".", "_name_for_model", "[", "name", ".", "model", "]", "]", ")", "else", ":", "raise", "TypeError", "(", "\"get_plugins_by_name() expects a plugin name or class, not: {0}\"", ".", "format", "(", "name", ")", ")", "return", "plugin_instances" ]
Return a list of plugins by plugin class, or name.
[ "Return", "a", "list", "of", "plugins", "by", "plugin", "class", "or", "name", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/extensions/pluginpool.py#L128-L145
django-fluent/django-fluent-contents
fluent_contents/extensions/pluginpool.py
PluginPool.get_model_classes
def get_model_classes(self): """ Return all :class:`~fluent_contents.models.ContentItem` model classes which are exposed by plugins. """ self._import_plugins() return [plugin.model for plugin in self.plugins.values()]
python
def get_model_classes(self): """ Return all :class:`~fluent_contents.models.ContentItem` model classes which are exposed by plugins. """ self._import_plugins() return [plugin.model for plugin in self.plugins.values()]
[ "def", "get_model_classes", "(", "self", ")", ":", "self", ".", "_import_plugins", "(", ")", "return", "[", "plugin", ".", "model", "for", "plugin", "in", "self", ".", "plugins", ".", "values", "(", ")", "]" ]
Return all :class:`~fluent_contents.models.ContentItem` model classes which are exposed by plugins.
[ "Return", "all", ":", "class", ":", "~fluent_contents", ".", "models", ".", "ContentItem", "model", "classes", "which", "are", "exposed", "by", "plugins", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/extensions/pluginpool.py#L147-L152
django-fluent/django-fluent-contents
fluent_contents/extensions/pluginpool.py
PluginPool.get_plugin_by_model
def get_plugin_by_model(self, model_class): """ Return the corresponding plugin for a given model. You can also use the :attr:`ContentItem.plugin <fluent_contents.models.ContentItem.plugin>` property directly. This is the low-level function that supports that feature. """ self._import_plugins() # could happen during rendering that no plugin scan happened yet. assert issubclass(model_class, ContentItem) # avoid confusion between model instance and class here! try: name = self._name_for_model[model_class] except KeyError: raise PluginNotFound("No plugin found for model '{0}'.".format(model_class.__name__)) return self.plugins[name]
python
def get_plugin_by_model(self, model_class): """ Return the corresponding plugin for a given model. You can also use the :attr:`ContentItem.plugin <fluent_contents.models.ContentItem.plugin>` property directly. This is the low-level function that supports that feature. """ self._import_plugins() # could happen during rendering that no plugin scan happened yet. assert issubclass(model_class, ContentItem) # avoid confusion between model instance and class here! try: name = self._name_for_model[model_class] except KeyError: raise PluginNotFound("No plugin found for model '{0}'.".format(model_class.__name__)) return self.plugins[name]
[ "def", "get_plugin_by_model", "(", "self", ",", "model_class", ")", ":", "self", ".", "_import_plugins", "(", ")", "# could happen during rendering that no plugin scan happened yet.", "assert", "issubclass", "(", "model_class", ",", "ContentItem", ")", "# avoid confusion between model instance and class here!", "try", ":", "name", "=", "self", ".", "_name_for_model", "[", "model_class", "]", "except", "KeyError", ":", "raise", "PluginNotFound", "(", "\"No plugin found for model '{0}'.\"", ".", "format", "(", "model_class", ".", "__name__", ")", ")", "return", "self", ".", "plugins", "[", "name", "]" ]
Return the corresponding plugin for a given model. You can also use the :attr:`ContentItem.plugin <fluent_contents.models.ContentItem.plugin>` property directly. This is the low-level function that supports that feature.
[ "Return", "the", "corresponding", "plugin", "for", "a", "given", "model", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/extensions/pluginpool.py#L154-L168
django-fluent/django-fluent-contents
fluent_contents/extensions/pluginpool.py
PluginPool._import_plugins
def _import_plugins(self): """ Internal function, ensure all plugin packages are imported. """ if self.detected: return # In some cases, plugin scanning may start during a request. # Make sure there is only one thread scanning for plugins. self.scanLock.acquire() if self.detected: return # previous threaded released + completed try: import_apps_submodule("content_plugins") self.detected = True finally: self.scanLock.release()
python
def _import_plugins(self): """ Internal function, ensure all plugin packages are imported. """ if self.detected: return # In some cases, plugin scanning may start during a request. # Make sure there is only one thread scanning for plugins. self.scanLock.acquire() if self.detected: return # previous threaded released + completed try: import_apps_submodule("content_plugins") self.detected = True finally: self.scanLock.release()
[ "def", "_import_plugins", "(", "self", ")", ":", "if", "self", ".", "detected", ":", "return", "# In some cases, plugin scanning may start during a request.", "# Make sure there is only one thread scanning for plugins.", "self", ".", "scanLock", ".", "acquire", "(", ")", "if", "self", ".", "detected", ":", "return", "# previous threaded released + completed", "try", ":", "import_apps_submodule", "(", "\"content_plugins\"", ")", "self", ".", "detected", "=", "True", "finally", ":", "self", ".", "scanLock", ".", "release", "(", ")" ]
Internal function, ensure all plugin packages are imported.
[ "Internal", "function", "ensure", "all", "plugin", "packages", "are", "imported", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/extensions/pluginpool.py#L190-L207
django-fluent/django-fluent-contents
fluent_contents/utils/filters.py
apply_filters
def apply_filters(instance, html, field_name): """ Run all filters for a given HTML snippet. Returns the results of the pre-filter and post-filter as tuple. This function can be called from the :meth:`~django.db.models.Model.full_clean` method in the model. That function is called when the form values are assigned. For example: .. code-block:: python def full_clean(self, *args, **kwargs): super(TextItem, self).full_clean(*args, **kwargs) self.html, self.html_final = apply_filters(self, self.html, field_name='html') :type instance: fluent_contents.models.ContentItem :raise ValidationError: when one of the filters detects a problem. """ try: html = apply_pre_filters(instance, html) # Perform post processing. This does not effect the original 'html' html_final = apply_post_filters(instance, html) except ValidationError as e: if hasattr(e, 'error_list'): # The filters can raise a "dump" ValidationError with a single error. # However, during post_clean it's expected that the fields are named. raise ValidationError({ field_name: e.error_list }) raise return html, html_final
python
def apply_filters(instance, html, field_name): """ Run all filters for a given HTML snippet. Returns the results of the pre-filter and post-filter as tuple. This function can be called from the :meth:`~django.db.models.Model.full_clean` method in the model. That function is called when the form values are assigned. For example: .. code-block:: python def full_clean(self, *args, **kwargs): super(TextItem, self).full_clean(*args, **kwargs) self.html, self.html_final = apply_filters(self, self.html, field_name='html') :type instance: fluent_contents.models.ContentItem :raise ValidationError: when one of the filters detects a problem. """ try: html = apply_pre_filters(instance, html) # Perform post processing. This does not effect the original 'html' html_final = apply_post_filters(instance, html) except ValidationError as e: if hasattr(e, 'error_list'): # The filters can raise a "dump" ValidationError with a single error. # However, during post_clean it's expected that the fields are named. raise ValidationError({ field_name: e.error_list }) raise return html, html_final
[ "def", "apply_filters", "(", "instance", ",", "html", ",", "field_name", ")", ":", "try", ":", "html", "=", "apply_pre_filters", "(", "instance", ",", "html", ")", "# Perform post processing. This does not effect the original 'html'", "html_final", "=", "apply_post_filters", "(", "instance", ",", "html", ")", "except", "ValidationError", "as", "e", ":", "if", "hasattr", "(", "e", ",", "'error_list'", ")", ":", "# The filters can raise a \"dump\" ValidationError with a single error.", "# However, during post_clean it's expected that the fields are named.", "raise", "ValidationError", "(", "{", "field_name", ":", "e", ".", "error_list", "}", ")", "raise", "return", "html", ",", "html_final" ]
Run all filters for a given HTML snippet. Returns the results of the pre-filter and post-filter as tuple. This function can be called from the :meth:`~django.db.models.Model.full_clean` method in the model. That function is called when the form values are assigned. For example: .. code-block:: python def full_clean(self, *args, **kwargs): super(TextItem, self).full_clean(*args, **kwargs) self.html, self.html_final = apply_filters(self, self.html, field_name='html') :type instance: fluent_contents.models.ContentItem :raise ValidationError: when one of the filters detects a problem.
[ "Run", "all", "filters", "for", "a", "given", "HTML", "snippet", ".", "Returns", "the", "results", "of", "the", "pre", "-", "filter", "and", "post", "-", "filter", "as", "tuple", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/utils/filters.py#L11-L43
django-fluent/django-fluent-contents
fluent_contents/utils/filters.py
apply_pre_filters
def apply_pre_filters(instance, html): """ Perform optimizations in the HTML source code. :type instance: fluent_contents.models.ContentItem :raise ValidationError: when one of the filters detects a problem. """ # Allow pre processing. Typical use-case is HTML syntax correction. for post_func in appsettings.PRE_FILTER_FUNCTIONS: html = post_func(instance, html) return html
python
def apply_pre_filters(instance, html): """ Perform optimizations in the HTML source code. :type instance: fluent_contents.models.ContentItem :raise ValidationError: when one of the filters detects a problem. """ # Allow pre processing. Typical use-case is HTML syntax correction. for post_func in appsettings.PRE_FILTER_FUNCTIONS: html = post_func(instance, html) return html
[ "def", "apply_pre_filters", "(", "instance", ",", "html", ")", ":", "# Allow pre processing. Typical use-case is HTML syntax correction.", "for", "post_func", "in", "appsettings", ".", "PRE_FILTER_FUNCTIONS", ":", "html", "=", "post_func", "(", "instance", ",", "html", ")", "return", "html" ]
Perform optimizations in the HTML source code. :type instance: fluent_contents.models.ContentItem :raise ValidationError: when one of the filters detects a problem.
[ "Perform", "optimizations", "in", "the", "HTML", "source", "code", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/utils/filters.py#L46-L57
django-fluent/django-fluent-contents
fluent_contents/utils/filters.py
apply_post_filters
def apply_post_filters(instance, html): """ Allow post processing functions to change the text. This change is not saved in the original text. :type instance: fluent_contents.models.ContentItem :raise ValidationError: when one of the filters detects a problem. """ for post_func in appsettings.POST_FILTER_FUNCTIONS: html = post_func(instance, html) return html
python
def apply_post_filters(instance, html): """ Allow post processing functions to change the text. This change is not saved in the original text. :type instance: fluent_contents.models.ContentItem :raise ValidationError: when one of the filters detects a problem. """ for post_func in appsettings.POST_FILTER_FUNCTIONS: html = post_func(instance, html) return html
[ "def", "apply_post_filters", "(", "instance", ",", "html", ")", ":", "for", "post_func", "in", "appsettings", ".", "POST_FILTER_FUNCTIONS", ":", "html", "=", "post_func", "(", "instance", ",", "html", ")", "return", "html" ]
Allow post processing functions to change the text. This change is not saved in the original text. :type instance: fluent_contents.models.ContentItem :raise ValidationError: when one of the filters detects a problem.
[ "Allow", "post", "processing", "functions", "to", "change", "the", "text", ".", "This", "change", "is", "not", "saved", "in", "the", "original", "text", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/utils/filters.py#L60-L71
django-fluent/django-fluent-contents
fluent_contents/plugins/commentsarea/models.py
clear_commentarea_cache
def clear_commentarea_cache(comment): """ Clean the plugin output cache of a rendered plugin. """ parent = comment.content_object for instance in CommentsAreaItem.objects.parent(parent): instance.clear_cache()
python
def clear_commentarea_cache(comment): """ Clean the plugin output cache of a rendered plugin. """ parent = comment.content_object for instance in CommentsAreaItem.objects.parent(parent): instance.clear_cache()
[ "def", "clear_commentarea_cache", "(", "comment", ")", ":", "parent", "=", "comment", ".", "content_object", "for", "instance", "in", "CommentsAreaItem", ".", "objects", ".", "parent", "(", "parent", ")", ":", "instance", ".", "clear_cache", "(", ")" ]
Clean the plugin output cache of a rendered plugin.
[ "Clean", "the", "plugin", "output", "cache", "of", "a", "rendered", "plugin", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/plugins/commentsarea/models.py#L27-L33
django-fluent/django-fluent-contents
fluent_contents/plugins/sharedcontent/managers.py
SharedContentQuerySet.parent_site
def parent_site(self, site): """ Filter to the given site, only give content relevant for that site. """ # Avoid auto filter if site is already set. self._parent_site = site if sharedcontent_appsettings.FLUENT_SHARED_CONTENT_ENABLE_CROSS_SITE: # Allow content to be shared between all sites: return self.filter(Q(parent_site=site) | Q(is_cross_site=True)) else: return self.filter(parent_site=site)
python
def parent_site(self, site): """ Filter to the given site, only give content relevant for that site. """ # Avoid auto filter if site is already set. self._parent_site = site if sharedcontent_appsettings.FLUENT_SHARED_CONTENT_ENABLE_CROSS_SITE: # Allow content to be shared between all sites: return self.filter(Q(parent_site=site) | Q(is_cross_site=True)) else: return self.filter(parent_site=site)
[ "def", "parent_site", "(", "self", ",", "site", ")", ":", "# Avoid auto filter if site is already set.", "self", ".", "_parent_site", "=", "site", "if", "sharedcontent_appsettings", ".", "FLUENT_SHARED_CONTENT_ENABLE_CROSS_SITE", ":", "# Allow content to be shared between all sites:", "return", "self", ".", "filter", "(", "Q", "(", "parent_site", "=", "site", ")", "|", "Q", "(", "is_cross_site", "=", "True", ")", ")", "else", ":", "return", "self", ".", "filter", "(", "parent_site", "=", "site", ")" ]
Filter to the given site, only give content relevant for that site.
[ "Filter", "to", "the", "given", "site", "only", "give", "content", "relevant", "for", "that", "site", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/plugins/sharedcontent/managers.py#L22-L33
django-fluent/django-fluent-contents
fluent_contents/plugins/sharedcontent/managers.py
SharedContentQuerySet._single_site
def _single_site(self): """ Make sure the queryset is filtered on a parent site, if that didn't happen already. """ if appsettings.FLUENT_CONTENTS_FILTER_SITE_ID and self._parent_site is None: return self.parent_site(settings.SITE_ID) else: return self
python
def _single_site(self): """ Make sure the queryset is filtered on a parent site, if that didn't happen already. """ if appsettings.FLUENT_CONTENTS_FILTER_SITE_ID and self._parent_site is None: return self.parent_site(settings.SITE_ID) else: return self
[ "def", "_single_site", "(", "self", ")", ":", "if", "appsettings", ".", "FLUENT_CONTENTS_FILTER_SITE_ID", "and", "self", ".", "_parent_site", "is", "None", ":", "return", "self", ".", "parent_site", "(", "settings", ".", "SITE_ID", ")", "else", ":", "return", "self" ]
Make sure the queryset is filtered on a parent site, if that didn't happen already.
[ "Make", "sure", "the", "queryset", "is", "filtered", "on", "a", "parent", "site", "if", "that", "didn", "t", "happen", "already", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/plugins/sharedcontent/managers.py#L35-L42
django-fluent/django-fluent-contents
fluent_contents/analyzer.py
get_template_placeholder_data
def get_template_placeholder_data(template): """ Return the placeholders found in a template, wrapped in a :class:`~fluent_contents.models.containers.PlaceholderData` object. This function looks for the :class:`~fluent_contents.templatetags.fluent_contents_tags.PagePlaceholderNode` nodes in the template, using the :func:`~template_analyzer.djangoanalyzer.get_node_instances` function of `django-template-analyzer <https://github.com/edoburu/django-template-analyzer>`_. :param template: The Template object, or nodelist to scan. :rtype: list of :class:`~fluent_contents.models.PlaceholderData` """ # Find the instances. nodes = get_node_instances(template, PagePlaceholderNode) # Avoid duplicates, wrap in a class. names = set() result = [] for pageplaceholdernode in nodes: data = PlaceholderData( slot=pageplaceholdernode.get_slot(), title=pageplaceholdernode.get_title(), role=pageplaceholdernode.get_role(), fallback_language=pageplaceholdernode.get_fallback_language(), ) if data.slot not in names: result.append(data) names.add(data.slot) return result
python
def get_template_placeholder_data(template): """ Return the placeholders found in a template, wrapped in a :class:`~fluent_contents.models.containers.PlaceholderData` object. This function looks for the :class:`~fluent_contents.templatetags.fluent_contents_tags.PagePlaceholderNode` nodes in the template, using the :func:`~template_analyzer.djangoanalyzer.get_node_instances` function of `django-template-analyzer <https://github.com/edoburu/django-template-analyzer>`_. :param template: The Template object, or nodelist to scan. :rtype: list of :class:`~fluent_contents.models.PlaceholderData` """ # Find the instances. nodes = get_node_instances(template, PagePlaceholderNode) # Avoid duplicates, wrap in a class. names = set() result = [] for pageplaceholdernode in nodes: data = PlaceholderData( slot=pageplaceholdernode.get_slot(), title=pageplaceholdernode.get_title(), role=pageplaceholdernode.get_role(), fallback_language=pageplaceholdernode.get_fallback_language(), ) if data.slot not in names: result.append(data) names.add(data.slot) return result
[ "def", "get_template_placeholder_data", "(", "template", ")", ":", "# Find the instances.", "nodes", "=", "get_node_instances", "(", "template", ",", "PagePlaceholderNode", ")", "# Avoid duplicates, wrap in a class.", "names", "=", "set", "(", ")", "result", "=", "[", "]", "for", "pageplaceholdernode", "in", "nodes", ":", "data", "=", "PlaceholderData", "(", "slot", "=", "pageplaceholdernode", ".", "get_slot", "(", ")", ",", "title", "=", "pageplaceholdernode", ".", "get_title", "(", ")", ",", "role", "=", "pageplaceholdernode", ".", "get_role", "(", ")", ",", "fallback_language", "=", "pageplaceholdernode", ".", "get_fallback_language", "(", ")", ",", ")", "if", "data", ".", "slot", "not", "in", "names", ":", "result", ".", "append", "(", "data", ")", "names", ".", "add", "(", "data", ".", "slot", ")", "return", "result" ]
Return the placeholders found in a template, wrapped in a :class:`~fluent_contents.models.containers.PlaceholderData` object. This function looks for the :class:`~fluent_contents.templatetags.fluent_contents_tags.PagePlaceholderNode` nodes in the template, using the :func:`~template_analyzer.djangoanalyzer.get_node_instances` function of `django-template-analyzer <https://github.com/edoburu/django-template-analyzer>`_. :param template: The Template object, or nodelist to scan. :rtype: list of :class:`~fluent_contents.models.PlaceholderData`
[ "Return", "the", "placeholders", "found", "in", "a", "template", "wrapped", "in", "a", ":", "class", ":", "~fluent_contents", ".", "models", ".", "containers", ".", "PlaceholderData", "object", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/analyzer.py#L11-L41
django-fluent/django-fluent-contents
fluent_contents/management/commands/find_contentitem_urls.py
Command.inspect_model
def inspect_model(self, model): """ Inspect a single model """ # See which interesting fields the model holds. url_fields = sorted(f for f in model._meta.fields if isinstance(f, (PluginUrlField, models.URLField))) file_fields = sorted(f for f in model._meta.fields if isinstance(f, (PluginImageField, models.FileField))) html_fields = sorted(f for f in model._meta.fields if isinstance(f, (models.TextField, PluginHtmlField))) all_fields = [f.name for f in (file_fields + html_fields + url_fields)] if not all_fields: return [] if model.__name__ in self.exclude: self.stderr.write("Skipping {0} ({1})\n".format(model.__name__, ", ".join(all_fields))) return [] sys.stderr.write("Inspecting {0} ({1})\n".format(model.__name__, ", ".join(all_fields))) q_notnull = reduce(operator.or_, (Q(**{"{0}__isnull".format(f): False}) for f in all_fields)) qs = model.objects.filter(q_notnull).order_by('pk') urls = [] for object in qs: # HTML fields need proper html5lib parsing for field in html_fields: value = getattr(object, field.name) if value: html_images = self.extract_html_urls(value) urls += html_images for image in html_images: self.show_match(object, image) # Picture fields take the URL from the storage class. for field in file_fields: value = getattr(object, field.name) if value: value = unquote_utf8(value.url) urls.append(value) self.show_match(object, value) # URL fields can be read directly. for field in url_fields: value = getattr(object, field.name) if value: if isinstance(value, six.text_type): value = force_text(value) else: value = value.to_db_value() # AnyUrlValue urls.append(value) self.show_match(object, value) return urls
python
def inspect_model(self, model): """ Inspect a single model """ # See which interesting fields the model holds. url_fields = sorted(f for f in model._meta.fields if isinstance(f, (PluginUrlField, models.URLField))) file_fields = sorted(f for f in model._meta.fields if isinstance(f, (PluginImageField, models.FileField))) html_fields = sorted(f for f in model._meta.fields if isinstance(f, (models.TextField, PluginHtmlField))) all_fields = [f.name for f in (file_fields + html_fields + url_fields)] if not all_fields: return [] if model.__name__ in self.exclude: self.stderr.write("Skipping {0} ({1})\n".format(model.__name__, ", ".join(all_fields))) return [] sys.stderr.write("Inspecting {0} ({1})\n".format(model.__name__, ", ".join(all_fields))) q_notnull = reduce(operator.or_, (Q(**{"{0}__isnull".format(f): False}) for f in all_fields)) qs = model.objects.filter(q_notnull).order_by('pk') urls = [] for object in qs: # HTML fields need proper html5lib parsing for field in html_fields: value = getattr(object, field.name) if value: html_images = self.extract_html_urls(value) urls += html_images for image in html_images: self.show_match(object, image) # Picture fields take the URL from the storage class. for field in file_fields: value = getattr(object, field.name) if value: value = unquote_utf8(value.url) urls.append(value) self.show_match(object, value) # URL fields can be read directly. for field in url_fields: value = getattr(object, field.name) if value: if isinstance(value, six.text_type): value = force_text(value) else: value = value.to_db_value() # AnyUrlValue urls.append(value) self.show_match(object, value) return urls
[ "def", "inspect_model", "(", "self", ",", "model", ")", ":", "# See which interesting fields the model holds.", "url_fields", "=", "sorted", "(", "f", "for", "f", "in", "model", ".", "_meta", ".", "fields", "if", "isinstance", "(", "f", ",", "(", "PluginUrlField", ",", "models", ".", "URLField", ")", ")", ")", "file_fields", "=", "sorted", "(", "f", "for", "f", "in", "model", ".", "_meta", ".", "fields", "if", "isinstance", "(", "f", ",", "(", "PluginImageField", ",", "models", ".", "FileField", ")", ")", ")", "html_fields", "=", "sorted", "(", "f", "for", "f", "in", "model", ".", "_meta", ".", "fields", "if", "isinstance", "(", "f", ",", "(", "models", ".", "TextField", ",", "PluginHtmlField", ")", ")", ")", "all_fields", "=", "[", "f", ".", "name", "for", "f", "in", "(", "file_fields", "+", "html_fields", "+", "url_fields", ")", "]", "if", "not", "all_fields", ":", "return", "[", "]", "if", "model", ".", "__name__", "in", "self", ".", "exclude", ":", "self", ".", "stderr", ".", "write", "(", "\"Skipping {0} ({1})\\n\"", ".", "format", "(", "model", ".", "__name__", ",", "\", \"", ".", "join", "(", "all_fields", ")", ")", ")", "return", "[", "]", "sys", ".", "stderr", ".", "write", "(", "\"Inspecting {0} ({1})\\n\"", ".", "format", "(", "model", ".", "__name__", ",", "\", \"", ".", "join", "(", "all_fields", ")", ")", ")", "q_notnull", "=", "reduce", "(", "operator", ".", "or_", ",", "(", "Q", "(", "*", "*", "{", "\"{0}__isnull\"", ".", "format", "(", "f", ")", ":", "False", "}", ")", "for", "f", "in", "all_fields", ")", ")", "qs", "=", "model", ".", "objects", ".", "filter", "(", "q_notnull", ")", ".", "order_by", "(", "'pk'", ")", "urls", "=", "[", "]", "for", "object", "in", "qs", ":", "# HTML fields need proper html5lib parsing", "for", "field", "in", "html_fields", ":", "value", "=", "getattr", "(", "object", ",", "field", ".", "name", ")", "if", "value", ":", "html_images", "=", "self", ".", "extract_html_urls", "(", "value", ")", "urls", "+=", "html_images", "for", "image", "in", "html_images", ":", "self", ".", "show_match", "(", "object", ",", "image", ")", "# Picture fields take the URL from the storage class.", "for", "field", "in", "file_fields", ":", "value", "=", "getattr", "(", "object", ",", "field", ".", "name", ")", "if", "value", ":", "value", "=", "unquote_utf8", "(", "value", ".", "url", ")", "urls", ".", "append", "(", "value", ")", "self", ".", "show_match", "(", "object", ",", "value", ")", "# URL fields can be read directly.", "for", "field", "in", "url_fields", ":", "value", "=", "getattr", "(", "object", ",", "field", ".", "name", ")", "if", "value", ":", "if", "isinstance", "(", "value", ",", "six", ".", "text_type", ")", ":", "value", "=", "force_text", "(", "value", ")", "else", ":", "value", "=", "value", ".", "to_db_value", "(", ")", "# AnyUrlValue", "urls", ".", "append", "(", "value", ")", "self", ".", "show_match", "(", "object", ",", "value", ")", "return", "urls" ]
Inspect a single model
[ "Inspect", "a", "single", "model" ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/management/commands/find_contentitem_urls.py#L61-L113
django-fluent/django-fluent-contents
fluent_contents/management/commands/find_contentitem_urls.py
Command.extract_html_urls
def extract_html_urls(self, html): """ Take all ``<img src="..">`` from the HTML """ p = HTMLParser(tree=treebuilders.getTreeBuilder("dom")) dom = p.parse(html) urls = [] for img in dom.getElementsByTagName('img'): src = img.getAttribute('src') if src: urls.append(unquote_utf8(src)) srcset = img.getAttribute('srcset') if srcset: urls += self.extract_srcset(srcset) for source in dom.getElementsByTagName('source'): srcset = source.getAttribute('srcset') if srcset: urls += self.extract_srcset(srcset) for source in dom.getElementsByTagName('a'): href = source.getAttribute('href') if href: urls.append(unquote_utf8(href)) return urls
python
def extract_html_urls(self, html): """ Take all ``<img src="..">`` from the HTML """ p = HTMLParser(tree=treebuilders.getTreeBuilder("dom")) dom = p.parse(html) urls = [] for img in dom.getElementsByTagName('img'): src = img.getAttribute('src') if src: urls.append(unquote_utf8(src)) srcset = img.getAttribute('srcset') if srcset: urls += self.extract_srcset(srcset) for source in dom.getElementsByTagName('source'): srcset = source.getAttribute('srcset') if srcset: urls += self.extract_srcset(srcset) for source in dom.getElementsByTagName('a'): href = source.getAttribute('href') if href: urls.append(unquote_utf8(href)) return urls
[ "def", "extract_html_urls", "(", "self", ",", "html", ")", ":", "p", "=", "HTMLParser", "(", "tree", "=", "treebuilders", ".", "getTreeBuilder", "(", "\"dom\"", ")", ")", "dom", "=", "p", ".", "parse", "(", "html", ")", "urls", "=", "[", "]", "for", "img", "in", "dom", ".", "getElementsByTagName", "(", "'img'", ")", ":", "src", "=", "img", ".", "getAttribute", "(", "'src'", ")", "if", "src", ":", "urls", ".", "append", "(", "unquote_utf8", "(", "src", ")", ")", "srcset", "=", "img", ".", "getAttribute", "(", "'srcset'", ")", "if", "srcset", ":", "urls", "+=", "self", ".", "extract_srcset", "(", "srcset", ")", "for", "source", "in", "dom", ".", "getElementsByTagName", "(", "'source'", ")", ":", "srcset", "=", "source", ".", "getAttribute", "(", "'srcset'", ")", "if", "srcset", ":", "urls", "+=", "self", ".", "extract_srcset", "(", "srcset", ")", "for", "source", "in", "dom", ".", "getElementsByTagName", "(", "'a'", ")", ":", "href", "=", "source", ".", "getAttribute", "(", "'href'", ")", "if", "href", ":", "urls", ".", "append", "(", "unquote_utf8", "(", "href", ")", ")", "return", "urls" ]
Take all ``<img src="..">`` from the HTML
[ "Take", "all", "<img", "src", "=", "..", ">", "from", "the", "HTML" ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/management/commands/find_contentitem_urls.py#L119-L146
django-fluent/django-fluent-contents
fluent_contents/management/commands/find_contentitem_urls.py
Command.extract_srcset
def extract_srcset(self, srcset): """ Handle ``srcset="image.png 1x, [email protected] 2x"`` """ urls = [] for item in srcset.split(','): if item: urls.append(unquote_utf8(item.rsplit(' ', 1)[0])) return urls
python
def extract_srcset(self, srcset): """ Handle ``srcset="image.png 1x, [email protected] 2x"`` """ urls = [] for item in srcset.split(','): if item: urls.append(unquote_utf8(item.rsplit(' ', 1)[0])) return urls
[ "def", "extract_srcset", "(", "self", ",", "srcset", ")", ":", "urls", "=", "[", "]", "for", "item", "in", "srcset", ".", "split", "(", "','", ")", ":", "if", "item", ":", "urls", ".", "append", "(", "unquote_utf8", "(", "item", ".", "rsplit", "(", "' '", ",", "1", ")", "[", "0", "]", ")", ")", "return", "urls" ]
Handle ``srcset="image.png 1x, [email protected] 2x"``
[ "Handle", "srcset", "=", "image", ".", "png", "1x", "image" ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/management/commands/find_contentitem_urls.py#L148-L156
django-fluent/django-fluent-contents
fluent_contents/models/db.py
on_delete_model_translation
def on_delete_model_translation(instance, **kwargs): """ Make sure ContentItems are deleted when a translation in deleted. """ translation = instance parent_object = translation.master parent_object.set_current_language(translation.language_code) # Also delete any associated plugins # Placeholders are shared between languages, so these are not affected. for item in ContentItem.objects.parent(parent_object, limit_parent_language=True): item.delete()
python
def on_delete_model_translation(instance, **kwargs): """ Make sure ContentItems are deleted when a translation in deleted. """ translation = instance parent_object = translation.master parent_object.set_current_language(translation.language_code) # Also delete any associated plugins # Placeholders are shared between languages, so these are not affected. for item in ContentItem.objects.parent(parent_object, limit_parent_language=True): item.delete()
[ "def", "on_delete_model_translation", "(", "instance", ",", "*", "*", "kwargs", ")", ":", "translation", "=", "instance", "parent_object", "=", "translation", ".", "master", "parent_object", ".", "set_current_language", "(", "translation", ".", "language_code", ")", "# Also delete any associated plugins", "# Placeholders are shared between languages, so these are not affected.", "for", "item", "in", "ContentItem", ".", "objects", ".", "parent", "(", "parent_object", ",", "limit_parent_language", "=", "True", ")", ":", "item", ".", "delete", "(", ")" ]
Make sure ContentItems are deleted when a translation in deleted.
[ "Make", "sure", "ContentItems", "are", "deleted", "when", "a", "translation", "in", "deleted", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/models/db.py#L426-L438
django-fluent/django-fluent-contents
fluent_contents/utils/html.py
clean_html
def clean_html(input, sanitize=False): """ Takes an HTML fragment and processes it using html5lib to ensure that the HTML is well-formed. :param sanitize: Remove unwanted HTML tags and attributes. >>> clean_html("<p>Foo<b>bar</b></p>") u'<p>Foo<b>bar</b></p>' >>> clean_html("<p>Foo<b>bar</b><i>Ooops!</p>") u'<p>Foo<b>bar</b><i>Ooops!</i></p>' >>> clean_html('<p>Foo<b>bar</b>& oops<a href="#foo&bar">This is a <>link</a></p>') u'<p>Foo<b>bar</b>&amp; oops<a href=#foo&amp;bar>This is a &lt;&gt;link</a></p>' """ parser_kwargs = {} serializer_kwargs = {} if sanitize: if HTMLSanitizer is None: # new syntax as of 0.99999999/1.0b9 (Released on July 14, 2016) serializer_kwargs['sanitize'] = True else: parser_kwargs['tokenizer'] = HTMLSanitizer p = HTMLParser(tree=treebuilders.getTreeBuilder("dom"), **parser_kwargs) dom_tree = p.parseFragment(input) walker = treewalkers.getTreeWalker("dom") stream = walker(dom_tree) s = HTMLSerializer(omit_optional_tags=False, **serializer_kwargs) return "".join(s.serialize(stream))
python
def clean_html(input, sanitize=False): """ Takes an HTML fragment and processes it using html5lib to ensure that the HTML is well-formed. :param sanitize: Remove unwanted HTML tags and attributes. >>> clean_html("<p>Foo<b>bar</b></p>") u'<p>Foo<b>bar</b></p>' >>> clean_html("<p>Foo<b>bar</b><i>Ooops!</p>") u'<p>Foo<b>bar</b><i>Ooops!</i></p>' >>> clean_html('<p>Foo<b>bar</b>& oops<a href="#foo&bar">This is a <>link</a></p>') u'<p>Foo<b>bar</b>&amp; oops<a href=#foo&amp;bar>This is a &lt;&gt;link</a></p>' """ parser_kwargs = {} serializer_kwargs = {} if sanitize: if HTMLSanitizer is None: # new syntax as of 0.99999999/1.0b9 (Released on July 14, 2016) serializer_kwargs['sanitize'] = True else: parser_kwargs['tokenizer'] = HTMLSanitizer p = HTMLParser(tree=treebuilders.getTreeBuilder("dom"), **parser_kwargs) dom_tree = p.parseFragment(input) walker = treewalkers.getTreeWalker("dom") stream = walker(dom_tree) s = HTMLSerializer(omit_optional_tags=False, **serializer_kwargs) return "".join(s.serialize(stream))
[ "def", "clean_html", "(", "input", ",", "sanitize", "=", "False", ")", ":", "parser_kwargs", "=", "{", "}", "serializer_kwargs", "=", "{", "}", "if", "sanitize", ":", "if", "HTMLSanitizer", "is", "None", ":", "# new syntax as of 0.99999999/1.0b9 (Released on July 14, 2016)", "serializer_kwargs", "[", "'sanitize'", "]", "=", "True", "else", ":", "parser_kwargs", "[", "'tokenizer'", "]", "=", "HTMLSanitizer", "p", "=", "HTMLParser", "(", "tree", "=", "treebuilders", ".", "getTreeBuilder", "(", "\"dom\"", ")", ",", "*", "*", "parser_kwargs", ")", "dom_tree", "=", "p", ".", "parseFragment", "(", "input", ")", "walker", "=", "treewalkers", ".", "getTreeWalker", "(", "\"dom\"", ")", "stream", "=", "walker", "(", "dom_tree", ")", "s", "=", "HTMLSerializer", "(", "omit_optional_tags", "=", "False", ",", "*", "*", "serializer_kwargs", ")", "return", "\"\"", ".", "join", "(", "s", ".", "serialize", "(", "stream", ")", ")" ]
Takes an HTML fragment and processes it using html5lib to ensure that the HTML is well-formed. :param sanitize: Remove unwanted HTML tags and attributes. >>> clean_html("<p>Foo<b>bar</b></p>") u'<p>Foo<b>bar</b></p>' >>> clean_html("<p>Foo<b>bar</b><i>Ooops!</p>") u'<p>Foo<b>bar</b><i>Ooops!</i></p>' >>> clean_html('<p>Foo<b>bar</b>& oops<a href="#foo&bar">This is a <>link</a></p>') u'<p>Foo<b>bar</b>&amp; oops<a href=#foo&amp;bar>This is a &lt;&gt;link</a></p>'
[ "Takes", "an", "HTML", "fragment", "and", "processes", "it", "using", "html5lib", "to", "ensure", "that", "the", "HTML", "is", "well", "-", "formed", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/utils/html.py#L20-L48
django-fluent/django-fluent-contents
fluent_contents/models/__init__.py
PlaceholderData.as_dict
def as_dict(self): """ Return the contents as dictionary, for client-side export. The dictionary contains the fields: * ``slot`` * ``title`` * ``role`` * ``fallback_language`` * ``allowed_plugins`` """ plugins = self.get_allowed_plugins() return { 'slot': self.slot, 'title': self.title, 'role': self.role, 'fallback_language': self.fallback_language, 'allowed_plugins': [plugin.name for plugin in plugins], }
python
def as_dict(self): """ Return the contents as dictionary, for client-side export. The dictionary contains the fields: * ``slot`` * ``title`` * ``role`` * ``fallback_language`` * ``allowed_plugins`` """ plugins = self.get_allowed_plugins() return { 'slot': self.slot, 'title': self.title, 'role': self.role, 'fallback_language': self.fallback_language, 'allowed_plugins': [plugin.name for plugin in plugins], }
[ "def", "as_dict", "(", "self", ")", ":", "plugins", "=", "self", ".", "get_allowed_plugins", "(", ")", "return", "{", "'slot'", ":", "self", ".", "slot", ",", "'title'", ":", "self", ".", "title", ",", "'role'", ":", "self", ".", "role", ",", "'fallback_language'", ":", "self", ".", "fallback_language", ",", "'allowed_plugins'", ":", "[", "plugin", ".", "name", "for", "plugin", "in", "plugins", "]", ",", "}" ]
Return the contents as dictionary, for client-side export. The dictionary contains the fields: * ``slot`` * ``title`` * ``role`` * ``fallback_language`` * ``allowed_plugins``
[ "Return", "the", "contents", "as", "dictionary", "for", "client", "-", "side", "export", ".", "The", "dictionary", "contains", "the", "fields", ":" ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/models/__init__.py#L64-L82
django-fluent/django-fluent-contents
fluent_contents/plugins/markup/migrations/0002_fix_polymorphic_ctype.py
_forwards
def _forwards(apps, schema_editor): """ Make sure that the MarkupItem model actually points to the correct proxy model, that implements the given language. """ # Need to work on the actual models here. from fluent_contents.plugins.markup.models import LANGUAGE_MODEL_CLASSES from fluent_contents.plugins.markup.models import MarkupItem from django.contrib.contenttypes.models import ContentType ctype = ContentType.objects.get_for_model(MarkupItem) for language, proxy_model in LANGUAGE_MODEL_CLASSES.items(): proxy_ctype = ContentType.objects.get_for_model(proxy_model, for_concrete_model=False) MarkupItem.objects.filter( polymorphic_ctype=ctype, language=language ).update( polymorphic_ctype=proxy_ctype )
python
def _forwards(apps, schema_editor): """ Make sure that the MarkupItem model actually points to the correct proxy model, that implements the given language. """ # Need to work on the actual models here. from fluent_contents.plugins.markup.models import LANGUAGE_MODEL_CLASSES from fluent_contents.plugins.markup.models import MarkupItem from django.contrib.contenttypes.models import ContentType ctype = ContentType.objects.get_for_model(MarkupItem) for language, proxy_model in LANGUAGE_MODEL_CLASSES.items(): proxy_ctype = ContentType.objects.get_for_model(proxy_model, for_concrete_model=False) MarkupItem.objects.filter( polymorphic_ctype=ctype, language=language ).update( polymorphic_ctype=proxy_ctype )
[ "def", "_forwards", "(", "apps", ",", "schema_editor", ")", ":", "# Need to work on the actual models here.", "from", "fluent_contents", ".", "plugins", ".", "markup", ".", "models", "import", "LANGUAGE_MODEL_CLASSES", "from", "fluent_contents", ".", "plugins", ".", "markup", ".", "models", "import", "MarkupItem", "from", "django", ".", "contrib", ".", "contenttypes", ".", "models", "import", "ContentType", "ctype", "=", "ContentType", ".", "objects", ".", "get_for_model", "(", "MarkupItem", ")", "for", "language", ",", "proxy_model", "in", "LANGUAGE_MODEL_CLASSES", ".", "items", "(", ")", ":", "proxy_ctype", "=", "ContentType", ".", "objects", ".", "get_for_model", "(", "proxy_model", ",", "for_concrete_model", "=", "False", ")", "MarkupItem", ".", "objects", ".", "filter", "(", "polymorphic_ctype", "=", "ctype", ",", "language", "=", "language", ")", ".", "update", "(", "polymorphic_ctype", "=", "proxy_ctype", ")" ]
Make sure that the MarkupItem model actually points to the correct proxy model, that implements the given language.
[ "Make", "sure", "that", "the", "MarkupItem", "model", "actually", "points", "to", "the", "correct", "proxy", "model", "that", "implements", "the", "given", "language", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/plugins/markup/migrations/0002_fix_polymorphic_ctype.py#L8-L26
django-fluent/django-fluent-contents
fluent_contents/admin/placeholdereditor.py
PlaceholderEditorInline.get_formset
def get_formset(self, request, obj=None, **kwargs): """ Pre-populate formset with the initial placeholders to display. """ def _placeholder_initial(p): # p.as_dict() returns allowed_plugins too for the client-side API. return { 'slot': p.slot, 'title': p.title, 'role': p.role, } # Note this method is called twice, the second time in get_fieldsets() as `get_formset(request).form` initial = [] if request.method == "GET": placeholder_admin = self._get_parent_modeladmin() # Grab the initial data from the parent PlaceholderEditorBaseMixin data = placeholder_admin.get_placeholder_data(request, obj) initial = [_placeholder_initial(d) for d in data] # Order initial properly, # Inject as default parameter to the constructor # This is the BaseExtendedGenericInlineFormSet constructor FormSetClass = super(PlaceholderEditorInline, self).get_formset(request, obj, **kwargs) FormSetClass.__init__ = curry(FormSetClass.__init__, initial=initial) return FormSetClass
python
def get_formset(self, request, obj=None, **kwargs): """ Pre-populate formset with the initial placeholders to display. """ def _placeholder_initial(p): # p.as_dict() returns allowed_plugins too for the client-side API. return { 'slot': p.slot, 'title': p.title, 'role': p.role, } # Note this method is called twice, the second time in get_fieldsets() as `get_formset(request).form` initial = [] if request.method == "GET": placeholder_admin = self._get_parent_modeladmin() # Grab the initial data from the parent PlaceholderEditorBaseMixin data = placeholder_admin.get_placeholder_data(request, obj) initial = [_placeholder_initial(d) for d in data] # Order initial properly, # Inject as default parameter to the constructor # This is the BaseExtendedGenericInlineFormSet constructor FormSetClass = super(PlaceholderEditorInline, self).get_formset(request, obj, **kwargs) FormSetClass.__init__ = curry(FormSetClass.__init__, initial=initial) return FormSetClass
[ "def", "get_formset", "(", "self", ",", "request", ",", "obj", "=", "None", ",", "*", "*", "kwargs", ")", ":", "def", "_placeholder_initial", "(", "p", ")", ":", "# p.as_dict() returns allowed_plugins too for the client-side API.", "return", "{", "'slot'", ":", "p", ".", "slot", ",", "'title'", ":", "p", ".", "title", ",", "'role'", ":", "p", ".", "role", ",", "}", "# Note this method is called twice, the second time in get_fieldsets() as `get_formset(request).form`", "initial", "=", "[", "]", "if", "request", ".", "method", "==", "\"GET\"", ":", "placeholder_admin", "=", "self", ".", "_get_parent_modeladmin", "(", ")", "# Grab the initial data from the parent PlaceholderEditorBaseMixin", "data", "=", "placeholder_admin", ".", "get_placeholder_data", "(", "request", ",", "obj", ")", "initial", "=", "[", "_placeholder_initial", "(", "d", ")", "for", "d", "in", "data", "]", "# Order initial properly,", "# Inject as default parameter to the constructor", "# This is the BaseExtendedGenericInlineFormSet constructor", "FormSetClass", "=", "super", "(", "PlaceholderEditorInline", ",", "self", ")", ".", "get_formset", "(", "request", ",", "obj", ",", "*", "*", "kwargs", ")", "FormSetClass", ".", "__init__", "=", "curry", "(", "FormSetClass", ".", "__init__", ",", "initial", "=", "initial", ")", "return", "FormSetClass" ]
Pre-populate formset with the initial placeholders to display.
[ "Pre", "-", "populate", "formset", "with", "the", "initial", "placeholders", "to", "display", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/admin/placeholdereditor.py#L106-L133
django-fluent/django-fluent-contents
fluent_contents/admin/placeholdereditor.py
PlaceholderEditorAdmin.get_inline_instances
def get_inline_instances(self, request, *args, **kwargs): """ Create the inlines for the admin, including the placeholder and contentitem inlines. """ inlines = super(PlaceholderEditorAdmin, self).get_inline_instances(request, *args, **kwargs) extra_inline_instances = [] inlinetypes = self.get_extra_inlines() for InlineType in inlinetypes: inline_instance = InlineType(self.model, self.admin_site) extra_inline_instances.append(inline_instance) return extra_inline_instances + inlines
python
def get_inline_instances(self, request, *args, **kwargs): """ Create the inlines for the admin, including the placeholder and contentitem inlines. """ inlines = super(PlaceholderEditorAdmin, self).get_inline_instances(request, *args, **kwargs) extra_inline_instances = [] inlinetypes = self.get_extra_inlines() for InlineType in inlinetypes: inline_instance = InlineType(self.model, self.admin_site) extra_inline_instances.append(inline_instance) return extra_inline_instances + inlines
[ "def", "get_inline_instances", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "inlines", "=", "super", "(", "PlaceholderEditorAdmin", ",", "self", ")", ".", "get_inline_instances", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", "extra_inline_instances", "=", "[", "]", "inlinetypes", "=", "self", ".", "get_extra_inlines", "(", ")", "for", "InlineType", "in", "inlinetypes", ":", "inline_instance", "=", "InlineType", "(", "self", ".", "model", ",", "self", ".", "admin_site", ")", "extra_inline_instances", ".", "append", "(", "inline_instance", ")", "return", "extra_inline_instances", "+", "inlines" ]
Create the inlines for the admin, including the placeholder and contentitem inlines.
[ "Create", "the", "inlines", "for", "the", "admin", "including", "the", "placeholder", "and", "contentitem", "inlines", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/admin/placeholdereditor.py#L188-L200
django-fluent/django-fluent-contents
fluent_contents/admin/placeholdereditor.py
PlaceholderEditorAdmin.get_placeholder_data_view
def get_placeholder_data_view(self, request, object_id): """ Return the placeholder data as dictionary. This is used in the client for the "copy" functionality. """ language = 'en' #request.POST['language'] with translation.override(language): # Use generic solution here, don't assume django-parler is used now. obj = self.get_object(request, object_id) if obj is None: json = {'success': False, 'error': 'Page not found'} status = 404 elif not self.has_change_permission(request, obj): json = {'success': False, 'error': 'No access to page'} status = 403 else: # Fetch the forms that would be displayed, # return the data as serialized form data. status = 200 json = { 'success': True, 'object_id': object_id, 'language_code': language, 'formset_forms': self._get_object_formset_data(request, obj), } return JsonResponse(json, status=status)
python
def get_placeholder_data_view(self, request, object_id): """ Return the placeholder data as dictionary. This is used in the client for the "copy" functionality. """ language = 'en' #request.POST['language'] with translation.override(language): # Use generic solution here, don't assume django-parler is used now. obj = self.get_object(request, object_id) if obj is None: json = {'success': False, 'error': 'Page not found'} status = 404 elif not self.has_change_permission(request, obj): json = {'success': False, 'error': 'No access to page'} status = 403 else: # Fetch the forms that would be displayed, # return the data as serialized form data. status = 200 json = { 'success': True, 'object_id': object_id, 'language_code': language, 'formset_forms': self._get_object_formset_data(request, obj), } return JsonResponse(json, status=status)
[ "def", "get_placeholder_data_view", "(", "self", ",", "request", ",", "object_id", ")", ":", "language", "=", "'en'", "#request.POST['language']", "with", "translation", ".", "override", "(", "language", ")", ":", "# Use generic solution here, don't assume django-parler is used now.", "obj", "=", "self", ".", "get_object", "(", "request", ",", "object_id", ")", "if", "obj", "is", "None", ":", "json", "=", "{", "'success'", ":", "False", ",", "'error'", ":", "'Page not found'", "}", "status", "=", "404", "elif", "not", "self", ".", "has_change_permission", "(", "request", ",", "obj", ")", ":", "json", "=", "{", "'success'", ":", "False", ",", "'error'", ":", "'No access to page'", "}", "status", "=", "403", "else", ":", "# Fetch the forms that would be displayed,", "# return the data as serialized form data.", "status", "=", "200", "json", "=", "{", "'success'", ":", "True", ",", "'object_id'", ":", "object_id", ",", "'language_code'", ":", "language", ",", "'formset_forms'", ":", "self", ".", "_get_object_formset_data", "(", "request", ",", "obj", ")", ",", "}", "return", "JsonResponse", "(", "json", ",", "status", "=", "status", ")" ]
Return the placeholder data as dictionary. This is used in the client for the "copy" functionality.
[ "Return", "the", "placeholder", "data", "as", "dictionary", ".", "This", "is", "used", "in", "the", "client", "for", "the", "copy", "functionality", "." ]
train
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/admin/placeholdereditor.py#L221-L247
rmax/scrapy-inline-requests
src/inline_requests/__init__.py
inline_requests
def inline_requests(method_or_func): """A decorator to use coroutine-like spider callbacks. Example: .. code:: python class MySpider(Spider): @inline_callbacks def parse(self, response): next_url = response.urjoin('?next') try: next_resp = yield Request(next_url) except Exception as e: self.logger.exception("An error occurred.") return else: yield {"next_url": next_resp.url} You must conform with the following conventions: * The decorated method must be a spider method. * The decorated method must use the ``yield`` keyword or return a generator. * The decorated method must accept ``response`` as the first argument. * The decorated method should yield ``Request`` objects without neither ``callback`` nor ``errback`` set. If your requests don't come back to the generator try setting the flag to handle all http statuses: .. code:: python request.meta['handle_httpstatus_all'] = True """ args = get_args(method_or_func) if not args: raise TypeError("Function must accept at least one argument.") # XXX: hardcoded convention of 'self' as first argument for methods if args[0] == 'self': def wrapper(self, response, **kwargs): callback = create_bound_method(method_or_func, self) genwrapper = RequestGenerator(callback, **kwargs) return genwrapper(response) else: warnings.warn("Decorating a non-method function will be deprecated", ScrapyDeprecationWarning, stacklevel=1) def wrapper(response, **kwargs): genwrapper = RequestGenerator(method_or_func, **kwargs) return genwrapper(response) return wraps(method_or_func)(wrapper)
python
def inline_requests(method_or_func): """A decorator to use coroutine-like spider callbacks. Example: .. code:: python class MySpider(Spider): @inline_callbacks def parse(self, response): next_url = response.urjoin('?next') try: next_resp = yield Request(next_url) except Exception as e: self.logger.exception("An error occurred.") return else: yield {"next_url": next_resp.url} You must conform with the following conventions: * The decorated method must be a spider method. * The decorated method must use the ``yield`` keyword or return a generator. * The decorated method must accept ``response`` as the first argument. * The decorated method should yield ``Request`` objects without neither ``callback`` nor ``errback`` set. If your requests don't come back to the generator try setting the flag to handle all http statuses: .. code:: python request.meta['handle_httpstatus_all'] = True """ args = get_args(method_or_func) if not args: raise TypeError("Function must accept at least one argument.") # XXX: hardcoded convention of 'self' as first argument for methods if args[0] == 'self': def wrapper(self, response, **kwargs): callback = create_bound_method(method_or_func, self) genwrapper = RequestGenerator(callback, **kwargs) return genwrapper(response) else: warnings.warn("Decorating a non-method function will be deprecated", ScrapyDeprecationWarning, stacklevel=1) def wrapper(response, **kwargs): genwrapper = RequestGenerator(method_or_func, **kwargs) return genwrapper(response) return wraps(method_or_func)(wrapper)
[ "def", "inline_requests", "(", "method_or_func", ")", ":", "args", "=", "get_args", "(", "method_or_func", ")", "if", "not", "args", ":", "raise", "TypeError", "(", "\"Function must accept at least one argument.\"", ")", "# XXX: hardcoded convention of 'self' as first argument for methods", "if", "args", "[", "0", "]", "==", "'self'", ":", "def", "wrapper", "(", "self", ",", "response", ",", "*", "*", "kwargs", ")", ":", "callback", "=", "create_bound_method", "(", "method_or_func", ",", "self", ")", "genwrapper", "=", "RequestGenerator", "(", "callback", ",", "*", "*", "kwargs", ")", "return", "genwrapper", "(", "response", ")", "else", ":", "warnings", ".", "warn", "(", "\"Decorating a non-method function will be deprecated\"", ",", "ScrapyDeprecationWarning", ",", "stacklevel", "=", "1", ")", "def", "wrapper", "(", "response", ",", "*", "*", "kwargs", ")", ":", "genwrapper", "=", "RequestGenerator", "(", "method_or_func", ",", "*", "*", "kwargs", ")", "return", "genwrapper", "(", "response", ")", "return", "wraps", "(", "method_or_func", ")", "(", "wrapper", ")" ]
A decorator to use coroutine-like spider callbacks. Example: .. code:: python class MySpider(Spider): @inline_callbacks def parse(self, response): next_url = response.urjoin('?next') try: next_resp = yield Request(next_url) except Exception as e: self.logger.exception("An error occurred.") return else: yield {"next_url": next_resp.url} You must conform with the following conventions: * The decorated method must be a spider method. * The decorated method must use the ``yield`` keyword or return a generator. * The decorated method must accept ``response`` as the first argument. * The decorated method should yield ``Request`` objects without neither ``callback`` nor ``errback`` set. If your requests don't come back to the generator try setting the flag to handle all http statuses: .. code:: python request.meta['handle_httpstatus_all'] = True
[ "A", "decorator", "to", "use", "coroutine", "-", "like", "spider", "callbacks", "." ]
train
https://github.com/rmax/scrapy-inline-requests/blob/2cbbb66e6e97260b7e126aa9d8ecde1393a554c9/src/inline_requests/__init__.py#L19-L74
rmax/scrapy-inline-requests
src/inline_requests/utils.py
get_args
def get_args(method_or_func): """Returns method or function arguments.""" try: # Python 3.0+ args = list(inspect.signature(method_or_func).parameters.keys()) except AttributeError: # Python 2.7 args = inspect.getargspec(method_or_func).args return args
python
def get_args(method_or_func): """Returns method or function arguments.""" try: # Python 3.0+ args = list(inspect.signature(method_or_func).parameters.keys()) except AttributeError: # Python 2.7 args = inspect.getargspec(method_or_func).args return args
[ "def", "get_args", "(", "method_or_func", ")", ":", "try", ":", "# Python 3.0+", "args", "=", "list", "(", "inspect", ".", "signature", "(", "method_or_func", ")", ".", "parameters", ".", "keys", "(", ")", ")", "except", "AttributeError", ":", "# Python 2.7", "args", "=", "inspect", ".", "getargspec", "(", "method_or_func", ")", ".", "args", "return", "args" ]
Returns method or function arguments.
[ "Returns", "method", "or", "function", "arguments", "." ]
train
https://github.com/rmax/scrapy-inline-requests/blob/2cbbb66e6e97260b7e126aa9d8ecde1393a554c9/src/inline_requests/utils.py#L4-L12
rmax/scrapy-inline-requests
src/inline_requests/generator.py
RequestGenerator._unwindGenerator
def _unwindGenerator(self, generator, _prev=None): """Unwind (resume) generator.""" while True: if _prev: ret, _prev = _prev, None else: try: ret = next(generator) except StopIteration: break if isinstance(ret, Request): if ret.callback: warnings.warn("Got a request with callback set, bypassing " "the generator wrapper. Generator may not " "be able to resume. %s" % ret) elif ret.errback: # By Scrapy defaults, a request without callback defaults to # self.parse spider method. warnings.warn("Got a request with errback set, bypassing " "the generator wrapper. Generator may not " "be able to resume. %s" % ret) else: yield self._wrapRequest(ret, generator) return # A request with callbacks, item or None object. yield ret
python
def _unwindGenerator(self, generator, _prev=None): """Unwind (resume) generator.""" while True: if _prev: ret, _prev = _prev, None else: try: ret = next(generator) except StopIteration: break if isinstance(ret, Request): if ret.callback: warnings.warn("Got a request with callback set, bypassing " "the generator wrapper. Generator may not " "be able to resume. %s" % ret) elif ret.errback: # By Scrapy defaults, a request without callback defaults to # self.parse spider method. warnings.warn("Got a request with errback set, bypassing " "the generator wrapper. Generator may not " "be able to resume. %s" % ret) else: yield self._wrapRequest(ret, generator) return # A request with callbacks, item or None object. yield ret
[ "def", "_unwindGenerator", "(", "self", ",", "generator", ",", "_prev", "=", "None", ")", ":", "while", "True", ":", "if", "_prev", ":", "ret", ",", "_prev", "=", "_prev", ",", "None", "else", ":", "try", ":", "ret", "=", "next", "(", "generator", ")", "except", "StopIteration", ":", "break", "if", "isinstance", "(", "ret", ",", "Request", ")", ":", "if", "ret", ".", "callback", ":", "warnings", ".", "warn", "(", "\"Got a request with callback set, bypassing \"", "\"the generator wrapper. Generator may not \"", "\"be able to resume. %s\"", "%", "ret", ")", "elif", "ret", ".", "errback", ":", "# By Scrapy defaults, a request without callback defaults to", "# self.parse spider method.", "warnings", ".", "warn", "(", "\"Got a request with errback set, bypassing \"", "\"the generator wrapper. Generator may not \"", "\"be able to resume. %s\"", "%", "ret", ")", "else", ":", "yield", "self", ".", "_wrapRequest", "(", "ret", ",", "generator", ")", "return", "# A request with callbacks, item or None object.", "yield", "ret" ]
Unwind (resume) generator.
[ "Unwind", "(", "resume", ")", "generator", "." ]
train
https://github.com/rmax/scrapy-inline-requests/blob/2cbbb66e6e97260b7e126aa9d8ecde1393a554c9/src/inline_requests/generator.py#L44-L71
vimalloc/flask-jwt-simple
flask_jwt_simple/view_decorators.py
jwt_required
def jwt_required(fn): """ If you decorate a view with this, it will ensure that the requester has a valid JWT before calling the actual view. :param fn: The view function to decorate """ @wraps(fn) def wrapper(*args, **kwargs): jwt_data = _decode_jwt_from_headers() ctx_stack.top.jwt = jwt_data return fn(*args, **kwargs) return wrapper
python
def jwt_required(fn): """ If you decorate a view with this, it will ensure that the requester has a valid JWT before calling the actual view. :param fn: The view function to decorate """ @wraps(fn) def wrapper(*args, **kwargs): jwt_data = _decode_jwt_from_headers() ctx_stack.top.jwt = jwt_data return fn(*args, **kwargs) return wrapper
[ "def", "jwt_required", "(", "fn", ")", ":", "@", "wraps", "(", "fn", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "jwt_data", "=", "_decode_jwt_from_headers", "(", ")", "ctx_stack", ".", "top", ".", "jwt", "=", "jwt_data", "return", "fn", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "wrapper" ]
If you decorate a view with this, it will ensure that the requester has a valid JWT before calling the actual view. :param fn: The view function to decorate
[ "If", "you", "decorate", "a", "view", "with", "this", "it", "will", "ensure", "that", "the", "requester", "has", "a", "valid", "JWT", "before", "calling", "the", "actual", "view", "." ]
train
https://github.com/vimalloc/flask-jwt-simple/blob/ed930340cfcff5a6ddc49248d4682e87204dd3be/flask_jwt_simple/view_decorators.py#L14-L26
vimalloc/flask-jwt-simple
flask_jwt_simple/view_decorators.py
jwt_optional
def jwt_optional(fn): """ If you decorate a view with this, it will check the request for a valid JWT and put it into the Flask application context before calling the view. If no authorization header is present, the view will be called without the application context being changed. Other authentication errors are not affected. For example, if an expired JWT is passed in, it will still not be able to access an endpoint protected by this decorator. :param fn: The view function to decorate """ @wraps(fn) def wrapper(*args, **kwargs): try: jwt_data = _decode_jwt_from_headers() ctx_stack.top.jwt = jwt_data except (NoAuthorizationError, InvalidHeaderError): pass return fn(*args, **kwargs) return wrapper
python
def jwt_optional(fn): """ If you decorate a view with this, it will check the request for a valid JWT and put it into the Flask application context before calling the view. If no authorization header is present, the view will be called without the application context being changed. Other authentication errors are not affected. For example, if an expired JWT is passed in, it will still not be able to access an endpoint protected by this decorator. :param fn: The view function to decorate """ @wraps(fn) def wrapper(*args, **kwargs): try: jwt_data = _decode_jwt_from_headers() ctx_stack.top.jwt = jwt_data except (NoAuthorizationError, InvalidHeaderError): pass return fn(*args, **kwargs) return wrapper
[ "def", "jwt_optional", "(", "fn", ")", ":", "@", "wraps", "(", "fn", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "jwt_data", "=", "_decode_jwt_from_headers", "(", ")", "ctx_stack", ".", "top", ".", "jwt", "=", "jwt_data", "except", "(", "NoAuthorizationError", ",", "InvalidHeaderError", ")", ":", "pass", "return", "fn", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "wrapper" ]
If you decorate a view with this, it will check the request for a valid JWT and put it into the Flask application context before calling the view. If no authorization header is present, the view will be called without the application context being changed. Other authentication errors are not affected. For example, if an expired JWT is passed in, it will still not be able to access an endpoint protected by this decorator. :param fn: The view function to decorate
[ "If", "you", "decorate", "a", "view", "with", "this", "it", "will", "check", "the", "request", "for", "a", "valid", "JWT", "and", "put", "it", "into", "the", "Flask", "application", "context", "before", "calling", "the", "view", ".", "If", "no", "authorization", "header", "is", "present", "the", "view", "will", "be", "called", "without", "the", "application", "context", "being", "changed", ".", "Other", "authentication", "errors", "are", "not", "affected", ".", "For", "example", "if", "an", "expired", "JWT", "is", "passed", "in", "it", "will", "still", "not", "be", "able", "to", "access", "an", "endpoint", "protected", "by", "this", "decorator", "." ]
train
https://github.com/vimalloc/flask-jwt-simple/blob/ed930340cfcff5a6ddc49248d4682e87204dd3be/flask_jwt_simple/view_decorators.py#L29-L48
vimalloc/flask-jwt-simple
flask_jwt_simple/utils.py
decode_jwt
def decode_jwt(encoded_token): """ Returns the decoded token from an encoded one. This does all the checks to insure that the decoded token is valid before returning it. """ secret = config.decode_key algorithm = config.algorithm audience = config.audience return jwt.decode(encoded_token, secret, algorithms=[algorithm], audience=audience)
python
def decode_jwt(encoded_token): """ Returns the decoded token from an encoded one. This does all the checks to insure that the decoded token is valid before returning it. """ secret = config.decode_key algorithm = config.algorithm audience = config.audience return jwt.decode(encoded_token, secret, algorithms=[algorithm], audience=audience)
[ "def", "decode_jwt", "(", "encoded_token", ")", ":", "secret", "=", "config", ".", "decode_key", "algorithm", "=", "config", ".", "algorithm", "audience", "=", "config", ".", "audience", "return", "jwt", ".", "decode", "(", "encoded_token", ",", "secret", ",", "algorithms", "=", "[", "algorithm", "]", ",", "audience", "=", "audience", ")" ]
Returns the decoded token from an encoded one. This does all the checks to insure that the decoded token is valid before returning it.
[ "Returns", "the", "decoded", "token", "from", "an", "encoded", "one", ".", "This", "does", "all", "the", "checks", "to", "insure", "that", "the", "decoded", "token", "is", "valid", "before", "returning", "it", "." ]
train
https://github.com/vimalloc/flask-jwt-simple/blob/ed930340cfcff5a6ddc49248d4682e87204dd3be/flask_jwt_simple/utils.py#L36-L44
vimalloc/flask-jwt-simple
flask_jwt_simple/jwt_manager.py
JWTManager.init_app
def init_app(self, app): """ Register this extension with the flask app :param app: A flask application """ # Save this so we can use it later in the extension if not hasattr(app, 'extensions'): # pragma: no cover app.extensions = {} app.extensions['flask-jwt-simple'] = self # Set all the default configurations for this extension self._set_default_configuration_options(app) self._set_error_handler_callbacks(app) # Set propagate exceptions, so all of our error handlers properly # work in production app.config['PROPAGATE_EXCEPTIONS'] = True
python
def init_app(self, app): """ Register this extension with the flask app :param app: A flask application """ # Save this so we can use it later in the extension if not hasattr(app, 'extensions'): # pragma: no cover app.extensions = {} app.extensions['flask-jwt-simple'] = self # Set all the default configurations for this extension self._set_default_configuration_options(app) self._set_error_handler_callbacks(app) # Set propagate exceptions, so all of our error handlers properly # work in production app.config['PROPAGATE_EXCEPTIONS'] = True
[ "def", "init_app", "(", "self", ",", "app", ")", ":", "# Save this so we can use it later in the extension", "if", "not", "hasattr", "(", "app", ",", "'extensions'", ")", ":", "# pragma: no cover", "app", ".", "extensions", "=", "{", "}", "app", ".", "extensions", "[", "'flask-jwt-simple'", "]", "=", "self", "# Set all the default configurations for this extension", "self", ".", "_set_default_configuration_options", "(", "app", ")", "self", ".", "_set_error_handler_callbacks", "(", "app", ")", "# Set propagate exceptions, so all of our error handlers properly", "# work in production", "app", ".", "config", "[", "'PROPAGATE_EXCEPTIONS'", "]", "=", "True" ]
Register this extension with the flask app :param app: A flask application
[ "Register", "this", "extension", "with", "the", "flask", "app" ]
train
https://github.com/vimalloc/flask-jwt-simple/blob/ed930340cfcff5a6ddc49248d4682e87204dd3be/flask_jwt_simple/jwt_manager.py#L40-L57
vimalloc/flask-jwt-simple
flask_jwt_simple/jwt_manager.py
JWTManager._set_error_handler_callbacks
def _set_error_handler_callbacks(self, app): """ Sets the error handler callbacks used by this extension """ @app.errorhandler(NoAuthorizationError) def handle_no_auth_error(e): return self._unauthorized_callback(str(e)) @app.errorhandler(InvalidHeaderError) def handle_invalid_header_error(e): return self._invalid_token_callback(str(e)) @app.errorhandler(jwt.ExpiredSignatureError) def handle_expired_error(e): return self._expired_token_callback() @app.errorhandler(jwt.InvalidTokenError) def handle_invalid_token_error(e): return self._invalid_token_callback(str(e))
python
def _set_error_handler_callbacks(self, app): """ Sets the error handler callbacks used by this extension """ @app.errorhandler(NoAuthorizationError) def handle_no_auth_error(e): return self._unauthorized_callback(str(e)) @app.errorhandler(InvalidHeaderError) def handle_invalid_header_error(e): return self._invalid_token_callback(str(e)) @app.errorhandler(jwt.ExpiredSignatureError) def handle_expired_error(e): return self._expired_token_callback() @app.errorhandler(jwt.InvalidTokenError) def handle_invalid_token_error(e): return self._invalid_token_callback(str(e))
[ "def", "_set_error_handler_callbacks", "(", "self", ",", "app", ")", ":", "@", "app", ".", "errorhandler", "(", "NoAuthorizationError", ")", "def", "handle_no_auth_error", "(", "e", ")", ":", "return", "self", ".", "_unauthorized_callback", "(", "str", "(", "e", ")", ")", "@", "app", ".", "errorhandler", "(", "InvalidHeaderError", ")", "def", "handle_invalid_header_error", "(", "e", ")", ":", "return", "self", ".", "_invalid_token_callback", "(", "str", "(", "e", ")", ")", "@", "app", ".", "errorhandler", "(", "jwt", ".", "ExpiredSignatureError", ")", "def", "handle_expired_error", "(", "e", ")", ":", "return", "self", ".", "_expired_token_callback", "(", ")", "@", "app", ".", "errorhandler", "(", "jwt", ".", "InvalidTokenError", ")", "def", "handle_invalid_token_error", "(", "e", ")", ":", "return", "self", ".", "_invalid_token_callback", "(", "str", "(", "e", ")", ")" ]
Sets the error handler callbacks used by this extension
[ "Sets", "the", "error", "handler", "callbacks", "used", "by", "this", "extension" ]
train
https://github.com/vimalloc/flask-jwt-simple/blob/ed930340cfcff5a6ddc49248d4682e87204dd3be/flask_jwt_simple/jwt_manager.py#L59-L77
vimalloc/flask-jwt-simple
flask_jwt_simple/jwt_manager.py
JWTManager._set_default_configuration_options
def _set_default_configuration_options(app): """ Sets the default configuration options used by this extension """ # Options for JWTs when the TOKEN_LOCATION is headers app.config.setdefault('JWT_HEADER_NAME', 'Authorization') app.config.setdefault('JWT_HEADER_TYPE', 'Bearer') # How long an a token created with 'create_jwt' will last before # it expires (when using the default jwt_data_callback function). app.config.setdefault('JWT_EXPIRES', datetime.timedelta(hours=1)) # What algorithm to use to sign the token. See here for a list of options: # https://github.com/jpadilla/pyjwt/blob/master/jwt/api_jwt.py app.config.setdefault('JWT_ALGORITHM', 'HS256') # Key that acts as the identity for the JWT app.config.setdefault('JWT_IDENTITY_CLAIM', 'sub') # Expected value of the audience claim app.config.setdefault('JWT_DECODE_AUDIENCE', None) # Secret key to sign JWTs with. Only used if a symmetric algorithm is # used (such as the HS* algorithms). app.config.setdefault('JWT_SECRET_KEY', None) # Keys to sign JWTs with when use when using an asymmetric # (public/private key) algorithms, such as RS* or EC* app.config.setdefault('JWT_PRIVATE_KEY', None) app.config.setdefault('JWT_PUBLIC_KEY', None)
python
def _set_default_configuration_options(app): """ Sets the default configuration options used by this extension """ # Options for JWTs when the TOKEN_LOCATION is headers app.config.setdefault('JWT_HEADER_NAME', 'Authorization') app.config.setdefault('JWT_HEADER_TYPE', 'Bearer') # How long an a token created with 'create_jwt' will last before # it expires (when using the default jwt_data_callback function). app.config.setdefault('JWT_EXPIRES', datetime.timedelta(hours=1)) # What algorithm to use to sign the token. See here for a list of options: # https://github.com/jpadilla/pyjwt/blob/master/jwt/api_jwt.py app.config.setdefault('JWT_ALGORITHM', 'HS256') # Key that acts as the identity for the JWT app.config.setdefault('JWT_IDENTITY_CLAIM', 'sub') # Expected value of the audience claim app.config.setdefault('JWT_DECODE_AUDIENCE', None) # Secret key to sign JWTs with. Only used if a symmetric algorithm is # used (such as the HS* algorithms). app.config.setdefault('JWT_SECRET_KEY', None) # Keys to sign JWTs with when use when using an asymmetric # (public/private key) algorithms, such as RS* or EC* app.config.setdefault('JWT_PRIVATE_KEY', None) app.config.setdefault('JWT_PUBLIC_KEY', None)
[ "def", "_set_default_configuration_options", "(", "app", ")", ":", "# Options for JWTs when the TOKEN_LOCATION is headers", "app", ".", "config", ".", "setdefault", "(", "'JWT_HEADER_NAME'", ",", "'Authorization'", ")", "app", ".", "config", ".", "setdefault", "(", "'JWT_HEADER_TYPE'", ",", "'Bearer'", ")", "# How long an a token created with 'create_jwt' will last before", "# it expires (when using the default jwt_data_callback function).", "app", ".", "config", ".", "setdefault", "(", "'JWT_EXPIRES'", ",", "datetime", ".", "timedelta", "(", "hours", "=", "1", ")", ")", "# What algorithm to use to sign the token. See here for a list of options:", "# https://github.com/jpadilla/pyjwt/blob/master/jwt/api_jwt.py", "app", ".", "config", ".", "setdefault", "(", "'JWT_ALGORITHM'", ",", "'HS256'", ")", "# Key that acts as the identity for the JWT", "app", ".", "config", ".", "setdefault", "(", "'JWT_IDENTITY_CLAIM'", ",", "'sub'", ")", "# Expected value of the audience claim", "app", ".", "config", ".", "setdefault", "(", "'JWT_DECODE_AUDIENCE'", ",", "None", ")", "# Secret key to sign JWTs with. Only used if a symmetric algorithm is", "# used (such as the HS* algorithms).", "app", ".", "config", ".", "setdefault", "(", "'JWT_SECRET_KEY'", ",", "None", ")", "# Keys to sign JWTs with when use when using an asymmetric", "# (public/private key) algorithms, such as RS* or EC*", "app", ".", "config", ".", "setdefault", "(", "'JWT_PRIVATE_KEY'", ",", "None", ")", "app", ".", "config", ".", "setdefault", "(", "'JWT_PUBLIC_KEY'", ",", "None", ")" ]
Sets the default configuration options used by this extension
[ "Sets", "the", "default", "configuration", "options", "used", "by", "this", "extension" ]
train
https://github.com/vimalloc/flask-jwt-simple/blob/ed930340cfcff5a6ddc49248d4682e87204dd3be/flask_jwt_simple/jwt_manager.py#L80-L109
zachwill/fred
fred/api.py
category
def category(**kwargs): """Get a category.""" if 'series' in kwargs: kwargs.pop('series') path = 'series' else: path = None return Fred().category(path, **kwargs)
python
def category(**kwargs): """Get a category.""" if 'series' in kwargs: kwargs.pop('series') path = 'series' else: path = None return Fred().category(path, **kwargs)
[ "def", "category", "(", "*", "*", "kwargs", ")", ":", "if", "'series'", "in", "kwargs", ":", "kwargs", ".", "pop", "(", "'series'", ")", "path", "=", "'series'", "else", ":", "path", "=", "None", "return", "Fred", "(", ")", ".", "category", "(", "path", ",", "*", "*", "kwargs", ")" ]
Get a category.
[ "Get", "a", "category", "." ]
train
https://github.com/zachwill/fred/blob/8fb8975e8b4fd8a550f586027dd75cbc2fe225f0/fred/api.py#L18-L25
zachwill/fred
fred/api.py
releases
def releases(release_id=None, **kwargs): """Get all releases of economic data.""" if not 'id' in kwargs and release_id is not None: kwargs['release_id'] = release_id return Fred().release(**kwargs) return Fred().releases(**kwargs)
python
def releases(release_id=None, **kwargs): """Get all releases of economic data.""" if not 'id' in kwargs and release_id is not None: kwargs['release_id'] = release_id return Fred().release(**kwargs) return Fred().releases(**kwargs)
[ "def", "releases", "(", "release_id", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "'id'", "in", "kwargs", "and", "release_id", "is", "not", "None", ":", "kwargs", "[", "'release_id'", "]", "=", "release_id", "return", "Fred", "(", ")", ".", "release", "(", "*", "*", "kwargs", ")", "return", "Fred", "(", ")", ".", "releases", "(", "*", "*", "kwargs", ")" ]
Get all releases of economic data.
[ "Get", "all", "releases", "of", "economic", "data", "." ]
train
https://github.com/zachwill/fred/blob/8fb8975e8b4fd8a550f586027dd75cbc2fe225f0/fred/api.py#L62-L67
zachwill/fred
fred/api.py
series
def series(identifier=None, **kwargs): """Get an economic data series.""" if identifier: kwargs['series_id'] = identifier if 'release' in kwargs: kwargs.pop('release') path = 'release' elif 'releases' in kwargs: kwargs.pop('releases') path = 'release' else: path = None return Fred().series(path, **kwargs)
python
def series(identifier=None, **kwargs): """Get an economic data series.""" if identifier: kwargs['series_id'] = identifier if 'release' in kwargs: kwargs.pop('release') path = 'release' elif 'releases' in kwargs: kwargs.pop('releases') path = 'release' else: path = None return Fred().series(path, **kwargs)
[ "def", "series", "(", "identifier", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "identifier", ":", "kwargs", "[", "'series_id'", "]", "=", "identifier", "if", "'release'", "in", "kwargs", ":", "kwargs", ".", "pop", "(", "'release'", ")", "path", "=", "'release'", "elif", "'releases'", "in", "kwargs", ":", "kwargs", ".", "pop", "(", "'releases'", ")", "path", "=", "'release'", "else", ":", "path", "=", "None", "return", "Fred", "(", ")", ".", "series", "(", "path", ",", "*", "*", "kwargs", ")" ]
Get an economic data series.
[ "Get", "an", "economic", "data", "series", "." ]
train
https://github.com/zachwill/fred/blob/8fb8975e8b4fd8a550f586027dd75cbc2fe225f0/fred/api.py#L79-L91
zachwill/fred
fred/api.py
source
def source(source_id=None, **kwargs): """Get a source of economic data.""" if source_id is not None: kwargs['source_id'] = source_id elif 'id' in kwargs: source_id = kwargs.pop('id') kwargs['source_id'] = source_id if 'releases' in kwargs: kwargs.pop('releases') path = 'releases' else: path = None return Fred().source(path, **kwargs)
python
def source(source_id=None, **kwargs): """Get a source of economic data.""" if source_id is not None: kwargs['source_id'] = source_id elif 'id' in kwargs: source_id = kwargs.pop('id') kwargs['source_id'] = source_id if 'releases' in kwargs: kwargs.pop('releases') path = 'releases' else: path = None return Fred().source(path, **kwargs)
[ "def", "source", "(", "source_id", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "source_id", "is", "not", "None", ":", "kwargs", "[", "'source_id'", "]", "=", "source_id", "elif", "'id'", "in", "kwargs", ":", "source_id", "=", "kwargs", ".", "pop", "(", "'id'", ")", "kwargs", "[", "'source_id'", "]", "=", "source_id", "if", "'releases'", "in", "kwargs", ":", "kwargs", ".", "pop", "(", "'releases'", ")", "path", "=", "'releases'", "else", ":", "path", "=", "None", "return", "Fred", "(", ")", ".", "source", "(", "path", ",", "*", "*", "kwargs", ")" ]
Get a source of economic data.
[ "Get", "a", "source", "of", "economic", "data", "." ]
train
https://github.com/zachwill/fred/blob/8fb8975e8b4fd8a550f586027dd75cbc2fe225f0/fred/api.py#L124-L136
zachwill/fred
fred/api.py
sources
def sources(source_id=None, **kwargs): """Get the sources of economic data.""" if source_id or 'id' in kwargs: return source(source_id, **kwargs) return Fred().sources(**kwargs)
python
def sources(source_id=None, **kwargs): """Get the sources of economic data.""" if source_id or 'id' in kwargs: return source(source_id, **kwargs) return Fred().sources(**kwargs)
[ "def", "sources", "(", "source_id", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "source_id", "or", "'id'", "in", "kwargs", ":", "return", "source", "(", "source_id", ",", "*", "*", "kwargs", ")", "return", "Fred", "(", ")", ".", "sources", "(", "*", "*", "kwargs", ")" ]
Get the sources of economic data.
[ "Get", "the", "sources", "of", "economic", "data", "." ]
train
https://github.com/zachwill/fred/blob/8fb8975e8b4fd8a550f586027dd75cbc2fe225f0/fred/api.py#L139-L143
zachwill/fred
fred/core.py
Fred._create_path
def _create_path(self, *args): """Create the URL path with the Fred endpoint and given arguments.""" args = filter(None, args) path = self.endpoint + '/'.join(args) return path
python
def _create_path(self, *args): """Create the URL path with the Fred endpoint and given arguments.""" args = filter(None, args) path = self.endpoint + '/'.join(args) return path
[ "def", "_create_path", "(", "self", ",", "*", "args", ")", ":", "args", "=", "filter", "(", "None", ",", "args", ")", "path", "=", "self", ".", "endpoint", "+", "'/'", ".", "join", "(", "args", ")", "return", "path" ]
Create the URL path with the Fred endpoint and given arguments.
[ "Create", "the", "URL", "path", "with", "the", "Fred", "endpoint", "and", "given", "arguments", "." ]
train
https://github.com/zachwill/fred/blob/8fb8975e8b4fd8a550f586027dd75cbc2fe225f0/fred/core.py#L32-L36
zachwill/fred
fred/core.py
Fred.get
def get(self, *args, **kwargs): """Perform a GET request againt the Fred API endpoint.""" location = args[0] params = self._get_keywords(location, kwargs) url = self._create_path(*args) request = requests.get(url, params=params) content = request.content self._request = request return self._output(content)
python
def get(self, *args, **kwargs): """Perform a GET request againt the Fred API endpoint.""" location = args[0] params = self._get_keywords(location, kwargs) url = self._create_path(*args) request = requests.get(url, params=params) content = request.content self._request = request return self._output(content)
[ "def", "get", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "location", "=", "args", "[", "0", "]", "params", "=", "self", ".", "_get_keywords", "(", "location", ",", "kwargs", ")", "url", "=", "self", ".", "_create_path", "(", "*", "args", ")", "request", "=", "requests", ".", "get", "(", "url", ",", "params", "=", "params", ")", "content", "=", "request", ".", "content", "self", ".", "_request", "=", "request", "return", "self", ".", "_output", "(", "content", ")" ]
Perform a GET request againt the Fred API endpoint.
[ "Perform", "a", "GET", "request", "againt", "the", "Fred", "API", "endpoint", "." ]
train
https://github.com/zachwill/fred/blob/8fb8975e8b4fd8a550f586027dd75cbc2fe225f0/fred/core.py#L38-L46
zachwill/fred
fred/core.py
Fred._get_keywords
def _get_keywords(self, location, keywords): """Format GET request's parameters from keywords.""" if 'xml' in keywords: keywords.pop('xml') self.xml = True else: keywords['file_type'] = 'json' if 'id' in keywords: if location != 'series': location = location.rstrip('s') key = '%s_id' % location value = keywords.pop('id') keywords[key] = value if 'start' in keywords: time = keywords.pop('start') keywords['realtime_start'] = time if 'end' in keywords: time = keywords.pop('end') keywords['realtime_end'] = time if 'sort' in keywords: order = keywords.pop('sort') keywords['sort_order'] = order keywords['api_key'] = self.api_key return keywords
python
def _get_keywords(self, location, keywords): """Format GET request's parameters from keywords.""" if 'xml' in keywords: keywords.pop('xml') self.xml = True else: keywords['file_type'] = 'json' if 'id' in keywords: if location != 'series': location = location.rstrip('s') key = '%s_id' % location value = keywords.pop('id') keywords[key] = value if 'start' in keywords: time = keywords.pop('start') keywords['realtime_start'] = time if 'end' in keywords: time = keywords.pop('end') keywords['realtime_end'] = time if 'sort' in keywords: order = keywords.pop('sort') keywords['sort_order'] = order keywords['api_key'] = self.api_key return keywords
[ "def", "_get_keywords", "(", "self", ",", "location", ",", "keywords", ")", ":", "if", "'xml'", "in", "keywords", ":", "keywords", ".", "pop", "(", "'xml'", ")", "self", ".", "xml", "=", "True", "else", ":", "keywords", "[", "'file_type'", "]", "=", "'json'", "if", "'id'", "in", "keywords", ":", "if", "location", "!=", "'series'", ":", "location", "=", "location", ".", "rstrip", "(", "'s'", ")", "key", "=", "'%s_id'", "%", "location", "value", "=", "keywords", ".", "pop", "(", "'id'", ")", "keywords", "[", "key", "]", "=", "value", "if", "'start'", "in", "keywords", ":", "time", "=", "keywords", ".", "pop", "(", "'start'", ")", "keywords", "[", "'realtime_start'", "]", "=", "time", "if", "'end'", "in", "keywords", ":", "time", "=", "keywords", ".", "pop", "(", "'end'", ")", "keywords", "[", "'realtime_end'", "]", "=", "time", "if", "'sort'", "in", "keywords", ":", "order", "=", "keywords", ".", "pop", "(", "'sort'", ")", "keywords", "[", "'sort_order'", "]", "=", "order", "keywords", "[", "'api_key'", "]", "=", "self", ".", "api_key", "return", "keywords" ]
Format GET request's parameters from keywords.
[ "Format", "GET", "request", "s", "parameters", "from", "keywords", "." ]
train
https://github.com/zachwill/fred/blob/8fb8975e8b4fd8a550f586027dd75cbc2fe225f0/fred/core.py#L48-L71
chrisdev/django-wagtail-feeds
wagtail_feeds/feeds.py
ExtendedFeed.item_extra_kwargs
def item_extra_kwargs(self, item): """ Returns an extra keyword arguments dictionary that is used with the 'add_item' call of the feed generator. Add the fields of the item, to be used by the custom feed generator. """ if use_feed_image: feed_image = item.feed_image if feed_image: image_complete_url = urljoin( self.get_site_url(), feed_image.file.url ) else: image_complete_url = "" content_field = getattr(item, self.item_content_field) try: content = expand_db_html(content_field) except: content = content_field.__html__() soup = BeautifulSoup(content, 'html.parser') # Remove style attribute to remove large botton padding for div in soup.find_all("div", {'class': 'responsive-object'}): del div['style'] # Add site url to image source for img_tag in soup.findAll('img'): if img_tag.has_attr('src'): img_tag['src'] = urljoin(self.get_site_url(), img_tag['src']) fields_to_add = { 'content': soup.prettify(formatter="html"), } if use_feed_image: fields_to_add['image'] = image_complete_url else: fields_to_add['image'] = "" return fields_to_add
python
def item_extra_kwargs(self, item): """ Returns an extra keyword arguments dictionary that is used with the 'add_item' call of the feed generator. Add the fields of the item, to be used by the custom feed generator. """ if use_feed_image: feed_image = item.feed_image if feed_image: image_complete_url = urljoin( self.get_site_url(), feed_image.file.url ) else: image_complete_url = "" content_field = getattr(item, self.item_content_field) try: content = expand_db_html(content_field) except: content = content_field.__html__() soup = BeautifulSoup(content, 'html.parser') # Remove style attribute to remove large botton padding for div in soup.find_all("div", {'class': 'responsive-object'}): del div['style'] # Add site url to image source for img_tag in soup.findAll('img'): if img_tag.has_attr('src'): img_tag['src'] = urljoin(self.get_site_url(), img_tag['src']) fields_to_add = { 'content': soup.prettify(formatter="html"), } if use_feed_image: fields_to_add['image'] = image_complete_url else: fields_to_add['image'] = "" return fields_to_add
[ "def", "item_extra_kwargs", "(", "self", ",", "item", ")", ":", "if", "use_feed_image", ":", "feed_image", "=", "item", ".", "feed_image", "if", "feed_image", ":", "image_complete_url", "=", "urljoin", "(", "self", ".", "get_site_url", "(", ")", ",", "feed_image", ".", "file", ".", "url", ")", "else", ":", "image_complete_url", "=", "\"\"", "content_field", "=", "getattr", "(", "item", ",", "self", ".", "item_content_field", ")", "try", ":", "content", "=", "expand_db_html", "(", "content_field", ")", "except", ":", "content", "=", "content_field", ".", "__html__", "(", ")", "soup", "=", "BeautifulSoup", "(", "content", ",", "'html.parser'", ")", "# Remove style attribute to remove large botton padding", "for", "div", "in", "soup", ".", "find_all", "(", "\"div\"", ",", "{", "'class'", ":", "'responsive-object'", "}", ")", ":", "del", "div", "[", "'style'", "]", "# Add site url to image source", "for", "img_tag", "in", "soup", ".", "findAll", "(", "'img'", ")", ":", "if", "img_tag", ".", "has_attr", "(", "'src'", ")", ":", "img_tag", "[", "'src'", "]", "=", "urljoin", "(", "self", ".", "get_site_url", "(", ")", ",", "img_tag", "[", "'src'", "]", ")", "fields_to_add", "=", "{", "'content'", ":", "soup", ".", "prettify", "(", "formatter", "=", "\"html\"", ")", ",", "}", "if", "use_feed_image", ":", "fields_to_add", "[", "'image'", "]", "=", "image_complete_url", "else", ":", "fields_to_add", "[", "'image'", "]", "=", "\"\"", "return", "fields_to_add" ]
Returns an extra keyword arguments dictionary that is used with the 'add_item' call of the feed generator. Add the fields of the item, to be used by the custom feed generator.
[ "Returns", "an", "extra", "keyword", "arguments", "dictionary", "that", "is", "used", "with", "the", "add_item", "call", "of", "the", "feed", "generator", ".", "Add", "the", "fields", "of", "the", "item", "to", "be", "used", "by", "the", "custom", "feed", "generator", "." ]
train
https://github.com/chrisdev/django-wagtail-feeds/blob/df377afa7fc44316d1149183201461de2d8a99ca/wagtail_feeds/feeds.py#L231-L270
caktus/django-treenav
treenav/views.py
treenav_undefined_url
def treenav_undefined_url(request, item_slug): """ Sample view demonstrating that you can provide custom handlers for undefined menu items on a per-item basis. """ item = get_object_or_404(treenav.MenuItem, slug=item_slug) # noqa # do something with item here and return an HttpResponseRedirect raise Http404
python
def treenav_undefined_url(request, item_slug): """ Sample view demonstrating that you can provide custom handlers for undefined menu items on a per-item basis. """ item = get_object_or_404(treenav.MenuItem, slug=item_slug) # noqa # do something with item here and return an HttpResponseRedirect raise Http404
[ "def", "treenav_undefined_url", "(", "request", ",", "item_slug", ")", ":", "item", "=", "get_object_or_404", "(", "treenav", ".", "MenuItem", ",", "slug", "=", "item_slug", ")", "# noqa", "# do something with item here and return an HttpResponseRedirect", "raise", "Http404" ]
Sample view demonstrating that you can provide custom handlers for undefined menu items on a per-item basis.
[ "Sample", "view", "demonstrating", "that", "you", "can", "provide", "custom", "handlers", "for", "undefined", "menu", "items", "on", "a", "per", "-", "item", "basis", "." ]
train
https://github.com/caktus/django-treenav/blob/8f81619a8598790d1c2dc7bf77ba9d8e9e9564e6/treenav/views.py#L7-L14
caktus/django-treenav
treenav/signals.py
treenav_save_other_object_handler
def treenav_save_other_object_handler(sender, instance, created, **kwargs): """ This signal attempts to update the HREF of any menu items that point to another model object, when that objects is saved. """ # import here so models don't get loaded during app loading from django.contrib.contenttypes.models import ContentType from .models import MenuItem cache_key = 'django-treenav-menumodels' if sender == MenuItem: cache.delete(cache_key) menu_models = cache.get(cache_key) if not menu_models: menu_models = [] for menu_item in MenuItem.objects.exclude(content_type__isnull=True): menu_models.append(menu_item.content_type.model_class()) cache.set(cache_key, menu_models) # only attempt to update MenuItem if sender is known to be referenced if sender in menu_models: ct = ContentType.objects.get_for_model(sender) items = MenuItem.objects.filter(content_type=ct, object_id=instance.pk) for item in items: if item.href != instance.get_absolute_url(): item.href = instance.get_absolute_url() item.save()
python
def treenav_save_other_object_handler(sender, instance, created, **kwargs): """ This signal attempts to update the HREF of any menu items that point to another model object, when that objects is saved. """ # import here so models don't get loaded during app loading from django.contrib.contenttypes.models import ContentType from .models import MenuItem cache_key = 'django-treenav-menumodels' if sender == MenuItem: cache.delete(cache_key) menu_models = cache.get(cache_key) if not menu_models: menu_models = [] for menu_item in MenuItem.objects.exclude(content_type__isnull=True): menu_models.append(menu_item.content_type.model_class()) cache.set(cache_key, menu_models) # only attempt to update MenuItem if sender is known to be referenced if sender in menu_models: ct = ContentType.objects.get_for_model(sender) items = MenuItem.objects.filter(content_type=ct, object_id=instance.pk) for item in items: if item.href != instance.get_absolute_url(): item.href = instance.get_absolute_url() item.save()
[ "def", "treenav_save_other_object_handler", "(", "sender", ",", "instance", ",", "created", ",", "*", "*", "kwargs", ")", ":", "# import here so models don't get loaded during app loading", "from", "django", ".", "contrib", ".", "contenttypes", ".", "models", "import", "ContentType", "from", ".", "models", "import", "MenuItem", "cache_key", "=", "'django-treenav-menumodels'", "if", "sender", "==", "MenuItem", ":", "cache", ".", "delete", "(", "cache_key", ")", "menu_models", "=", "cache", ".", "get", "(", "cache_key", ")", "if", "not", "menu_models", ":", "menu_models", "=", "[", "]", "for", "menu_item", "in", "MenuItem", ".", "objects", ".", "exclude", "(", "content_type__isnull", "=", "True", ")", ":", "menu_models", ".", "append", "(", "menu_item", ".", "content_type", ".", "model_class", "(", ")", ")", "cache", ".", "set", "(", "cache_key", ",", "menu_models", ")", "# only attempt to update MenuItem if sender is known to be referenced", "if", "sender", "in", "menu_models", ":", "ct", "=", "ContentType", ".", "objects", ".", "get_for_model", "(", "sender", ")", "items", "=", "MenuItem", ".", "objects", ".", "filter", "(", "content_type", "=", "ct", ",", "object_id", "=", "instance", ".", "pk", ")", "for", "item", "in", "items", ":", "if", "item", ".", "href", "!=", "instance", ".", "get_absolute_url", "(", ")", ":", "item", ".", "href", "=", "instance", ".", "get_absolute_url", "(", ")", "item", ".", "save", "(", ")" ]
This signal attempts to update the HREF of any menu items that point to another model object, when that objects is saved.
[ "This", "signal", "attempts", "to", "update", "the", "HREF", "of", "any", "menu", "items", "that", "point", "to", "another", "model", "object", "when", "that", "objects", "is", "saved", "." ]
train
https://github.com/caktus/django-treenav/blob/8f81619a8598790d1c2dc7bf77ba9d8e9e9564e6/treenav/signals.py#L5-L29
caktus/django-treenav
treenav/admin.py
MenuItemAdmin.refresh_hrefs
def refresh_hrefs(self, request): """ Refresh all the cached menu item HREFs in the database. """ for item in treenav.MenuItem.objects.all(): item.save() # refreshes the HREF self.message_user(request, _('Menu item HREFs refreshed successfully.')) info = self.model._meta.app_label, self.model._meta.model_name changelist_url = reverse('admin:%s_%s_changelist' % info, current_app=self.admin_site.name) return redirect(changelist_url)
python
def refresh_hrefs(self, request): """ Refresh all the cached menu item HREFs in the database. """ for item in treenav.MenuItem.objects.all(): item.save() # refreshes the HREF self.message_user(request, _('Menu item HREFs refreshed successfully.')) info = self.model._meta.app_label, self.model._meta.model_name changelist_url = reverse('admin:%s_%s_changelist' % info, current_app=self.admin_site.name) return redirect(changelist_url)
[ "def", "refresh_hrefs", "(", "self", ",", "request", ")", ":", "for", "item", "in", "treenav", ".", "MenuItem", ".", "objects", ".", "all", "(", ")", ":", "item", ".", "save", "(", ")", "# refreshes the HREF", "self", ".", "message_user", "(", "request", ",", "_", "(", "'Menu item HREFs refreshed successfully.'", ")", ")", "info", "=", "self", ".", "model", ".", "_meta", ".", "app_label", ",", "self", ".", "model", ".", "_meta", ".", "model_name", "changelist_url", "=", "reverse", "(", "'admin:%s_%s_changelist'", "%", "info", ",", "current_app", "=", "self", ".", "admin_site", ".", "name", ")", "return", "redirect", "(", "changelist_url", ")" ]
Refresh all the cached menu item HREFs in the database.
[ "Refresh", "all", "the", "cached", "menu", "item", "HREFs", "in", "the", "database", "." ]
train
https://github.com/caktus/django-treenav/blob/8f81619a8598790d1c2dc7bf77ba9d8e9e9564e6/treenav/admin.py#L82-L91
caktus/django-treenav
treenav/admin.py
MenuItemAdmin.clean_cache
def clean_cache(self, request): """ Remove all MenuItems from Cache. """ treenav.delete_cache() self.message_user(request, _('Cache menuitem cache cleaned successfully.')) info = self.model._meta.app_label, self.model._meta.model_name changelist_url = reverse('admin:%s_%s_changelist' % info, current_app=self.admin_site.name) return redirect(changelist_url)
python
def clean_cache(self, request): """ Remove all MenuItems from Cache. """ treenav.delete_cache() self.message_user(request, _('Cache menuitem cache cleaned successfully.')) info = self.model._meta.app_label, self.model._meta.model_name changelist_url = reverse('admin:%s_%s_changelist' % info, current_app=self.admin_site.name) return redirect(changelist_url)
[ "def", "clean_cache", "(", "self", ",", "request", ")", ":", "treenav", ".", "delete_cache", "(", ")", "self", ".", "message_user", "(", "request", ",", "_", "(", "'Cache menuitem cache cleaned successfully.'", ")", ")", "info", "=", "self", ".", "model", ".", "_meta", ".", "app_label", ",", "self", ".", "model", ".", "_meta", ".", "model_name", "changelist_url", "=", "reverse", "(", "'admin:%s_%s_changelist'", "%", "info", ",", "current_app", "=", "self", ".", "admin_site", ".", "name", ")", "return", "redirect", "(", "changelist_url", ")" ]
Remove all MenuItems from Cache.
[ "Remove", "all", "MenuItems", "from", "Cache", "." ]
train
https://github.com/caktus/django-treenav/blob/8f81619a8598790d1c2dc7bf77ba9d8e9e9564e6/treenav/admin.py#L93-L101
caktus/django-treenav
treenav/admin.py
MenuItemAdmin.rebuild_tree
def rebuild_tree(self, request): ''' Rebuilds the tree and clears the cache. ''' self.model.objects.rebuild() self.message_user(request, _('Menu Tree Rebuilt.')) return self.clean_cache(request)
python
def rebuild_tree(self, request): ''' Rebuilds the tree and clears the cache. ''' self.model.objects.rebuild() self.message_user(request, _('Menu Tree Rebuilt.')) return self.clean_cache(request)
[ "def", "rebuild_tree", "(", "self", ",", "request", ")", ":", "self", ".", "model", ".", "objects", ".", "rebuild", "(", ")", "self", ".", "message_user", "(", "request", ",", "_", "(", "'Menu Tree Rebuilt.'", ")", ")", "return", "self", ".", "clean_cache", "(", "request", ")" ]
Rebuilds the tree and clears the cache.
[ "Rebuilds", "the", "tree", "and", "clears", "the", "cache", "." ]
train
https://github.com/caktus/django-treenav/blob/8f81619a8598790d1c2dc7bf77ba9d8e9e9564e6/treenav/admin.py#L103-L109
caktus/django-treenav
treenav/admin.py
MenuItemAdmin.save_related
def save_related(self, request, form, formsets, change): """ Rebuilds the tree after saving items related to parent. """ super(MenuItemAdmin, self).save_related(request, form, formsets, change) self.model.objects.rebuild()
python
def save_related(self, request, form, formsets, change): """ Rebuilds the tree after saving items related to parent. """ super(MenuItemAdmin, self).save_related(request, form, formsets, change) self.model.objects.rebuild()
[ "def", "save_related", "(", "self", ",", "request", ",", "form", ",", "formsets", ",", "change", ")", ":", "super", "(", "MenuItemAdmin", ",", "self", ")", ".", "save_related", "(", "request", ",", "form", ",", "formsets", ",", "change", ")", "self", ".", "model", ".", "objects", ".", "rebuild", "(", ")" ]
Rebuilds the tree after saving items related to parent.
[ "Rebuilds", "the", "tree", "after", "saving", "items", "related", "to", "parent", "." ]
train
https://github.com/caktus/django-treenav/blob/8f81619a8598790d1c2dc7bf77ba9d8e9e9564e6/treenav/admin.py#L111-L116
milesgranger/gap_statistic
gap_statistic/optimalK.py
OptimalK._calculate_dispersion
def _calculate_dispersion(X: Union[pd.DataFrame, np.ndarray], labels: np.ndarray, centroids: np.ndarray) -> float: """ Calculate the dispersion between actual points and their assigned centroids """ disp = np.sum(np.sum([np.abs(inst - centroids[label]) ** 2 for inst, label in zip(X, labels)])) # type: float return disp
python
def _calculate_dispersion(X: Union[pd.DataFrame, np.ndarray], labels: np.ndarray, centroids: np.ndarray) -> float: """ Calculate the dispersion between actual points and their assigned centroids """ disp = np.sum(np.sum([np.abs(inst - centroids[label]) ** 2 for inst, label in zip(X, labels)])) # type: float return disp
[ "def", "_calculate_dispersion", "(", "X", ":", "Union", "[", "pd", ".", "DataFrame", ",", "np", ".", "ndarray", "]", ",", "labels", ":", "np", ".", "ndarray", ",", "centroids", ":", "np", ".", "ndarray", ")", "->", "float", ":", "disp", "=", "np", ".", "sum", "(", "np", ".", "sum", "(", "[", "np", ".", "abs", "(", "inst", "-", "centroids", "[", "label", "]", ")", "**", "2", "for", "inst", ",", "label", "in", "zip", "(", "X", ",", "labels", ")", "]", ")", ")", "# type: float", "return", "disp" ]
Calculate the dispersion between actual points and their assigned centroids
[ "Calculate", "the", "dispersion", "between", "actual", "points", "and", "their", "assigned", "centroids" ]
train
https://github.com/milesgranger/gap_statistic/blob/146f868febfac37823114e87819df5e8bfc16ac8/gap_statistic/optimalK.py#L91-L96
milesgranger/gap_statistic
gap_statistic/optimalK.py
OptimalK._calculate_gap
def _calculate_gap(self, X: Union[pd.DataFrame, np.ndarray], n_refs: int, n_clusters: int) -> Tuple[float, int]: """ Calculate the gap value of the given data, n_refs, and number of clusters. Return the resutling gap value and n_clusters """ # Holder for reference dispersion results ref_dispersions = np.zeros(n_refs) # type: np.ndarray # For n_references, generate random sample and perform kmeans getting resulting dispersion of each loop for i in range(n_refs): # Create new random reference set random_data = np.random.random_sample(size=X.shape) # type: np.ndarray # Fit to it, getting the centroids and labels, and add to accumulated reference dispersions array. centroids, labels = kmeans2(data=random_data, k=n_clusters, iter=10, minit='points') # type: Tuple[np.ndarray, np.ndarray] dispersion = self._calculate_dispersion(X=random_data, labels=labels, centroids=centroids) # type: float ref_dispersions[i] = dispersion # Fit cluster to original data and create dispersion calc. centroids, labels = kmeans2(data=X, k=n_clusters, iter=10, minit='points') dispersion = self._calculate_dispersion(X=X, labels=labels, centroids=centroids) # Calculate gap statistic gap_value = np.mean(np.log(ref_dispersions)) - np.log(dispersion) return gap_value, int(n_clusters)
python
def _calculate_gap(self, X: Union[pd.DataFrame, np.ndarray], n_refs: int, n_clusters: int) -> Tuple[float, int]: """ Calculate the gap value of the given data, n_refs, and number of clusters. Return the resutling gap value and n_clusters """ # Holder for reference dispersion results ref_dispersions = np.zeros(n_refs) # type: np.ndarray # For n_references, generate random sample and perform kmeans getting resulting dispersion of each loop for i in range(n_refs): # Create new random reference set random_data = np.random.random_sample(size=X.shape) # type: np.ndarray # Fit to it, getting the centroids and labels, and add to accumulated reference dispersions array. centroids, labels = kmeans2(data=random_data, k=n_clusters, iter=10, minit='points') # type: Tuple[np.ndarray, np.ndarray] dispersion = self._calculate_dispersion(X=random_data, labels=labels, centroids=centroids) # type: float ref_dispersions[i] = dispersion # Fit cluster to original data and create dispersion calc. centroids, labels = kmeans2(data=X, k=n_clusters, iter=10, minit='points') dispersion = self._calculate_dispersion(X=X, labels=labels, centroids=centroids) # Calculate gap statistic gap_value = np.mean(np.log(ref_dispersions)) - np.log(dispersion) return gap_value, int(n_clusters)
[ "def", "_calculate_gap", "(", "self", ",", "X", ":", "Union", "[", "pd", ".", "DataFrame", ",", "np", ".", "ndarray", "]", ",", "n_refs", ":", "int", ",", "n_clusters", ":", "int", ")", "->", "Tuple", "[", "float", ",", "int", "]", ":", "# Holder for reference dispersion results", "ref_dispersions", "=", "np", ".", "zeros", "(", "n_refs", ")", "# type: np.ndarray", "# For n_references, generate random sample and perform kmeans getting resulting dispersion of each loop", "for", "i", "in", "range", "(", "n_refs", ")", ":", "# Create new random reference set", "random_data", "=", "np", ".", "random", ".", "random_sample", "(", "size", "=", "X", ".", "shape", ")", "# type: np.ndarray", "# Fit to it, getting the centroids and labels, and add to accumulated reference dispersions array.", "centroids", ",", "labels", "=", "kmeans2", "(", "data", "=", "random_data", ",", "k", "=", "n_clusters", ",", "iter", "=", "10", ",", "minit", "=", "'points'", ")", "# type: Tuple[np.ndarray, np.ndarray]", "dispersion", "=", "self", ".", "_calculate_dispersion", "(", "X", "=", "random_data", ",", "labels", "=", "labels", ",", "centroids", "=", "centroids", ")", "# type: float", "ref_dispersions", "[", "i", "]", "=", "dispersion", "# Fit cluster to original data and create dispersion calc.", "centroids", ",", "labels", "=", "kmeans2", "(", "data", "=", "X", ",", "k", "=", "n_clusters", ",", "iter", "=", "10", ",", "minit", "=", "'points'", ")", "dispersion", "=", "self", ".", "_calculate_dispersion", "(", "X", "=", "X", ",", "labels", "=", "labels", ",", "centroids", "=", "centroids", ")", "# Calculate gap statistic", "gap_value", "=", "np", ".", "mean", "(", "np", ".", "log", "(", "ref_dispersions", ")", ")", "-", "np", ".", "log", "(", "dispersion", ")", "return", "gap_value", ",", "int", "(", "n_clusters", ")" ]
Calculate the gap value of the given data, n_refs, and number of clusters. Return the resutling gap value and n_clusters
[ "Calculate", "the", "gap", "value", "of", "the", "given", "data", "n_refs", "and", "number", "of", "clusters", ".", "Return", "the", "resutling", "gap", "value", "and", "n_clusters" ]
train
https://github.com/milesgranger/gap_statistic/blob/146f868febfac37823114e87819df5e8bfc16ac8/gap_statistic/optimalK.py#L98-L127
milesgranger/gap_statistic
gap_statistic/optimalK.py
OptimalK._process_with_rust
def _process_with_rust(self, X: Union[pd.DataFrame, np.ndarray], n_refs: int, cluster_array: np.ndarray): """ Process gap stat using pure rust """ from gap_statistic.rust import gapstat for label, gap_value in gapstat.optimal_k(X, list(cluster_array)): yield (gap_value, label)
python
def _process_with_rust(self, X: Union[pd.DataFrame, np.ndarray], n_refs: int, cluster_array: np.ndarray): """ Process gap stat using pure rust """ from gap_statistic.rust import gapstat for label, gap_value in gapstat.optimal_k(X, list(cluster_array)): yield (gap_value, label)
[ "def", "_process_with_rust", "(", "self", ",", "X", ":", "Union", "[", "pd", ".", "DataFrame", ",", "np", ".", "ndarray", "]", ",", "n_refs", ":", "int", ",", "cluster_array", ":", "np", ".", "ndarray", ")", ":", "from", "gap_statistic", ".", "rust", "import", "gapstat", "for", "label", ",", "gap_value", "in", "gapstat", ".", "optimal_k", "(", "X", ",", "list", "(", "cluster_array", ")", ")", ":", "yield", "(", "gap_value", ",", "label", ")" ]
Process gap stat using pure rust
[ "Process", "gap", "stat", "using", "pure", "rust" ]
train
https://github.com/milesgranger/gap_statistic/blob/146f868febfac37823114e87819df5e8bfc16ac8/gap_statistic/optimalK.py#L129-L135
milesgranger/gap_statistic
gap_statistic/optimalK.py
OptimalK._process_with_joblib
def _process_with_joblib(self, X: Union[pd.DataFrame, np.ndarray], n_refs: int, cluster_array: np.ndarray): """ Process calling of .calculate_gap() method using the joblib backend """ if Parallel is None: raise EnvironmentError('joblib is not installed; cannot use joblib as the parallel backend!') with Parallel(n_jobs=self.n_jobs) as parallel: for gap_value, n_clusters in parallel(delayed(self._calculate_gap)(X, n_refs, n_clusters) for n_clusters in cluster_array): yield (gap_value, n_clusters)
python
def _process_with_joblib(self, X: Union[pd.DataFrame, np.ndarray], n_refs: int, cluster_array: np.ndarray): """ Process calling of .calculate_gap() method using the joblib backend """ if Parallel is None: raise EnvironmentError('joblib is not installed; cannot use joblib as the parallel backend!') with Parallel(n_jobs=self.n_jobs) as parallel: for gap_value, n_clusters in parallel(delayed(self._calculate_gap)(X, n_refs, n_clusters) for n_clusters in cluster_array): yield (gap_value, n_clusters)
[ "def", "_process_with_joblib", "(", "self", ",", "X", ":", "Union", "[", "pd", ".", "DataFrame", ",", "np", ".", "ndarray", "]", ",", "n_refs", ":", "int", ",", "cluster_array", ":", "np", ".", "ndarray", ")", ":", "if", "Parallel", "is", "None", ":", "raise", "EnvironmentError", "(", "'joblib is not installed; cannot use joblib as the parallel backend!'", ")", "with", "Parallel", "(", "n_jobs", "=", "self", ".", "n_jobs", ")", "as", "parallel", ":", "for", "gap_value", ",", "n_clusters", "in", "parallel", "(", "delayed", "(", "self", ".", "_calculate_gap", ")", "(", "X", ",", "n_refs", ",", "n_clusters", ")", "for", "n_clusters", "in", "cluster_array", ")", ":", "yield", "(", "gap_value", ",", "n_clusters", ")" ]
Process calling of .calculate_gap() method using the joblib backend
[ "Process", "calling", "of", ".", "calculate_gap", "()", "method", "using", "the", "joblib", "backend" ]
train
https://github.com/milesgranger/gap_statistic/blob/146f868febfac37823114e87819df5e8bfc16ac8/gap_statistic/optimalK.py#L137-L147
milesgranger/gap_statistic
gap_statistic/optimalK.py
OptimalK._process_with_multiprocessing
def _process_with_multiprocessing(self, X: Union[pd.DataFrame, np.ndarray], n_refs: int, cluster_array: np.ndarray): """ Process calling of .calculate_gap() method using the multiprocessing library """ with ProcessPoolExecutor(max_workers=self.n_jobs) as executor: jobs = [executor.submit(self._calculate_gap, X, n_refs, n_clusters) for n_clusters in cluster_array ] for future in as_completed(jobs): gap_value, k = future.result() yield (gap_value, k)
python
def _process_with_multiprocessing(self, X: Union[pd.DataFrame, np.ndarray], n_refs: int, cluster_array: np.ndarray): """ Process calling of .calculate_gap() method using the multiprocessing library """ with ProcessPoolExecutor(max_workers=self.n_jobs) as executor: jobs = [executor.submit(self._calculate_gap, X, n_refs, n_clusters) for n_clusters in cluster_array ] for future in as_completed(jobs): gap_value, k = future.result() yield (gap_value, k)
[ "def", "_process_with_multiprocessing", "(", "self", ",", "X", ":", "Union", "[", "pd", ".", "DataFrame", ",", "np", ".", "ndarray", "]", ",", "n_refs", ":", "int", ",", "cluster_array", ":", "np", ".", "ndarray", ")", ":", "with", "ProcessPoolExecutor", "(", "max_workers", "=", "self", ".", "n_jobs", ")", "as", "executor", ":", "jobs", "=", "[", "executor", ".", "submit", "(", "self", ".", "_calculate_gap", ",", "X", ",", "n_refs", ",", "n_clusters", ")", "for", "n_clusters", "in", "cluster_array", "]", "for", "future", "in", "as_completed", "(", "jobs", ")", ":", "gap_value", ",", "k", "=", "future", ".", "result", "(", ")", "yield", "(", "gap_value", ",", "k", ")" ]
Process calling of .calculate_gap() method using the multiprocessing library
[ "Process", "calling", "of", ".", "calculate_gap", "()", "method", "using", "the", "multiprocessing", "library" ]
train
https://github.com/milesgranger/gap_statistic/blob/146f868febfac37823114e87819df5e8bfc16ac8/gap_statistic/optimalK.py#L149-L161
milesgranger/gap_statistic
gap_statistic/optimalK.py
OptimalK._process_non_parallel
def _process_non_parallel(self, X: Union[pd.DataFrame, np.ndarray], n_refs: int, cluster_array: np.ndarray): """ Process calling of .calculate_gap() method using no parallel backend; simple for loop generator """ for gap_value, n_clusters in [self._calculate_gap(X, n_refs, n_clusters) for n_clusters in cluster_array]: yield (gap_value, n_clusters)
python
def _process_non_parallel(self, X: Union[pd.DataFrame, np.ndarray], n_refs: int, cluster_array: np.ndarray): """ Process calling of .calculate_gap() method using no parallel backend; simple for loop generator """ for gap_value, n_clusters in [self._calculate_gap(X, n_refs, n_clusters) for n_clusters in cluster_array]: yield (gap_value, n_clusters)
[ "def", "_process_non_parallel", "(", "self", ",", "X", ":", "Union", "[", "pd", ".", "DataFrame", ",", "np", ".", "ndarray", "]", ",", "n_refs", ":", "int", ",", "cluster_array", ":", "np", ".", "ndarray", ")", ":", "for", "gap_value", ",", "n_clusters", "in", "[", "self", ".", "_calculate_gap", "(", "X", ",", "n_refs", ",", "n_clusters", ")", "for", "n_clusters", "in", "cluster_array", "]", ":", "yield", "(", "gap_value", ",", "n_clusters", ")" ]
Process calling of .calculate_gap() method using no parallel backend; simple for loop generator
[ "Process", "calling", "of", ".", "calculate_gap", "()", "method", "using", "no", "parallel", "backend", ";", "simple", "for", "loop", "generator" ]
train
https://github.com/milesgranger/gap_statistic/blob/146f868febfac37823114e87819df5e8bfc16ac8/gap_statistic/optimalK.py#L163-L169