signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def workflow_states_column(self, obj):
workflow_states = models.WorkflowState.objects.filter(<EOL>content_type=self._get_obj_ct(obj),<EOL>object_id=obj.pk,<EOL>)<EOL>return '<STR_LIT:U+002CU+0020>'.join([unicode(wfs) for wfs in workflow_states])<EOL>
Return text description of workflow states assigned to object
f4431:c4:m1
def created_by_column(self, obj):
try:<EOL><INDENT>first_addition_logentry = admin.models.LogEntry.objects.filter(<EOL>object_id=obj.pk,<EOL>content_type_id=self._get_obj_ct(obj).pk,<EOL>action_flag=admin.models.ADDITION,<EOL>).get()<EOL>return first_addition_logentry.user<EOL><DEDENT>except admin.models.LogEntry.DoesNotExist:<EOL><INDENT>return None<EOL><DEDENT>
Return user who first created an item in Django admin
f4431:c4:m2
def last_edited_by_column(self, obj):
latest_logentry = admin.models.LogEntry.objects.filter(<EOL>object_id=obj.pk,<EOL>content_type_id=self._get_obj_ct(obj).pk,<EOL>action_flag__in=[admin.models.ADDITION, admin.models.CHANGE],<EOL>).first()<EOL>if latest_logentry:<EOL><INDENT>return latest_logentry.user<EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>
Return user who last edited an item in Django admin, where "edited" means either created (addition) or modified (change).
f4431:c4:m3
@register.tag<EOL>def get_assigned_to_user(parser, token):
tokens = token.contents.split()<EOL>if len(tokens) < <NUM_LIT:4>:<EOL><INDENT>raise template.TemplateSyntaxError(<EOL>"<STR_LIT>")<EOL><DEDENT>if not tokens[<NUM_LIT:1>].isdigit():<EOL><INDENT>raise template.TemplateSyntaxError(<EOL>"<STR_LIT>")<EOL><DEDENT>if tokens[<NUM_LIT:2>] != '<STR_LIT>':<EOL><INDENT>raise template.TemplateSyntaxError(<EOL>"<STR_LIT>")<EOL><DEDENT>if len(tokens) > <NUM_LIT:4>:<EOL><INDENT>if tokens[<NUM_LIT:4>] != '<STR_LIT>':<EOL><INDENT>raise template.TemplateSyntaxError(<EOL>"<STR_LIT>")<EOL><DEDENT><DEDENT>return AssigedToUserNode(limit=tokens[<NUM_LIT:1>], varname=tokens[<NUM_LIT:3>], user=(tokens[<NUM_LIT:5>] if len(tokens) > <NUM_LIT:5> else None))<EOL>
Populates a template variable with the content with WorkflowState assignd for the given criteria. Usage:: {% get_assigned_to_user [limit] as [varname] for_user [context_var_containing_user_obj] %} Examples:: {% get_assigned_to_user 10 as content_list for_user 23 %} {% get_assigned_to_user 10 as content_list for_user user %} Note that ``context_var_containing_user_obj`` can be a hard-coded integer (user ID) or the name of a template context variable containing the user object whose ID you want.
f4432:m0
@receiver(post_save, sender=WorkflowState)<EOL>def send_email_notifications_for_workflow_state_change(<EOL>sender, instance, *args, **kwargs<EOL>):
<EOL>if not appsettings.WORKFLOW_EMAIL_NOTIFICATION_TARGETS:<EOL><INDENT>return<EOL><DEDENT>obj = instance.content_object<EOL>obj_ct = ContentType.objects.get_for_model(obj)<EOL>obj_app_name = '<STR_LIT:_>'.join(obj_ct.natural_key())<EOL>admin_path = reverse(<EOL>'<STR_LIT>' % obj_app_name, args=(obj.pk,))<EOL>admin_domain = getattr(<EOL>settings,<EOL>'<STR_LIT>',<EOL>Site.objects.all()[<NUM_LIT:0>].domain)<EOL>if '<STR_LIT>' not in admin_domain:<EOL><INDENT>admin_domain = '<STR_LIT>' + admin_domain<EOL><DEDENT>admin_url = '<STR_LIT>'.join([admin_domain, admin_path])<EOL>for target_settings in appsettings.WORKFLOW_EMAIL_NOTIFICATION_TARGETS:<EOL><INDENT>if '<STR_LIT:to>' in target_settings:<EOL><INDENT>to_addresses = target_settings['<STR_LIT:to>']<EOL><DEDENT>elif instance.assigned_to:<EOL><INDENT>to_addresses = instance.assigned_to.email<EOL><DEDENT>else:<EOL><INDENT>continue<EOL><DEDENT>if not isinstance(to_addresses, list):<EOL><INDENT>to_addresses = [to_addresses]<EOL><DEDENT>from_address = target_settings.get(<EOL>'<STR_LIT>', appsettings.WORKFLOW_EMAIL_NOTIFICATION_DEFAULT_FROM)<EOL>subject_template = target_settings.get(<EOL>'<STR_LIT>',<EOL>appsettings.WORKFLOW_EMAIL_NOTIFICATION_SUBJECT_TEMPLATE)<EOL>message_template = target_settings.get(<EOL>'<STR_LIT>',<EOL>appsettings.WORKFLOW_EMAIL_NOTIFICATION_MESSAGE_TEMPLATE)<EOL>assigned_to_mapper = target_settings.get(<EOL>'<STR_LIT>', lambda x: x)<EOL>template_context = Context({<EOL>'<STR_LIT:state>': instance,<EOL>'<STR_LIT:object>': obj,<EOL>'<STR_LIT>': admin_url,<EOL>'<STR_LIT>': assigned_to_mapper(instance.assigned_to),<EOL>})<EOL>subject = Template(subject_template).render(template_context)<EOL>message = Template(message_template).render(template_context)<EOL>send_mail(subject, message, from_address, to_addresses)<EOL><DEDENT>
Send email notifications for save events on ``WorkflowState`` based on settings in this module's `appsettings`.
f4441:m0
def get_context(self, request, page, **kwargs):
context = super(ListingPagePlugin, self).get_context(<EOL>request, page, **kwargs)<EOL>context['<STR_LIT>'] = page.get_items_to_list(request)<EOL>return context<EOL>
Include in context items to be visible on listing page
f4445:c0:m0
def get_view_response(self, request, page, view_func, view_args, view_kwargs):
return view_func(request, page, *view_args, **view_kwargs)<EOL>
Render the custom view that was exposed by the extra plugin URL patterns. This gives the ability to add extra middleware logic.
f4445:c0:m1
def validate_unique_slug(self):
clashes_qs = type(self).objects.filter(slug=self.slug)<EOL>if self.pk:<EOL><INDENT>clashes_qs = clashes_qs.exclude(pk=self.pk)<EOL><DEDENT>if isinstance(self, PublishingModel):<EOL><INDENT>clashes_qs = clashes_qs.filter(<EOL>publishing_is_draft=self.publishing_is_draft)<EOL><DEDENT>if clashes_qs:<EOL><INDENT>raise ValidationError(<EOL>"<STR_LIT>"<EOL>% (self.slug, clashes_qs))<EOL><DEDENT>
Ensure slug is unique for this model. This check is aware of publishing but is otherwise fairly basic and will need to be customised for situations where models with slugs are not in a flat hierarchy etc.
f4446:c0:m1
def publishing_prepare_published_copy(self, draft_obj):
self.validate_unique_slug()<EOL>
Perform slug validation on publish, not just when saving draft
f4446:c0:m3
def get_items_to_list(self, request=None):
raise NotImplementedError(<EOL>"<STR_LIT>" % type(self)<EOL>)<EOL>
Get the items that will be show in this page's listing. Remember that incoming relations will be on the draft version of the page. Do something like this: unpublished_pk = self.get_draft().pk return Article.objects.published().filter(parent_id=unpublished_pk) Editors normally expect to only see published() items in a listing, not visible() items, unless clearly marked as such. :return: the items to be rendered in the listing page
f4446:c2:m0
def get_items_to_mount(self, request):
raise NotImplementedError(<EOL>"<STR_LIT>" % type(self)<EOL>)<EOL>
Get all items that are associated with this page and can be previewed by the user at a URL. Again, incoming relations will be on the draft version of the page. Do something like this: unpublished_pk = self.get_draft().pk return Article.objects.visible().filter(parent_id=unpublished_pk) :return: the items with URL path endpoints under this page's path
f4446:c2:m1
def get_absolute_url(self):
<EOL>if self.is_draft:<EOL><INDENT>visible_parent = self.parent.get_draft()<EOL><DEDENT>else:<EOL><INDENT>visible_parent = self.parent.get_published() orself.parent.get_draft()<EOL><DEDENT>return urljoin(visible_parent.get_absolute_url(), self.slug + "<STR_LIT:/>")<EOL>
The majority of the time, the URL is the parent's URL plus the slug. If not, override this function.
f4446:c3:m1
def get_response(self, request, parent, *args, **kwargs):
context = {<EOL>'<STR_LIT>': self,<EOL>}<EOL>try:<EOL><INDENT>return TemplateResponse(<EOL>request,<EOL>self.get_layout_template_name(),<EOL>context<EOL>)<EOL><DEDENT>except AttributeError:<EOL><INDENT>raise AttributeError("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" % type(self).__name__)<EOL><DEDENT>
Render this collected content to a response. :param request: the request :param parent: the parent collection :param args: :param kwargs: :return:
f4446:c3:m2
def render_stats(stats, sort, format):
output = StdoutWrapper()<EOL>if hasattr(stats, "<STR_LIT>"):<EOL><INDENT>stats.stream = output.stream<EOL><DEDENT>stats.sort_stats(*sort)<EOL>getattr(stats, format)()<EOL>return output.stream<EOL>
Returns a StringIO containing the formatted statistics from _statsfile_. _sort_ is a list of fields to sort by. _format_ is the name of the method that pstats uses to format the data.
f4449:m0
def render_queries(queries, sort):
output = StringIO()<EOL>if sort == '<STR_LIT>':<EOL><INDENT>print >>output, "<STR_LIT>"<EOL>for query in queries:<EOL><INDENT>print >>output, "<STR_LIT>" % (query["<STR_LIT:time>"], query["<STR_LIT>"])<EOL><DEDENT>return output<EOL><DEDENT>if sort == '<STR_LIT:time>':<EOL><INDENT>def sorter(x, y):<EOL><INDENT>return cmp(x[<NUM_LIT:1>][<NUM_LIT:1>], y[<NUM_LIT:1>][<NUM_LIT:1>])<EOL><DEDENT><DEDENT>elif sort == '<STR_LIT>':<EOL><INDENT>def sorter(x, y):<EOL><INDENT>return cmp(x[<NUM_LIT:1>][<NUM_LIT:0>], y[<NUM_LIT:1>][<NUM_LIT:0>])<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise RuntimeError("<STR_LIT>" % sort)<EOL><DEDENT>print >>output, "<STR_LIT>"<EOL>results = {}<EOL>for query in queries:<EOL><INDENT>try:<EOL><INDENT>result = results[query["<STR_LIT>"]]<EOL>result[<NUM_LIT:0>] += <NUM_LIT:1><EOL>result[<NUM_LIT:1>] += Decimal(query["<STR_LIT:time>"])<EOL><DEDENT>except KeyError:<EOL><INDENT>results[query["<STR_LIT>"]] = [<NUM_LIT:1>, Decimal(query["<STR_LIT:time>"])]<EOL><DEDENT><DEDENT>results = sorted(results.iteritems(), cmp=sorter, reverse=True)<EOL>for result in results:<EOL><INDENT>print >>output, "<STR_LIT>" % (<EOL>result[<NUM_LIT:1>][<NUM_LIT:0>], result[<NUM_LIT:1>][<NUM_LIT:1>], result[<NUM_LIT:0>]<EOL>)<EOL><DEDENT>return output<EOL>
Returns a StringIO containing the formatted SQL queries. _sort_ is a field to sort by.
f4449:m1
def pickle_stats(stats):
if hasattr(stats, "<STR_LIT>"):<EOL><INDENT>del stats.stream<EOL><DEDENT>return cPickle.dumps(stats)<EOL>
Pickle a pstats.Stats object
f4449:m2
def unpickle_stats(stats):
stats = cPickle.loads(stats)<EOL>stats.stream = True<EOL>return stats<EOL>
Unpickle a pstats.Stats object
f4449:m3
def display_stats(request, stats, queries):
sort = [<EOL>request.REQUEST.get('<STR_LIT>', '<STR_LIT:time>'),<EOL>request.REQUEST.get('<STR_LIT>', '<STR_LIT>')<EOL>]<EOL>fmt = request.REQUEST.get('<STR_LIT>', '<STR_LIT>')<EOL>sort_first_buttons = RadioButtons('<STR_LIT>', sort[<NUM_LIT:0>], sort_categories)<EOL>sort_second_buttons = RadioButtons('<STR_LIT>', sort[<NUM_LIT:1>], sort_categories)<EOL>format_buttons = RadioButtons('<STR_LIT>', fmt, (<EOL>('<STR_LIT>', '<STR_LIT>'),<EOL>('<STR_LIT>', '<STR_LIT>'),<EOL>('<STR_LIT>', '<STR_LIT>')<EOL>))<EOL>output = render_stats(stats, sort, fmt)<EOL>output.reset()<EOL>output = [html.escape(unicode(line)) for line in output.readlines()]<EOL>response = HttpResponse(content_type='<STR_LIT>')<EOL>response.content = (stats_template % {<EOL>'<STR_LIT>': format_buttons,<EOL>'<STR_LIT>': sort_first_buttons,<EOL>'<STR_LIT>': sort_second_buttons,<EOL>'<STR_LIT>' : b64encode(cPickle.dumps(queries)),<EOL>'<STR_LIT>': b64encode(pickle_stats(stats)),<EOL>'<STR_LIT>': "<STR_LIT>".join(output),<EOL>'<STR_LIT:url>': request.path<EOL>})<EOL>return response<EOL>
Generate a HttpResponse of functions for a profiling run. _stats_ should contain a pstats.Stats of a hotshot session. _queries_ should contain a list of SQL queries.
f4449:m4
def display_queries(request, stats, queries):
sort = request.REQUEST.get('<STR_LIT>', '<STR_LIT:time>')<EOL>sort_buttons = RadioButtons('<STR_LIT>', sort, (<EOL>('<STR_LIT>', '<STR_LIT>'), ('<STR_LIT:time>', '<STR_LIT:time>'), ('<STR_LIT>', '<STR_LIT>')<EOL>))<EOL>output = render_queries(queries, sort)<EOL>output.reset()<EOL>output = [html.escape(unicode(line)) for line in output.readlines()]<EOL>response = HttpResponse(mimetype='<STR_LIT>')<EOL>response.content = (queries_template % {<EOL>'<STR_LIT>': sort_buttons,<EOL>'<STR_LIT>': len(queries),<EOL>'<STR_LIT>': "<STR_LIT>".join(output),<EOL>'<STR_LIT>' : b64encode(cPickle.dumps(queries)),<EOL>'<STR_LIT>': b64encode(pickle_stats(stats)),<EOL>'<STR_LIT:url>': request.path<EOL>})<EOL>return response<EOL>
Generate a HttpResponse of SQL queries for a profiling run. _stats_ should contain a pstats.Stats of a hotshot session. _queries_ should contain a list of SQL queries.
f4449:m5
def process_request(self, request):
def unpickle(params):<EOL><INDENT>stats = unpickle_stats(b64decode(params.get('<STR_LIT>', '<STR_LIT>')))<EOL>queries = cPickle.loads(b64decode(params.get('<STR_LIT>', '<STR_LIT>')))<EOL>return stats, queries<EOL><DEDENT>if request.method != '<STR_LIT:GET>' andnot (request.META.get(<EOL>'<STR_LIT>', request.META.get('<STR_LIT>', '<STR_LIT>')<EOL>) in ['<STR_LIT>', '<STR_LIT>']):<EOL><INDENT>return<EOL><DEDENT>if (request.REQUEST.get('<STR_LIT>', False) and<EOL>(settings.DEBUG == True or request.user.is_staff)):<EOL><INDENT>request.statsfile = tempfile.NamedTemporaryFile()<EOL>params = request.REQUEST<EOL>if (params.get('<STR_LIT>', False)<EOL>and params.get('<STR_LIT>', '<STR_LIT:1>') == '<STR_LIT:1>'):<EOL><INDENT>stats, queries = unpickle(params)<EOL>return display_stats(request, stats, queries)<EOL><DEDENT>elif (params.get('<STR_LIT>', False)<EOL>and params.get('<STR_LIT>', '<STR_LIT:1>') == '<STR_LIT:1>'):<EOL><INDENT>stats, queries = unpickle(params)<EOL>return display_queries(request, stats, queries)<EOL><DEDENT>else:<EOL><INDENT>request.profiler = hotshot.Profile(request.statsfile.name)<EOL>reset_queries()<EOL><DEDENT><DEDENT>
Setup the profiler for a profiling run and clear the SQL query log. If this is a resort of an existing profiling run, just return the resorted list.
f4449:c3:m0
def process_view(self, request, view_func, view_args, view_kwargs):
profiler = getattr(request, '<STR_LIT>', None)<EOL>if profiler:<EOL><INDENT>original_get = request.GET<EOL>request.GET = original_get.copy()<EOL>request.GET.pop('<STR_LIT>', None)<EOL>request.GET.pop('<STR_LIT>', None)<EOL>request.GET.pop('<STR_LIT>', None)<EOL>try:<EOL><INDENT>return profiler.runcall(<EOL>view_func, request, *view_args, **view_kwargs<EOL>)<EOL><DEDENT>finally:<EOL><INDENT>request.GET = original_get<EOL><DEDENT><DEDENT>
Run the profiler on _view_func_.
f4449:c3:m1
def process_response(self, request, response):
profiler = getattr(request, '<STR_LIT>', None)<EOL>if profiler:<EOL><INDENT>profiler.close()<EOL>params = request.REQUEST<EOL>stats = hotshot.stats.load(request.statsfile.name)<EOL>queries = connection.queries<EOL>if (params.get('<STR_LIT>', False)<EOL>and params.get('<STR_LIT>', '<STR_LIT:1>') == '<STR_LIT:1>'):<EOL><INDENT>response = display_queries(request, stats, queries)<EOL><DEDENT>else:<EOL><INDENT>response = display_stats(request, stats, queries)<EOL><DEDENT><DEDENT>return response<EOL>
Finish profiling and render the results.
f4449:c3:m2
def handle_soundcloud_malformed_widths_for_oembeds(sender, instance, **kwargs):
if instance.width == '<STR_LIT>':<EOL><INDENT>instance.width = -<NUM_LIT:100><EOL><DEDENT>
A signal receiver that prevents soundcloud from triggering ValueErrors when we save an OEmbedItem. Soundcloud returns "100%", instead of an integer for an OEmbed's width property. This is against the OEmbed spec, but actually makes sense in the context of responsive design. Unfortunately, the OEmbedItems can only store integers in the `width` field, so this becomes a 500 throwing issue. The issue is tracked https://github.com/edoburu/django-fluent-contents/issues/65
f4457:m0
def contribute_to_class(model_class, name='<STR_LIT>', descriptor=None):
rel_obj = descriptor or PlaceholderDescriptor()<EOL>rel_obj.contribute_to_class(model_class, name)<EOL>setattr(model_class, name, rel_obj)<EOL>return True<EOL>
Function that adds a description to a model Class. :param model_class: The model class the descriptor is to be added to. :param name: The attribute name the descriptor will be assigned to. :param descriptor: The descriptor instance to be used. If none is specified it will default to ``icekit.plugins.descriptors.PlaceholderDescriptor``. :return: True
f4464:m0
def __get__(self, instance=None, cls=None):
if instance is None:<EOL><INDENT>return self<EOL><DEDENT>return self.create_placeholder_access_object(instance)<EOL>
Create placeholder access object.
f4464:c0:m1
def contribute_to_class(self, cls, name):
self.name = name<EOL>self.model_class = cls<EOL>setattr(cls, self.name, self)<EOL>
Perform contriubtion to class.
f4464:c0:m2
def create_placeholder_access_object(self, instance):
related_model = self.related_model<EOL>def get_related_model_objects(name):<EOL><INDENT>"""<STR_LIT>"""<EOL>return related_model.objects.get(<EOL>parent_type=ContentType.objects.get_for_model(type(instance)),<EOL>parent_id=instance.id,<EOL>slot=name,<EOL>).get_content_items()<EOL><DEDENT>class PlaceholderAccess(object):<EOL><INDENT>def __getattribute__(self, name):<EOL><INDENT>"""<STR_LIT>"""<EOL>try:<EOL><INDENT>return get_related_model_objects(name)<EOL><DEDENT>except related_model.DoesNotExist:<EOL><INDENT>return super(PlaceholderAccess, self).__getattribute__(name)<EOL><DEDENT><DEDENT>def __getitem__(self, item):<EOL><INDENT>"""<STR_LIT>"""<EOL>try:<EOL><INDENT>return get_related_model_objects(item)<EOL><DEDENT>except related_model.DoesNotExist:<EOL><INDENT>raise KeyError<EOL><DEDENT><DEDENT><DEDENT>return PlaceholderAccess()<EOL>
Created objects with placeholder slots as properties. Each placeholder created for an object will be added to a `PlaceHolderAccess` object as a set property.
f4464:c0:m3
def file_size(self):
try:<EOL><INDENT>return filesizeformat(self.file.size)<EOL><DEDENT>except OSError:<EOL><INDENT>return filesizeformat(<NUM_LIT:0>)<EOL><DEDENT>
Obtain the file size for the file in human readable format. If the file isn't fount, return "0 bytes" rather than crash :return: String of file size with unit.
f4471:c0:m2
def extension(self):
file_name_and_extension_list = self.file.name.split('<STR_LIT:.>')<EOL>if len(file_name_and_extension_list) > <NUM_LIT:1>:<EOL><INDENT>return file_name_and_extension_list[-<NUM_LIT:1>]<EOL><DEDENT>return '<STR_LIT>'<EOL>
Obtain the extension for the file. :return: String.
f4471:c0:m3
def handle_soundcloud_malformed_widths_for_oembeds(sender, instance, **kwargs):
if instance.width == '<STR_LIT>':<EOL><INDENT>instance.width = -<NUM_LIT:100><EOL><DEDENT>
A signal receiver that prevents soundcloud from triggering ValueErrors when we save an OEmbedItem. Soundcloud returns "100%", instead of an integer for an OEmbed's width property. This is against the OEmbed spec, but actually makes sense in the context of responsive design. Unfortunately, the OEmbedItems can only store integers in the `width` field, so this becomes a 500 throwing issue. The issue is tracked https://github.com/edoburu/django-fluent-contents/issues/65
f4481:m0
def get_render_template(self, request, instance, **kwargs):
safe_filename = re_safe.sub('<STR_LIT>', instance.type or '<STR_LIT:default>')<EOL>return [<EOL>self.render_template_base.format(type=safe_filename),<EOL>self.render_template<EOL>]<EOL>
Allow to style the item based on the type.
f4483:c0:m0
def clean_url(self):
url = self.cleaned_data['<STR_LIT:url>']<EOL>if url:<EOL><INDENT>pattern = re.compile(r'<STR_LIT>')<EOL>if not pattern.match(url):<EOL><INDENT>raise forms.ValidationError('<STR_LIT>')<EOL><DEDENT><DEDENT>return url<EOL>
Make sure the URL provided matches the instagram URL format.
f4490:c0:m0
def clean(self, *args, **kwargs):
<EOL>instagram_data = self.fetch_instagram_data()<EOL>if isinstance(instagram_data, dict):<EOL><INDENT>for key in instagram_data.keys():<EOL><INDENT>setattr(self, key, instagram_data[key])<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise exceptions.ValidationError(instagram_data)<EOL><DEDENT>super(AbstractInstagramEmbedItem, self).clean(*args, **kwargs)<EOL>
Prefetch instagram data and clean it.
f4494:c0:m1
def fetch_instagram_data(self):
<EOL>if not self.url:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>r = requests.get('<STR_LIT>' % self.url)<EOL>if r.status_code is <NUM_LIT:200>:<EOL><INDENT>return json.loads(r.content.decode())<EOL><DEDENT>return r.content<EOL>
Get the instagram data for the url. :return: Dict of data if successful or String if error.
f4494:c0:m2
def get_thumbnail(self):
if self.thumbnail_url:<EOL><INDENT>return self.thumbnail_url<EOL><DEDENT>return '<STR_LIT>'<EOL>
Get the image thumbnail url if it exists. :return: String.
f4494:c0:m3
def get_default_embed(self):
if self.html:<EOL><INDENT>return mark_safe(self.html)<EOL><DEDENT>return '<STR_LIT>'<EOL>
Get the default embed if it exists. :return: HTML String marked safe.
f4494:c0:m4
def get_plugins(cls, *args, **kwargs):
return [plugin(*args, **kwargs) for plugin in cls.plugins]<EOL>
Return a list of plugin instances and pass through arguments.
f4527:c0:m1
def get_all_choices(cls, *args, **kwargs):
plugins = cls.get_plugins(*args, **kwargs)<EOL>all_choices = reduce(operator.add, [<EOL>plugin.choices for plugin in plugins<EOL>])<EOL>choices = []<EOL>seen = set()<EOL>for template, label in all_choices:<EOL><INDENT>if template in seen:<EOL><INDENT>continue<EOL><DEDENT>seen.add(template)<EOL>try:<EOL><INDENT>validators.template_name(template)<EOL><DEDENT>except ValidationError:<EOL><INDENT>continue<EOL><DEDENT>choices.append((template, label))<EOL><DEDENT>choices = sorted(choices, key=lambda a: (a[<NUM_LIT:0>], a[<NUM_LIT:1>]))<EOL>return choices<EOL>
Validate (template), de-duplicate (by template), sort (by label) and return a list of ``(template name, label)`` choices for all plugins.
f4527:c1:m0
@property<EOL><INDENT>def content_type(self):<DEDENT>
return ContentType.objects.get_for_model(self.model)<EOL>
Return the ``ContentType`` for the model.
f4527:c2:m0
@property<EOL><INDENT>def verbose_name(self):<DEDENT>
return self.model._meta.verbose_name<EOL>
Returns the title for the plugin, by default it reads the ``verbose_name`` of the model.
f4527:c2:m1
def __init__(self, field):
self.field = field<EOL>self.choices = self.get_choices() or []<EOL>
Set ``field`` and ``choices`` attributes.
f4527:c3:m0
def get_choices(self):
raise NotImplementedError(<EOL>'<STR_LIT>' % self)<EOL>
Return a list of `(template name, label)` choices.
f4527:c3:m1
def filter_content_types(self, content_type_qs):
return content_type_qs<EOL>
Filter the content types selectable for the content listing. Example to restrict content types to those for models that are subclasses of `AbstractCollectedContent`: valid_ct_ids = [] for ct in content_type_qs: model = ct.model_class() if model and issubclass(model, AbstractCollectedContent): valid_ct_ids.append(ct.id) return content_type_qs.filter(pk__in=valid_ct_ids)
f4539:c1:m1
def get_items(self, apply_limit=True):
model_class = self.content_type.model_class()<EOL>if not model_class:<EOL><INDENT>return []<EOL><DEDENT>items_qs = model_class.objects.all()<EOL>if hasattr(items_qs, '<STR_LIT>'):<EOL><INDENT>if is_draft_request_context():<EOL><INDENT>items_qs = items_qs.draft()<EOL><DEDENT>else:<EOL><INDENT>items_qs = items_qs.published()<EOL><DEDENT><DEDENT>if apply_limit and self.limit:<EOL><INDENT>items_qs = items_qs[:self.limit]<EOL><DEDENT>return items_qs<EOL>
Return the items to show in the listing. If you override this method in a subclass but still call this method via `super` be sure to pass ``apply_limit=False`` when calling the method to avoid applying the count limit too early, then apply it yourself at the end of the override method like this: if self.limit: qs = qs[:self.limit]
f4543:c0:m1
def get_choices(self):
choices = []<EOL>for related_object in self.field.model._meta.get_all_related_objects():<EOL><INDENT>meta = getattr(<EOL>related_object, '<STR_LIT>', related_object.model)._meta<EOL>template_name = '<STR_LIT>' % meta.app_label<EOL>label = '<STR_LIT>' % meta.app_config.verbose_name<EOL>choices.append((template_name, label))<EOL>template_name = '<STR_LIT>' % (<EOL>meta.app_label,<EOL>meta.model_name,<EOL>)<EOL>label = '<STR_LIT>' % (<EOL>meta.app_config.verbose_name,<EOL>meta.verbose_name.capitalize(),<EOL>)<EOL>choices.append((template_name, label))<EOL>for relation in meta.get_all_related_objects():<EOL><INDENT>model = getattr(relation, '<STR_LIT>', relation.model)<EOL>if issubclass(model, meta.model):<EOL><INDENT>template_name = '<STR_LIT>' % (<EOL>meta.app_label,<EOL>meta.model_name,<EOL>model._meta.model_name,<EOL>)<EOL>label = '<STR_LIT>' % (<EOL>meta.app_config.verbose_name,<EOL>model._meta.verbose_name.capitalize(),<EOL>)<EOL>choices.append((template_name, label))<EOL><DEDENT><DEDENT><DEDENT>return choices<EOL>
Return a list of choices for default app and app/model template names: * ``{{ app }}/{{ model }}/layouts/{{ child_model }}.html`` * ``{{ app }}/{{ model }}/layouts/default.html`` * ``{{ app }}/layouts/default.html``
f4553:c1:m0
def get_choices(self):
choices = []<EOL>for label_prefix, templates_dir, template_name_prefix inappsettings.LAYOUT_TEMPLATES:<EOL><INDENT>source_dir = os.path.join(templates_dir, template_name_prefix)<EOL>for local, dirs, files in os.walk(source_dir, followlinks=True):<EOL><INDENT>for source_file in files:<EOL><INDENT>template_name = os.path.join(<EOL>template_name_prefix, source_file)<EOL>label = '<STR_LIT>' % (label_prefix, source_file)<EOL>choices.append((template_name, label))<EOL><DEDENT><DEDENT><DEDENT>return choices<EOL>
Return a list of choices for source files found in configured layout template directories.
f4553:c2:m0
def _get_image_or_404(identifier, load_image=False):
try:<EOL><INDENT>image_id = int(identifier)<EOL><DEDENT>except ValueError:<EOL><INDENT>raise Http404()<EOL><DEDENT>ik_image = get_object_or_404(ICEkitImage, id=image_id)<EOL>if not load_image:<EOL><INDENT>return ik_image, None<EOL><DEDENT>image = Image.open(BytesIO(ik_image.image.read()))<EOL>try:<EOL><INDENT>image.load()<EOL><DEDENT>except IOError:<EOL><INDENT>pass<EOL><DEDENT>image.load()<EOL>if True: <EOL><INDENT>image = et_utils.exif_orientation(image)<EOL><DEDENT>return ik_image, image<EOL>
Return image matching `identifier`. The `identifier` is expected to be a raw image ID for now, but may be more complex later.
f4566:m0
@permission_required('<STR_LIT>')<EOL>def iiif_image_api_info(request, identifier_param):
<EOL>accept_header = request.environ.get('<STR_LIT>')<EOL>if accept_header == '<STR_LIT>':<EOL><INDENT>return HttpResponseNotImplemented(<EOL>"<STR_LIT>")<EOL><DEDENT>ik_image, __ = _get_image_or_404(identifier_param)<EOL>info = {<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT>": request.get_full_path(),<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT:width>": ik_image.width,<EOL>"<STR_LIT>": ik_image.height,<EOL>}<EOL>if ik_image.license:<EOL><INDENT>info['<STR_LIT>'] = [ik_image.license]<EOL><DEDENT>attribution_value = '<STR_LIT:U+0020>'.join([<EOL>"<STR_LIT>" % ik_image.credit if ik_image.credit else '<STR_LIT>',<EOL>"<STR_LIT>" % ik_image.source if ik_image.source else '<STR_LIT>',<EOL>]).strip()<EOL>if attribution_value:<EOL><INDENT>info['<STR_LIT>'] = [{<EOL>"<STR_LIT>": attribution_value,<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>}]<EOL><DEDENT>return JsonResponse(info)<EOL>
Image Information endpoint for IIIF Image API 2.1, see http://iiif.io/api/image/2.1/#image-information
f4566:m1
@permission_required('<STR_LIT>')<EOL>def iiif_image_api(request, identifier_param, region_param, size_param,<EOL>rotation_param, quality_param, format_param):
ik_image, image = _get_image_or_404(identifier_param, load_image=True)<EOL>is_transparent = et_utils.is_transparent(image)<EOL>is_grayscale = image.mode in ('<STR_LIT:L>', '<STR_LIT>')<EOL>format_mapping = {<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>}<EOL>try:<EOL><INDENT>x, y, r_width, r_height = parse_region(<EOL>region_param, image.width, image.height)<EOL>s_width, s_height = parse_size(size_param, r_width, r_height)<EOL>is_mirrored, rotation_degrees =parse_rotation(rotation_param, s_width, s_height)<EOL>quality = parse_quality(quality_param)<EOL>image_format = os.path.splitext(ik_image.image.name)[<NUM_LIT:1>][<NUM_LIT:1>:].lower()<EOL>output_format = parse_format(format_param, image_format)<EOL>corrected_format = format_mapping.get(output_format, output_format)<EOL>canonical_path = make_canonical_path(<EOL>identifier_param, image.width, image.height,<EOL>(x, y, r_width, r_height), <EOL>(s_width, s_height), <EOL>(is_mirrored, rotation_degrees), <EOL>quality,<EOL>output_format<EOL>)<EOL>if request.path != canonical_path:<EOL><INDENT>return HttpResponseRedirect(canonical_path)<EOL><DEDENT>if iiif_storage:<EOL><INDENT>storage_path = build_iiif_file_storage_path(<EOL>canonical_path, ik_image, iiif_storage)<EOL><DEDENT>else:<EOL><INDENT>storage_path = None<EOL><DEDENT>if (<EOL>storage_path and<EOL>iiif_storage.exists(storage_path)<EOL>):<EOL><INDENT>if is_remote_storage(iiif_storage, storage_path):<EOL><INDENT>return HttpResponseRedirect(iiif_storage.url(storage_path))<EOL><DEDENT>else:<EOL><INDENT>return FileResponse(<EOL>iiif_storage.open(storage_path),<EOL>content_type='<STR_LIT>' % corrected_format,<EOL>)<EOL><DEDENT><DEDENT>if x or y or r_width != image.width or r_height != image.height:<EOL><INDENT>box = (x, y, x + r_width, y + r_height)<EOL>image = image.crop(box)<EOL><DEDENT>if s_width != r_width or s_height != r_height:<EOL><INDENT>size = (s_width, s_height)<EOL>image = image.resize(size)<EOL><DEDENT>if quality in ('<STR_LIT:default>', '<STR_LIT>') and not is_grayscale:<EOL><INDENT>if is_transparent:<EOL><INDENT>new_mode = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>new_mode = '<STR_LIT>'<EOL><DEDENT><DEDENT>elif is_grayscale or quality == '<STR_LIT>':<EOL><INDENT>if is_transparent:<EOL><INDENT>new_mode = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>new_mode = '<STR_LIT:L>'<EOL><DEDENT><DEDENT>if new_mode != image.mode:<EOL><INDENT>image = image.convert(new_mode)<EOL><DEDENT>result_image = BytesIO()<EOL>image.save(result_image, format=corrected_format)<EOL>if storage_path:<EOL><INDENT>iiif_storage.save(storage_path, result_image)<EOL><DEDENT>if iiif_storage and is_remote_storage(iiif_storage, storage_path):<EOL><INDENT>return HttpResponseRedirect(iiif_storage.url(storage_path))<EOL><DEDENT>else:<EOL><INDENT>result_image.seek(<NUM_LIT:0>) <EOL>return FileResponse(<EOL>result_image.read(),<EOL>content_type='<STR_LIT>' % corrected_format,<EOL>)<EOL><DEDENT><DEDENT>except ClientError as ex:<EOL><INDENT>return HttpResponseBadRequest(ex.message) <EOL><DEDENT>except UnsupportedError as ex:<EOL><INDENT>return HttpResponseNotImplemented(ex.message)<EOL><DEDENT>
Image repurposing endpoint for IIIF Image API 2.1
f4566:m2
def parse_region(region, image_width, image_height):
if region == '<STR_LIT>':<EOL><INDENT>x, y, width, height = <NUM_LIT:0>, <NUM_LIT:0>, image_width, image_height<EOL><DEDENT>elif region == '<STR_LIT>':<EOL><INDENT>square_size = min(image_width, image_height)<EOL>x = int((image_width - square_size) / <NUM_LIT:2>)<EOL>y = int((image_height - square_size) / <NUM_LIT:2>)<EOL>width = height = square_size<EOL><DEDENT>elif region.startswith('<STR_LIT>'):<EOL><INDENT>x_pct, y_pct, width_pct, height_pct =parse_dimensions_string(region[<NUM_LIT:4>:], permit_floats=True)<EOL>x, y, width, height = list(map(int, (<EOL>x_pct / <NUM_LIT:100> * image_width,<EOL>y_pct / <NUM_LIT:100> * image_height,<EOL>width_pct / <NUM_LIT:100> * image_width,<EOL>height_pct / <NUM_LIT:100> * image_height,<EOL>)))<EOL><DEDENT>else:<EOL><INDENT>x, y, width, height = parse_dimensions_string(region)<EOL><DEDENT>width = min(width, image_width - x)<EOL>height = min(height, image_height - y)<EOL>return x, y, width, height<EOL>
Parse Region parameter to determine the rectangular portion of the full image to be returned, informed by the actual image dimensions. Returns (x, y, width, height): - x,y are pixel offsets into the image from the upper left - width, height are pixel dimensions for cropped image.
f4569:m2
def make_canonical_path(<EOL>image_identifier, image_width, image_height,<EOL>region, size, rotation, quality, format_str<EOL>):
original_aspect_ratio = float(image_width) / image_height<EOL>if (<EOL>region == '<STR_LIT>' or<EOL>(region == '<STR_LIT>' and image_width == image_height) or<EOL>(region == (<NUM_LIT:0>, <NUM_LIT:0>, image_width, image_height))<EOL>):<EOL><INDENT>canonical_region = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>canonical_region = '<STR_LIT:U+002C>'.join(map(str, region))<EOL><DEDENT>if size in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>canonical_size = '<STR_LIT>'<EOL><DEDENT>elif (region[<NUM_LIT:2>:] == size and (image_width, image_height) == size):<EOL><INDENT>canonical_size = '<STR_LIT>'<EOL><DEDENT>elif float(size[<NUM_LIT:0>]) / size[<NUM_LIT:1>] == original_aspect_ratio:<EOL><INDENT>canonical_size = '<STR_LIT>' % size[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>canonical_size = '<STR_LIT:U+002C>'.join(map(str, size))<EOL><DEDENT>canonical_rotation = '<STR_LIT>'<EOL>if rotation[<NUM_LIT:0>]:<EOL><INDENT>canonical_rotation += '<STR_LIT:!>'<EOL><DEDENT>canonical_rotation += '<STR_LIT>' % rotation[<NUM_LIT:1>]<EOL>canonical_quality = quality<EOL>canonical_format = format_str<EOL>return reverse(<EOL>'<STR_LIT>',<EOL>args=[image_identifier, canonical_region, canonical_size,<EOL>canonical_rotation, canonical_quality, canonical_format]<EOL>)<EOL>
Return the canonical URL path for an image for the given region/size/ rotation/quality/format API tranformation settings. See http://iiif.io/api/image/2.1/#canonical-uri-syntax
f4569:m7
def build_iiif_file_storage_path(url_path, ik_image, iiif_storage):
storage_path = url_path[<NUM_LIT:1>:] <EOL>if storage_path.startswith('<STR_LIT>'):<EOL><INDENT>storage_path = storage_path[<NUM_LIT:5>:]<EOL><DEDENT>ik_image_ts = str(calendar.timegm(ik_image.date_modified.timetuple()))<EOL>splits = storage_path.split('<STR_LIT:/>')<EOL>storage_path = '<STR_LIT:/>'.join(<EOL>[splits[<NUM_LIT:0>]] + <EOL>[ik_image_ts] + <EOL>splits[<NUM_LIT:1>:] <EOL>)<EOL>storage_path = storage_path.replace('<STR_LIT:/>', '<STR_LIT:->').replace('<STR_LIT:U+002C>', '<STR_LIT:->')<EOL>storage_path = iiif_storage.get_valid_name(storage_path)<EOL>if iiif_storage.location != '<STR_LIT>':<EOL><INDENT>storage_path = '<STR_LIT>' + storage_path<EOL><DEDENT>return storage_path<EOL>
Return the file storage path for a given IIIF Image API URL path. NOTE: The returned file storage path includes the given ``Image`` instance's ID to ensure the path is unique and identifiable, and its modified timestamp to act as a primitive cache-busting mechanism for when the image is changed but there are pre-existing image conversions. TODO: Ideally we should use a hash or timestamp for Image's actual image data changes, not the whole instance which could change but have same image.
f4569:m8
def is_remote_storage(iiif_storage, storage_path):
<EOL>try:<EOL><INDENT>iiif_storage.path(storage_path)<EOL>return False<EOL><DEDENT>except NotImplementedError:<EOL><INDENT>return True<EOL><DEDENT>
Return ``True`` if given storage class uses remote (not local) storage. See https://docs.djangoproject.com/en/1.10/ref/files/storage/#django.core.files.storage.Storage.path
f4569:m9
def get_item(self):
if hasattr(self, '<STR_LIT>'):<EOL><INDENT>draft = self.get_draft()<EOL><DEDENT>else:<EOL><INDENT>draft = self<EOL><DEDENT>if not hasattr(self, '<STR_LIT>'):<EOL><INDENT>try:<EOL><INDENT>self._item_cache = draft.item.get_published_or_draft()<EOL><DEDENT>except AttributeError:<EOL><INDENT>self._item_cache = draft.item<EOL><DEDENT><DEDENT>return self._item_cache<EOL>
If the item is publishable, get the visible version
f4592:c0:m0
def render(self, request, instance, **kwargs):
if instance.get_item():<EOL><INDENT>return super(LinkPlugin, self).render(request, instance, **kwargs)<EOL><DEDENT>return "<STR_LIT>"<EOL>
Only render the plugin if the item can be shown to the user
f4592:c1:m0
def file_size(self):
try:<EOL><INDENT>return filesizeformat(self.image.size)<EOL><DEDENT>except (OSError, IOError):<EOL><INDENT>return filesizeformat(<NUM_LIT:0>)<EOL><DEDENT>
Obtain the file size for the file in human readable format. :return: String of file size with unit.
f4643:c0:m3
@property<EOL><INDENT>def caption(self):<DEDENT>
if self.show_caption:<EOL><INDENT>return mark_safe(self.caption_override or self.image.caption)<EOL><DEDENT>return None<EOL>
Obtains the caption override or the actual image caption. :return: Caption text (safe).
f4643:c1:m1
@caption.setter<EOL><INDENT>def caption(self, value):<DEDENT>
self.caption_override = value<EOL>
If the caption property is assigned, make it use the `caption_override` field. :param value: The caption value to be saved. :return: None
f4643:c1:m2
@caption.deleter<EOL><INDENT>def caption(self):<DEDENT>
self.caption_override = '<STR_LIT>'<EOL>
If the caption property is to be deleted only delete the caption override. :return: None
f4643:c1:m3
@property<EOL><INDENT>def title(self):<DEDENT>
if self.show_title:<EOL><INDENT>return mark_safe(self.title_override or self.image.title)<EOL><DEDENT>return None<EOL>
Obtains the title override or the actual image title. :return: Title text (safe).
f4643:c1:m4
@title.setter<EOL><INDENT>def title(self, value):<DEDENT>
self.title_override = value<EOL>
If the title property is assigned, make it use the `title_override` field. :param value: The title value to be saved. :return: None
f4643:c1:m5
@title.deleter<EOL><INDENT>def title(self):<DEDENT>
self.title_override = '<STR_LIT>'<EOL>
If the title property is to be deleted only delete the title override. :return: None
f4643:c1:m6
@property<EOL><INDENT>def credit(self):<DEDENT>
return mark_safe(self.image.credit)<EOL>
:return: Image credit (safe).
f4643:c1:m7
def clean_twitter_url(self):
url = self.cleaned_data['<STR_LIT>']<EOL>if url:<EOL><INDENT>pattern = re.compile(r'<STR_LIT>')<EOL>if not pattern.match(url):<EOL><INDENT>raise forms.ValidationError('<STR_LIT>')<EOL><DEDENT><DEDENT>return url<EOL>
Make sure the URL provided matches the twitter URL format.
f4648:c0:m0
def clean(self, *args, **kwargs):
<EOL>twitter_data = self.fetch_twitter_data()<EOL>if isinstance(twitter_data, dict):<EOL><INDENT>if '<STR_LIT>' in twitter_data.keys():<EOL><INDENT>raise exceptions.ValidationError(twitter_data['<STR_LIT>'][<NUM_LIT:0>]['<STR_LIT:message>'])<EOL><DEDENT>for key in twitter_data.keys():<EOL><INDENT>setattr(self, key, twitter_data[key])<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise exceptions.ValidationError(twitter_data)<EOL><DEDENT>super(AbstractTwitterEmbedItem, self).clean(*args, **kwargs)<EOL>
Prefetch twitter data and clean it.
f4652:c0:m1
def fetch_twitter_data(self):
r = requests.get('<STR_LIT>' % self.twitter_url)<EOL>if r.status_code in [<NUM_LIT:200>, <NUM_LIT>]:<EOL><INDENT>return json.loads(r.content.decode('<STR_LIT:utf-8>'))<EOL><DEDENT>return r.content<EOL>
Get the twitter data for the url. :return: Dict of data if successful or String if error.
f4652:c0:m2
def get_default_embed(self):
if self.html:<EOL><INDENT>return mark_safe(self.html)<EOL><DEDENT>return '<STR_LIT>'<EOL>
Get the default embed if it exists. :return: HTML String marked safe.
f4652:c0:m3
def for_model(self, model, **kwargs):
queryset = self.filter(<EOL>content_types=ContentType.objects.get_for_model(model),<EOL>**kwargs<EOL>)<EOL>return queryset<EOL>
Return layouts that are allowed for the given model.
f4665:c0:m0
def annotate_distance_in_km(self, latitude, longitude):
<EOL>GCD = """<STR_LIT>"""<EOL>return self.get_queryset().exclude(map_center_lat=None).exclude(map_center_long=None).annotate(<EOL>distance_in_km=models.expressions.RawSQL(<EOL>GCD,<EOL>(latitude, longitude, latitude)<EOL>)<EOL>).order_by('<STR_LIT>')<EOL>
Return all records with non-null latitude/longitude values with the annotation value `distance_in_km` which is the distance between the record and the given `latitude`/`longitude` location.
f4665:c1:m0
def create_content_instance(content_plugin_class, page, placeholder_name='<STR_LIT>', **kwargs):
<EOL>placeholders = page.get_placeholder_by_slot(placeholder_name)<EOL>if placeholders.exists():<EOL><INDENT>placeholder = placeholders[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>placeholder = page.create_placeholder(placeholder_name)<EOL><DEDENT>ct = ContentType.objects.get_for_model(type(page))<EOL>try:<EOL><INDENT>content_instance = content_plugin_class.objects.create(<EOL>parent_type=ct,<EOL>parent_id=page.id,<EOL>placeholder=placeholder,<EOL>**kwargs<EOL>)<EOL><DEDENT>except TypeError:<EOL><INDENT>raise Exception(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>)<EOL><DEDENT>return content_instance<EOL>
Creates a content instance from a content plugin class. :param content_plugin_class: The class of the content plugin. :param page: The fluent_page instance to create the content instance one. :param placeholder_name: The placeholder name defined in the template. [DEFAULT: main] :param kwargs: Additional keyword arguments to be used in the content instance creation. :return: The content instance created.
f4666:m0
def dedupe_and_sort(sequence, first=None, last=None):
first = first or []<EOL>last = last or []<EOL>new_sequence = [i for i in first if i in sequence]<EOL>for item in sequence:<EOL><INDENT>if item not in new_sequence and item not in last:<EOL><INDENT>new_sequence.append(item)<EOL><DEDENT><DEDENT>new_sequence.extend([i for i in last if i in sequence])<EOL>return type(sequence)(new_sequence)<EOL>
De-dupe and partially sort a sequence. The `first` argument should contain all the items that might appear in `sequence` and for which the order (relative to each other) is important. The `last` argument is the same, but matching items will be placed at the end of the sequence. For example, `INSTALLED_APPS` and `MIDDLEWARE_CLASSES` settings. Items from `first` will only be included if they also appear in `sequence`. Items from `sequence` that don't appear in `first` will come after any that do, and retain their existing order. Returns a sequence of the same type as given.
f4667:m0
def slice_sequences(sequences, start, end, apply_slice=None):
if start < <NUM_LIT:0> or end < <NUM_LIT:0> or end <= start:<EOL><INDENT>raise ValueError('<STR_LIT>' % (start, end))<EOL><DEDENT>items_to_take = end - start<EOL>items_passed = <NUM_LIT:0><EOL>collected_items = []<EOL>if apply_slice is None:<EOL><INDENT>apply_slice = _apply_slice<EOL><DEDENT>for sequence, count in sequences:<EOL><INDENT>offset_start = start - items_passed<EOL>offset_end = end - items_passed<EOL>if items_passed == start:<EOL><INDENT>items = apply_slice(sequence, <NUM_LIT:0>, items_to_take)<EOL><DEDENT>elif <NUM_LIT:0> < offset_start < count:<EOL><INDENT>items = apply_slice(sequence, offset_start, offset_end)<EOL><DEDENT>elif offset_start < <NUM_LIT:0>:<EOL><INDENT>items = apply_slice(sequence, <NUM_LIT:0>, offset_end)<EOL><DEDENT>else:<EOL><INDENT>items = []<EOL><DEDENT>items = list(items)<EOL>collected_items += items<EOL>items_to_take -= len(items)<EOL>items_passed += count<EOL>if items_passed > end or items_to_take == <NUM_LIT:0>:<EOL><INDENT>break<EOL><DEDENT><DEDENT>return collected_items<EOL>
Performs a slice across multiple sequences. Useful when paginating across chained collections. :param sequences: an iterable of iterables, each nested iterable should contain a sequence and its size :param start: starting index to apply the slice from :param end: index that the slice should end at :param apply_slice: function that takes the sequence and start/end offsets, and returns the sliced sequence :return: a list of the items sliced from the sequences
f4667:m2
def is_empty(value):
return value is None or not value.strip()<EOL>
Return `True` if the given value is `None` or empty after `strip()`
f4670:m0
def scale_and_crop_with_ranges(<EOL>im, size, size_range=None, crop=False, upscale=False, zoom=None, target=None, **kwargs):
min_width, min_height = size<EOL>if min_width == <NUM_LIT:0> or min_height == <NUM_LIT:0> or not size_range:<EOL><INDENT>return scale_and_crop(im, size, crop, upscale, zoom, target, **kwargs)<EOL><DEDENT>max_width = min_width + size_range[<NUM_LIT:0>]<EOL>max_height = min_height + size_range[<NUM_LIT:1>]<EOL>min_ar = min_width * <NUM_LIT:1.0> / max_height<EOL>max_ar = max_width * <NUM_LIT:1.0> / min_height<EOL>img_width, img_height = [float(v) for v in im.size]<EOL>img_ar = img_width/img_height<EOL>if img_ar <= min_ar:<EOL><INDENT>size = (min_width, max_height)<EOL><DEDENT>elif img_ar >= max_ar:<EOL><INDENT>size = (max_width, min_height)<EOL><DEDENT>else:<EOL><INDENT>size = (max_width, max_height)<EOL><DEDENT>return scale_and_crop(im, size, crop, upscale, zoom, target, **kwargs)<EOL>
An easy_thumbnails processor that accepts a `size_range` tuple, which indicates that one or both dimensions can give by a number of pixels in order to minimize cropping.
f4672:m0
def describe_page_numbers(current_page, total_count, per_page, page_numbers_at_ends=<NUM_LIT:3>, pages_numbers_around_current=<NUM_LIT:3>):
if total_count:<EOL><INDENT>page_count = int(math.ceil(<NUM_LIT:1.0> * total_count / per_page))<EOL>if page_count < current_page:<EOL><INDENT>raise PageNumberOutOfBounds<EOL><DEDENT>page_numbers = get_page_numbers(<EOL>current_page=current_page,<EOL>num_pages=page_count,<EOL>extremes=page_numbers_at_ends,<EOL>arounds=pages_numbers_around_current,<EOL>)<EOL>current_items_start = (current_page * per_page) - per_page + <NUM_LIT:1><EOL>current_items_end = (current_items_start + per_page) - <NUM_LIT:1><EOL>if current_items_end > total_count:<EOL><INDENT>current_items_end = total_count<EOL><DEDENT><DEDENT>else:<EOL><INDENT>page_count = <NUM_LIT:0><EOL>page_numbers = []<EOL>current_items_start = <NUM_LIT:0><EOL>current_items_end = <NUM_LIT:0><EOL><DEDENT>return {<EOL>'<STR_LIT>': [num for num in page_numbers if not isinstance(num, six.string_types)],<EOL>'<STR_LIT>': '<STR_LIT>' in page_numbers,<EOL>'<STR_LIT>': '<STR_LIT>' in page_numbers,<EOL>'<STR_LIT>': current_page,<EOL>'<STR_LIT>': current_page - <NUM_LIT:1>,<EOL>'<STR_LIT>': current_page + <NUM_LIT:1>,<EOL>'<STR_LIT>': total_count,<EOL>'<STR_LIT>': page_count,<EOL>'<STR_LIT>': per_page,<EOL>'<STR_LIT>': current_items_start,<EOL>'<STR_LIT>': current_items_end,<EOL>}<EOL>
Produces a description of how to display a paginated list's page numbers. Rather than just spitting out a list of every page available, the page numbers returned will be trimmed to display only the immediate numbers around the start, end, and the current page. :param current_page: the current page number (page numbers should start at 1) :param total_count: the total number of items that are being paginated :param per_page: the number of items that are displayed per page :param page_numbers_at_ends: the amount of page numbers to display at the beginning and end of the list :param pages_numbers_around_current: the amount of page numbers to display around the currently selected page :return: a dictionary describing the page numbers, relative to the current page
f4677:m0
def check_settings(required_settings):
defined_settings = [<EOL>setting if hasattr(settings, setting) else None for setting in required_settings<EOL>]<EOL>if not all(defined_settings):<EOL><INDENT>raise NotImplementedError(<EOL>'<STR_LIT>' % '<STR_LIT:U+002CU+0020>'.join(<EOL>set(required_settings) - set(defined_settings)<EOL>)<EOL>)<EOL><DEDENT>
Checks all settings required by a module have been set. If a setting is required and it could not be found a NotImplementedError will be raised informing which settings are missing. :param required_settings: List of settings names (as strings) that are anticipated to be in the settings module. :return: None.
f4678:m0
def RenameAppInMigrationsTable(old_app_name, new_app_name):
return migrations.RunPython(<EOL>_assert_and_rename_app_in_migrations(old_app_name, new_app_name)<EOL>)<EOL>
Check whether an obsolete application name `old_app_name` is present in Django's `django_migrations` DB table and handle the situation as cleanly as possible. If there are migrations for the old app name, perform an UPDATE command to rename the app in this table so future migration runs will succeed, then exit with a `ObsoleteAppNameInMigrationsTableException` to indicate that migrations need to be re-run. If there are no migrations for the old app name -- e.g. the app has already been renamed in the table, or the old pre-rename migrations were never run on the DB -- then no action is performed.
f4679:m1
def cleanup(self):
<EOL>for alias in db.connections.databases:<EOL><INDENT>logger.info('<STR_LIT>', alias)<EOL>db.connections[alias].close()<EOL><DEDENT>
Performs clean-up after task is completed before it is executed again in the next internal.
f4680:c0:m1
def task(self, *args, **options):
raise NotImplementedError(<EOL>'<STR_LIT>')<EOL>
The actual logic of the task to execute. Subclasses must implement this method.
f4680:c0:m2
def resolve(obj, attr, fallback=None):
if obj is None:<EOL><INDENT>return fallback<EOL><DEDENT>value = getattr(obj, attr, fallback)<EOL>if callable(value):<EOL><INDENT>return value()<EOL><DEDENT>return value<EOL>
Resolves obj.attr to a value, calling it as a function if necessary. :param obj: :param attr: a string name of a property or function :param fallback: the value to return if none can be resolved :return: the result of the attribute, or fallback if object/attr not found
f4681:m0
def first_of(obj, *attrs):
for attr in attrs:<EOL><INDENT>r = resolve(obj, attr)<EOL>if r:<EOL><INDENT>return r<EOL><DEDENT><DEDENT>
:param obj: :param attrs: a list of strings :return: the first truthy attribute of obj, calling it as a function if necessary.
f4681:m1
def pre_facet_sqs(self):
sqs = SearchQuerySet()<EOL>if self.query:<EOL><INDENT>sqs = sqs.filter(<EOL>SQ(content=AutoQuery(self.query)) | <EOL>SQ(get_title=AutoQuery(self.query)) | <EOL>SQ(boosted_search_terms=AutoQuery(self.query)) <EOL>)<EOL><DEDENT>return sqs<EOL>
Return the queryset used for generating facets, before any facets are applied
f4684:c0:m1
def get(self, request, *args, **kwargs):
form_class = self.get_form_class()<EOL>form = self.get_form(form_class)<EOL>top_value = self.get_top_level_facet_value()<EOL>subfacets = SEARCH_SUBFACETS.get(top_value, [])<EOL>self.active_facets = [self.top_facet] + subfacets<EOL>if form.is_valid():<EOL><INDENT>self.query = form.cleaned_data.get(self.search_field)<EOL><DEDENT>else:<EOL><INDENT>self.query = "<STR_LIT>"<EOL><DEDENT>sqs = self.pre_facet_sqs()<EOL>for facet in self.active_facets:<EOL><INDENT>sqs = facet.set_on_sqs(sqs)<EOL><DEDENT>facet_counts = sqs.facet_counts()<EOL>for facet in self.active_facets:<EOL><INDENT>facet.set_values_from_sqs_facet_counts(facet_counts)<EOL>facet.apply_request_and_page_to_values(self.request, self.fluent_page)<EOL><DEDENT>for facet in self.active_facets:<EOL><INDENT>sqs = facet.narrow_sqs(sqs)<EOL><DEDENT>context = self.get_context_data(**{<EOL>self.form_name: form,<EOL>'<STR_LIT>': self.active_facets,<EOL>'<STR_LIT>': self.top_facet,<EOL>'<STR_LIT>': self.query,<EOL>'<STR_LIT>': sqs,<EOL>'<STR_LIT>': self.fluent_page,<EOL>'<STR_LIT>': self.show_placeholders()<EOL>})<EOL>return self.render_to_response(context)<EOL>
User has conducted a search, or default state
f4684:c0:m2
def _process_results(self, raw_results, *args, **kwargs):
if '<STR_LIT>' in raw_results:<EOL><INDENT>for agg_fieldname, agg_info in raw_results['<STR_LIT>'].items():<EOL><INDENT>agg_info['<STR_LIT>'] = '<STR_LIT>'<EOL>for bucket_item in agg_info['<STR_LIT>']:<EOL><INDENT>if '<STR_LIT>' in bucket_item:<EOL><INDENT>bucket_item['<STR_LIT>'] = bucket_item['<STR_LIT:key>']<EOL>bucket_item['<STR_LIT:count>'] = bucket_item['<STR_LIT>']<EOL><DEDENT><DEDENT>agg_info['<STR_LIT>'] = agg_info['<STR_LIT>']<EOL><DEDENT>raw_results['<STR_LIT>'] = raw_results['<STR_LIT>']<EOL><DEDENT>return super(ICEkitConfigurableElasticBackend, self)._process_results(raw_results, *args, **kwargs)<EOL>
Naively translate between the 'aggregations' search result data structure returned by ElasticSearch 2+ in response to 'aggs' queries into a structure with 'facets'-like content that Haystack (2.6.1) can understand and process, then pass it on to Haystack's default result processing code. WARNING: Only 'terms' facet types are currently supported. An example result: { 'hits': <BLAH> 'aggregations': { 'type_exact': { 'doc_count_error_upper_bound': 0, 'sum_other_doc_count': 0, 'buckets': [ {'key': 'artwork', 'doc_count': 14145}, {'key': 'artist', 'doc_count': 3360}, {'key': 'event', 'doc_count': 2606}, {'key': 'exhibition', 'doc_count': 416}, {'key': 'essay', 'doc_count': 20}, {'key': 'publication', 'doc_count': 1} ] } } } Will be translated to look like: { 'hits': <BLAH> 'facets': { 'type_exact': { '_type': 'terms', 'terms': [ {'term': 'artwork', 'count': 14145}, {'term': 'artist', 'count': 3360}, {'term': 'event', 'count': 2606}, {'term': 'exhibition', 'count': 416}, {'term': 'essay', 'count': 20}, {'term': 'publication', 'count': 1} ] } } } NOTE: We don't bother cleaning up the data quite this much really, we just translate and duplicate item names and leave the old ones in place for a time when Haystack may support the real returned results.
f4685:c0:m1
def set_values_from_sqs_facet_counts(self, sqs_facet_counts):
self._values = []<EOL>if sqs_facet_counts.has_key('<STR_LIT>'):<EOL><INDENT>if not self.select_many and sqs_facet_counts['<STR_LIT>'][self.field_name]:<EOL><INDENT>self._values += [<EOL>FacetValue(<EOL>facet=self,<EOL>value=None,<EOL>label="<STR_LIT>",<EOL>is_all_results=True,<EOL>)<EOL>]<EOL><DEDENT>self._values += [<EOL>FacetValue(<EOL>facet=self,<EOL>value=value,<EOL>label=value,<EOL>count=count<EOL>)<EOL>for value, count in sqs_facet_counts['<STR_LIT>'][self.field_name]<EOL>]<EOL><DEDENT>
Use the sqs.facet_counts() result to set up values and counts.
f4687:c1:m2
def apply_request_and_page_to_values(self, request, page=None):
value_is_set = False<EOL>for value in self._values:<EOL><INDENT>value.apply_request_and_page(request, page)<EOL><DEDENT>
Use the request and page config to figure out which values are active
f4687:c1:m3
def narrow_sqs(self, sqs):
if self.select_many:<EOL><INDENT>sq = None<EOL>for value in self.get_applicable_values():<EOL><INDENT>q = SQ(**{self.field_name: sqs.query.clean(value.value)})<EOL>if sq:<EOL><INDENT>sq = sq | q<EOL><DEDENT>else:<EOL><INDENT>sq = q<EOL><DEDENT><DEDENT>if sq:<EOL><INDENT>sqs = sqs.narrow(sq)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>for value in self.get_applicable_values():<EOL><INDENT>sqs = sqs.narrow(<EOL>u'<STR_LIT>' % (self.field_name, sqs.query.clean(value.value))<EOL>)<EOL><DEDENT><DEDENT>return sqs<EOL>
TODO: Currently this is an AND conjunction. It should vary depending on the value of self.select_many.
f4687:c1:m5
def get_applicable_values(self):
return [v for v in self._values if v.is_active and not v.is_all_results]<EOL>
Return selected values that will affect the search result
f4687:c1:m7
def get_value(self):
try:<EOL><INDENT>return self.get_applicable_values()[<NUM_LIT:0>]<EOL><DEDENT>except IndexError:<EOL><INDENT>if not self.select_many and self.get_values():<EOL><INDENT>return self.get_values()[<NUM_LIT:0>]<EOL><DEDENT><DEDENT>
Returns the label of the first value
f4687:c1:m8
def is_default(self):
if not self.get_applicable_values():<EOL><INDENT>return True<EOL><DEDENT>if self.get_value().is_default:<EOL><INDENT>return True<EOL><DEDENT>return False<EOL>
Return True if no active values, or if the active value is the default
f4687:c1:m9
def index_queryset(self, using=None):
return self.get_model().objects.published().select_related()<EOL>
Index published objects.
f4688:c0:m0
def full_prepare(self, obj):
prepared_data = super(AbstractLayoutIndex, self).full_prepare(obj)<EOL>prepared_data['<STR_LIT>'] = get_model_ct(self.get_model())<EOL>return prepared_data<EOL>
Make django_ct equal to the type of get_model, to make polymorphic children show up in results.
f4688:c0:m1
def update_site(sender, **kwargs):
Site = apps.get_model('<STR_LIT>', '<STR_LIT>')<EOL>domain = settings.SITE_DOMAIN<EOL>if settings.SITE_PORT:<EOL><INDENT>domain += '<STR_LIT>' % settings.SITE_PORT<EOL><DEDENT>Site.objects.update_or_create(<EOL>pk=settings.SITE_ID,<EOL>defaults=dict(<EOL>domain=domain,<EOL>name=settings.SITE_NAME))<EOL>sequence_sql = connection.ops.sequence_reset_sql(no_style(), [Site])<EOL>if sequence_sql:<EOL><INDENT>cursor = connection.cursor()<EOL>for command in sequence_sql:<EOL><INDENT>cursor.execute(command)<EOL><DEDENT><DEDENT>
Update `Site` object matching `SITE_ID` setting with `SITE_DOMAIN` and `SITE_PORT` settings.
f4692:m0
def formfield(self, **kwargs):
if self.plugin_class:<EOL><INDENT>self._choices = self.plugin_class.get_all_choices(field=self)<EOL><DEDENT>return super(TemplateNameField, self).formfield(**kwargs)<EOL>
Get choices from plugins, if necessary.
f4693:c0:m1
@classmethod<EOL><INDENT>def register_model_once(cls, ModelClass, **kwargs):<DEDENT>
if cls._static_registry.get_for_model(ModelClass) is None:<EOL><INDENT>logger.warn("<STR_LIT>"<EOL>.format(cls, ModelClass))<EOL><DEDENT>else:<EOL><INDENT>cls.register_model.register(ModelClass, **kwargs)<EOL><DEDENT>
Tweaked version of `AnyUrlField.register_model` that only registers the given model after checking that it is not already registered.
f4693:c1:m0
def formfield_for_foreignkey(self, db_field, *args, **kwargs):
formfield = super(FluentLayoutsMixin, self).formfield_for_foreignkey(<EOL>db_field, *args, **kwargs)<EOL>if db_field.name == '<STR_LIT>':<EOL><INDENT>formfield.queryset = formfield.queryset.for_model(self.model)<EOL><DEDENT>return formfield<EOL>
Update queryset for ``layout`` field.
f4694:c0:m0
def get_placeholder_data(self, request, obj):
if not obj or not getattr(obj, '<STR_LIT>', None):<EOL><INDENT>data = [PlaceholderData(slot='<STR_LIT>', role='<STR_LIT:m>', title='<STR_LIT>')]<EOL><DEDENT>else:<EOL><INDENT>data = obj.layout.get_placeholder_data()<EOL><DEDENT>return data<EOL>
Get placeholder data from layout.
f4694:c0:m1
def get_thumbnail_source(self, obj):
if hasattr(self, '<STR_LIT>') and self.thumbnail_field:<EOL><INDENT>return resolve(obj, self.thumbnail_field)<EOL><DEDENT>if hasattr(obj, '<STR_LIT>'):<EOL><INDENT>return resolve(obj, "<STR_LIT>")<EOL><DEDENT>logger.warning('<STR_LIT>')<EOL>return None<EOL>
Obtains the source image field for the thumbnail. :param obj: An object with a thumbnail_field defined. :return: Image field for thumbnail or None if not found.
f4694:c4:m0
def preview(self, obj, request=None):
source = self.get_thumbnail_source(obj)<EOL>if source:<EOL><INDENT>try:<EOL><INDENT>from easy_thumbnails.files import get_thumbnailer<EOL><DEDENT>except ImportError:<EOL><INDENT>logger.warning(<EOL>_(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>)<EOL>)<EOL>return '<STR_LIT>'<EOL><DEDENT>try:<EOL><INDENT>thumbnailer = get_thumbnailer(source)<EOL>thumbnail = thumbnailer.get_thumbnail(self.thumbnail_options)<EOL>return '<STR_LIT>'.format(<EOL>thumbnail.url)<EOL><DEDENT>except Exception as ex:<EOL><INDENT>logger.warning(<EOL>_(u'<STR_LIT>'<EOL>u'<STR_LIT>'.format(source)))<EOL>if self.thumbnail_show_exceptions:<EOL><INDENT>return '<STR_LIT>'.format(ex)<EOL><DEDENT><DEDENT><DEDENT>return '<STR_LIT>'<EOL>
Generate the HTML to display for the image. :param obj: An object with a thumbnail_field defined. :return: HTML for image display.
f4694:c4:m1
def _build_app_models(request, admin_apps, models_tuples, ensure_all_models=False):
app_models = []<EOL>for app_and_model, config in models_tuples:<EOL><INDENT>if app_and_model:<EOL><INDENT>app_label, model_name = app_and_model.split('<STR_LIT:.>')<EOL>for app in admin_apps:<EOL><INDENT>if app['<STR_LIT>'] == app_label:<EOL><INDENT>for model in app['<STR_LIT>']:<EOL><INDENT>if model['<STR_LIT:object_name>'] == model_name:<EOL><INDENT>try:<EOL><INDENT>model['<STR_LIT:name>'] =config['<STR_LIT:name>']<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT>model_class = apps.get_model(app_and_model)<EOL>model_admin = admin.site._registry[model_class]<EOL>if hasattr(model_admin, '<STR_LIT>'):<EOL><INDENT>model['<STR_LIT>'] =model_admin.get_child_type_choices(<EOL>request, '<STR_LIT>'<EOL>)<EOL><DEDENT>if '<STR_LIT>' in config.keys():<EOL><INDENT>ct = ContentType.objects.get_by_natural_key(<EOL>*config['<STR_LIT>'].lower().split('<STR_LIT:.>')<EOL>)<EOL>model.default_poly_child = ct.id<EOL><DEDENT>app_models.append(model)<EOL><DEDENT><DEDENT>break<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return app_models<EOL>
:param request: Request object :param admin_apps: The apps registered with the admin instance :param models_tuples: A list of (fully-qualified model name, config_dict) tuples :return:
f4695:m0