text
stringlengths
81
112k
Tell which language should be used to render the content item. 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_la...
At runtime, when logging is not active, replace the .debug() call with a no-op. 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) i...
Extract the search fields from the model. 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 strin...
Introduce more 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
Return the metadata about a layout 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) ...
Apply soft hyphenation to the text, which inserts ``­`` markers. def softhyphen_filter(textitem, html): """ Apply soft hyphenation to the text, which inserts ``­`` markers. """ language = textitem.language_code # Make sure the Django language code gets converted to what django-softhypen 1....
Return cached output for a placeholder, if available. This avoids fetching the Placeholder object. 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 PlaceholderRen...
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 cachea...
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. :ty...
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_lan...
Render the placeholder field. 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...
Get the set of plugins that this widget should display. 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: ...
Decorator for the TemplateResponse.render() function 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(respons...
Return a redirect response for the :class:`~fluent_contents.extensions.HttpRedirectRequest` def process_exception(self, request, exception): """ Return a redirect response for the :class:`~fluent_contents.extensions.HttpRedirectRequest` """ if isinstance(exception, HttpRedirectRequest):...
Render the text, reuses the template filters provided by Django. 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 ImproperlyConf...
Read the derived table data for all objects tracked as remaining (=not found in the cache). 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.obje...
Return the output in the correct ordering. :rtype: list[Tuple[contentitem, O]] 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. ...
The main rendering sequence. 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_polym...
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. def _fetch_cached_output(self, items, result): """ First try to fetch all items from the cac...
Tell whether the code should try reading 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...
Render a list of items, that didn't exist in the cache yet. 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. ...
Render the individual item. May raise :class:`SkipItem` to ignore an 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_overrid...
Combine all rendered items. Allow rendering the items with a template, to inserting separators or nice start/end code. 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/e...
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. def get_html_output(self, result, items): """ Collect all HTML from the rendered items, in the correct ordering. Th...
The main rendering sequence for placeholders. This will do all the magic for caching, and call :func:`render_items` in the end. def render_placeholder(self, placeholder, parent_object=None, template_name=None, cachable=None, limit_parent_language=True, fallback_language=None): """ The main rend...
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 re...
Return the plugins which are supported in the given placeholder name. 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_PLACE...
Return a list of plugins by plugin class, or 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): ...
Return all :class:`~fluent_contents.models.ContentItem` model classes which are exposed by plugins. def get_model_classes(self): """ Return all :class:`~fluent_contents.models.ContentItem` model classes which are exposed by plugins. """ self._import_plugins() return [plugin.mode...
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. def get_plugin_by_model(self, model_class): """ Return the corres...
Internal function, ensure all plugin packages are imported. 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...
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:: pyt...
Perform optimizations in the HTML source code. :type instance: fluent_contents.models.ContentItem :raise ValidationError: when one of the filters detects a problem. def apply_pre_filters(instance, html): """ Perform optimizations in the HTML source code. :type instance: fluent_contents.models.Con...
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. def apply_post_filters(instance, html): """ Allow post processing functions to ch...
Clean the plugin output cache of a rendered plugin. 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()
Filter to the given site, only give content relevant for that 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...
Make sure the queryset is filtered on a parent site, if that didn't happen already. 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 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...
Inspect a single 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 mo...
Take all ``<img src="..">`` from the HTML 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'): ...
Handle ``srcset="image.png 1x, image@2x.jpg 2x"`` def extract_srcset(self, srcset): """ Handle ``srcset="image.png 1x, image@2x.jpg 2x"`` """ urls = [] for item in srcset.split(','): if item: urls.append(unquote_utf8(item.rsplit(' ', 1)[0])) r...
Make sure ContentItems are deleted when a translation in deleted. 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(translat...
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></...
Return the contents as dictionary, for client-side export. The dictionary contains the fields: * ``slot`` * ``title`` * ``role`` * ``fallback_language`` * ``allowed_plugins`` def as_dict(self): """ Return the contents as dictionary, for client-side expor...
Make sure that the MarkupItem model actually points to the correct proxy model, that implements the given language. 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 t...
Pre-populate formset with the initial placeholders to display. 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-sid...
Create the inlines for the admin, including the placeholder and contentitem inlines. 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_i...
Return the placeholder data as dictionary. This is used in the client for the "copy" functionality. 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. """ langua...
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) ...
Returns method or function arguments. 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).a...
Unwind (resume) generator. def _unwindGenerator(self, generator, _prev=None): """Unwind (resume) generator.""" while True: if _prev: ret, _prev = _prev, None else: try: ret = next(generator) except StopIteration...
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 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....
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. F...
Returns the decoded token from an encoded one. This does all the checks to insure that the decoded token is valid before returning it. 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...
Register this extension with the flask app :param app: A flask application 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, 'exten...
Sets the error handler callbacks used by this extension 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_callbac...
Sets the default configuration options used by this extension 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', 'Author...
Get a category. def category(**kwargs): """Get a category.""" if 'series' in kwargs: kwargs.pop('series') path = 'series' else: path = None return Fred().category(path, **kwargs)
Get all releases of economic data. 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)
Get an economic data 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') ...
Get a source of economic data. 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: ...
Get the sources of economic data. 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)
Create the URL path with the Fred endpoint and given arguments. 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
Perform a GET request againt the Fred API endpoint. 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...
Format GET request's parameters from 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 ...
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. def item_extra_kwargs(self, item): """ Returns an extra keyword arguments dictionary that is used with ...
Sample view demonstrating that you can provide custom handlers for undefined menu items on a per-item basis. 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_4...
This signal attempts to update the HREF of any menu items that point to another model object, when that objects is saved. 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 th...
Refresh all the cached menu item HREFs in the database. 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 ...
Remove all MenuItems from 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 ...
Rebuilds the tree and clears the cache. 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)
Rebuilds the tree after saving items related to parent. 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()
Calculate the dispersion between actual points and their assigned centroids 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.su...
Calculate the gap value of the given data, n_refs, and number of clusters. Return the resutling gap value and n_clusters 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 nu...
Process gap stat using pure 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_ar...
Process calling of .calculate_gap() method using the joblib backend 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: ra...
Process calling of .calculate_gap() method using the multiprocessing library 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 Pro...
Process calling of .calculate_gap() method using no parallel backend; simple for loop generator 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 generato...
Get the last migration batch. :rtype: list def get_last(self): """ Get the last migration batch. :rtype: list """ query = self.table().where('batch', self.get_last_batch_number()) return query.order_by('migration', 'desc').get()
Compile an insert SQL statement :param query: A QueryBuilder instance :type query: QueryBuilder :param values: The values to insert :type values: dict or list :return: The compiled statement :rtype: str def compile_insert(self, query, values): """ Comp...
Get the ALTER TABLE SQL statement :param diff: The table diff :type diff: eloquent.dbal.table_diff.TableDiff :rtype: list def get_alter_table_sql(self, diff): """ Get the ALTER TABLE SQL statement :param diff: The table diff :type diff: eloquent.dbal.table_dif...
Compiled a date where based clause :param type: The date type :type type: str :param query: A QueryBuilder instance :type query: QueryBuilder :param where: The condition :type where: dict :return: The compiled clause :rtype: str def _date_based_where(...
Compile a select query into SQL :param query: A QueryBuilder instance :type query: QueryBuilder :return: The compiled sql :rtype: str def compile_select(self, query): """ Compile a select query into SQL :param query: A QueryBuilder instance :type query...
Compile the lock into SQL :param query: A QueryBuilder instance :type query: QueryBuilder :param value: The lock value :type value: bool or str :return: The compiled lock :rtype: str def _compile_lock(self, query, value): """ Compile the lock into SQL ...
Compile an update statement into SQL :param query: A QueryBuilder instance :type query: QueryBuilder :param values: The update values :type values: dict :return: The compiled update :rtype: str def compile_update(self, query, values): """ Compile an up...
Collapse the collection items into a single element (dict or list) :return: A new Collection instance with collapsed items :rtype: Collection def collapse(self): """ Collapse the collection items into a single element (dict or list) :return: A new Collection instance with coll...
Determine if an element is in the collection :param key: The element :type key: int or str :param value: The value of the element :type value: mixed :return: Whether the element is in the collection :rtype: bool def contains(self, key, value=None): """ ...
Get a list with the values of a given key :rtype: list def lists(self, value, key=None): """ Get a list with the values of a given key :rtype: list """ results = map(lambda x: x[value], self._items) return list(results)
Run a map over each of the item. :param callback: The map function :type callback: callable :rtype: Collection def map(self, callback): """ Run a map over each of the item. :param callback: The map function :type callback: callable :rtype: Collection ...
Return only unique items from the collection list. :rtype: Collection def unique(self): """ Return only unique items from the collection list. :rtype: Collection """ seen = set() seen_add = seen.add return Collection([x for x in self._items if not (x i...
Load a set of relationships onto the collection. def load(self, *relations): """ Load a set of relationships onto the collection. """ if len(self._items) > 0: query = self.first().new_query().with_(*relations) self._items = query.eager_load_relations(self._items...
Compile a foreign key command. :param blueprint: The blueprint :type blueprint: Blueprint :param command: The command :type command: Fluent :rtype: str def compile_foreign(self, blueprint, command, _): """ Compile a foreign key command. :param bluepri...
Get the blueprint's columns definitions. :param blueprint: The blueprint :type blueprint: Blueprint :rtype: list def _get_columns(self, blueprint): """ Get the blueprint's columns definitions. :param blueprint: The blueprint :type blueprint: Blueprint ...
Add the column modifiers to the deifinition def _add_modifiers(self, sql, blueprint, column): """ Add the column modifiers to the deifinition """ for modifier in self._modifiers: method = '_modify_%s' % modifier if hasattr(self, method): sql += g...
Get the pivot attributes from a model. :type model: eloquent.Model def _clean_pivot_attributes(self, model): """ Get the pivot attributes from a model. :type model: eloquent.Model """ values = {} delete_keys = [] for key, value in model.get_attributes(...
Add the constraints for a relationship count query on the same table. :type query: eloquent.orm.Builder :type parent: eloquent.orm.Builder :rtype: eloquent.orm.Builder def get_relation_count_query_for_self_join(self, query, parent): """ Add the constraints for a relationship c...
Set the select clause for the relation query. :param columns: The columns :type columns: list :rtype: list def _get_select_columns(self, columns=None): """ Set the select clause for the relation query. :param columns: The columns :type columns: list :...
Get the pivot columns for the relation. :rtype: list def _get_aliased_pivot_columns(self): """ Get the pivot columns for the relation. :rtype: list """ defaults = [self._foreign_key, self._other_key] columns = [] for column in defaults + self._pivot_c...
Set the join clause for the relation query. :param query: The query builder :type query: eloquent.orm.Builder :return: self :rtype: BelongsToMany def _set_join(self, query=None): """ Set the join clause for the relation query. :param query: The query builder ...
Match the eagerly loaded results to their parents. :type models: list :type results: Collection :type relation: str def match(self, models, results, relation): """ Match the eagerly loaded results to their parents. :type models: list :type results: Collection ...