def render(self, context): import time if type(self.cachetime) != int: cachetime = self.cachetime.resolve(context) else: cachetime = self.cachetime if isinstance(self.cachekey, basestring): cachekey = self.cachekey else: cachekey = self.cachekey.resolve(context) if type(self.isdebug) != bool: isdebug = self.isdebug.resolve(context) else: isdebug = self.isdebug from base.utils import get_or_set_cache def get_value(): result = self.nodelist.render(context) value = {'result': result, 'time': time.time()} return value value = get_or_set_cache(u'cache_%s' % cachekey, get_value, self.cachetime) if isdebug: from django.utils.safestring import SafeText return SafeText('<!- cache key=%s time=%s cached@%s ttl=%s -->' % (cachekey, cachetime, int(value['time']), int(cachetime + value['time'] - time.time()))) + value['result'] + SafeText( '<!- end cache key=%s -->' % (cachekey)) else: return value['result']
def student_view(self, context=None): """ The primary view, shown to students when viewing courses. """ user_service = self.runtime.service(self, 'user') xb_user = user_service.get_current_user() CURRENT = xb_user.opt_attrs.get('edx-platform.username') html = self.resource_string("static/html/gossxblock.html") frag = Fragment(html.format(self=self)) res0 = textwrap.dedent(""" <p id='goss_hidden'><span id="gosscurrent">{}</span></p> """).format(CURRENT) frag.add_content(SafeText(res0)) HTMLURL = 'https://node-server.online/r/assets/x92.html' if sys.version_info.major >= 3: response = urlopen(HTMLURL) encoding = response.info().get_content_charset('utf-8') html_data = response.read().decode(encoding) else: html_data = urlopen(HTMLURL).read() res = textwrap.dedent(html_data) frag.add_content(SafeText(res)) frag.add_css(self.resource_string("static/css/gossxblock.css")) frag.add_javascript( self.resource_string("static/js/src/goss92xblock.js")) frag.initialize_js('Goss92XBlock') return frag
def test_safe_string(self): safe_text = SafeText("dummy & safe data <html> ") safe_bytes = SafeText("dummy & safe data <html> ") self.cur.execute("INSERT INTO {0} VALUES(%s, %s)".format(self.tbl), (safe_text, safe_bytes)) self.cur.execute("SELECT * FROM {0}".format(self.tbl), ()) self.assertEqual(self.cur.fetchall(), [(safe_text, safe_bytes.encode())])
def get_template_sources(self, template_name, template_dirs=None): if template_name.startswith(APP_NAME): root = APP_NAME + '/' template_name = SafeText(template_name.replace(root, '{}themes/{}/'.format(root, conf.BOOTSTRAP3_THEME))) return super(AppDirectoriesLoader, self).get_template_sources( template_name, # _get_bs3_app_template_dirs(template_dirs), )
def success_message(self, result=None): (n, dry_run) = self.result if not n: return SafeText("No duplicates were found in the set") if dry_run: return SafeText("Found {n} duplicates, but did not delete them. Re-run without dry-run to remove" .format(**locals())) else: return SafeText("Removed {n} duplicates from the set!" .format(**locals()))
def get_context_data(self, **kwargs): context = super(PublicApplicationFeedback, self).get_context_data(**kwargs) app_id = self.kwargs['pk'] context['page_heading'] = 'Application for new Part 5 - '+app_id context['left_sidebar'] = 'yes' context['action'] = self.kwargs['action'] app = self.get_object() doclist = app.proposed_development_plans.all() context['proposed_development_plans_list'] = [] for doc in doclist: pub_web = None try: pub_web = PublicationWebsite.objects.get(original_document_id=doc.id,application=self.kwargs['pk']) # print PublicationWebsite.objects.get(original_document_id=doc.id) except: pub_web = None fileitem = {} if pub_web is None: fileitem['fileid'] = doc.id fileitem['path'] = doc.upload.name fileitem['path_short'] = SafeText(doc.upload.name)[19:] fileitem['name'] = doc.name fileitem['file_url'] = doc.file_url() context['proposed_development_plans_list'].append(fileitem) else: fileitem['fileid'] = pub_web.published_document.id fileitem['path'] = pub_web.published_document.upload.name fileitem['path_short'] = SafeText(pub_web.published_document.upload.name)[19:] fileitem['name'] = pub_web.published_document.name fileitem['file_url'] = pub_web.published_document.file_url() context['proposed_development_plans_list'].append(fileitem) if app.river_lease_scan_of_application: pub_web = None try: pub_web = PublicationWebsite.objects.get(original_document_id=app.river_lease_scan_of_application.id,application=self.kwargs['pk']) # print PublicationWebsite.objects.get(original_document_id=doc.id) except: pub_web = None # print pub_web if pub_web is None: context['river_lease_scan_of_application'] = app.river_lease_scan_of_application else: # print pub_web.published_document context['river_lease_scan_of_application'] = pub_web.published_document context['approval'] = [] approval = Approval.objects.filter(application=app) if approval.count() > 0: context['approval'] = approval[0] return context
def test_compression(self): """Test with ``ADV_CACHE_COMPRESS`` set to ``True``.""" # Reset CacheTag config with default value (from the ``override_settings``) self.reload_config() expected = "foobar" # We don't use new lines here because too complicated to set empty lines with only # spaces in a docstring with we'll have to compute the compressed version t = "{% load adv_cache %}{% cache 1 test_cached_template obj.pk obj.updated_at %}" \ " {{ obj.get_name }} {% endcache %}" # Render a first time, should miss the cache self.assertStripEqual(self.render(t), expected) self.assertEqual(self.get_name_called, 1) # Now the rendered template should be in cache key = self.get_template_key( 'test_cached_template', vary_on=[self.obj['pk'], self.obj['updated_at']]) self.assertEqual( key, 'template.cache.test_cached_template.0cac9a03d5330dd78ddc9a0c16f01403' ) # It should be in the cache, compressed # We use ``SafeText`` as django does in templates compressed = zlib.compress(pickle.dumps(SafeText(" foobar ")), -1) cache_expected = b'1::' + compressed # Test with ``assertEqual``, not ``assertStripEqual`` self.assertEqual(get_cache('default').get(key), cache_expected) # Render a second time, should hit the cache self.assertStripEqual(self.render(t), expected) self.assertEqual(self.get_name_called, 1) # Still 1 # Changing the compression level should not invalidate the cache CacheTag.options.compress_level = 9 self.assertStripEqual(self.render(t), expected) self.assertEqual(self.get_name_called, 1) # Still 1 # But if the cache is invalidated, the new one will use this new level get_cache('default').delete(key) self.assertStripEqual(self.render(t), expected) self.assertEqual(self.get_name_called, 2) # One more compressed = zlib.compress(pickle.dumps(SafeText(" foobar ")), 9) cache_expected = b'1::' + compressed self.assertEqual(get_cache('default').get(key), cache_expected)
def student_view(self, context=None): """ The primary view of the Goss2XBlock, shown to students when viewing courses. """ user_service = self.runtime.service(self, 'user') xb_user = user_service.get_current_user() CURRENT = xb_user.opt_attrs.get('edx-platform.username') XURL = 'https://fork.kodaktor.ru/testxblock2' response = urllib.urlopen(XURL) data = json.loads(response.read()) CHECK = data['message'] html = self.resource_string("static/html/goss4xblock.html") frag = Fragment(html.format(self=self)) res = textwrap.dedent(""" <h2>X4a: Server app challenge</h2> <p>Your server app URL should return this: <span id="gosscurrent">{}</span>!</h2> <p>The address {} returned {}</h2> <div>Enter URL: <input id='gossinput' /><br/> <button id='gosssend'>send to server</button> </div> """).format(CURRENT, XURL, CHECK) frag.add_content(SafeText(res)) frag.add_css(self.resource_string("static/css/goss4xblock.css")) frag.add_javascript( self.resource_string("static/js/src/goss4xblock.js")) frag.initialize_js('Goss4XBlock') return frag
def listKeyword(self): objs = self.keyword_set.all() arr = [] for item in objs: arr.append("<span style='margin:0 5px'>" + item.name + "</span>") # print(SafeText("".join(arr))) return SafeText("".join(arr))
def as_ul(self): if not self: return SafeText() first = self[0] if isinstance(first, tuple): valid_list = [] invalid_list = [] for e in self: """ Ignore $pristine errors, as they relate to the original rejected error handling or djng-error bound-field""" if e[2] == '$pristine': continue if e[3] == '$valid': li_format = self.li_format_valid error_list = valid_list elif e[5] == '$message': li_format = self.li_format_bind error_list = invalid_list else: li_format = self.li_format error_list = invalid_list msg_type = e[3].split('.') err_tuple = (e[0], msg_type[0] if len(msg_type) == 1 else msg_type.pop(), e[4], force_text(e[5])) error_list.append(format_html(li_format, *err_tuple)) return mark_safe(format_html(self.ul_format_valid, first[0], first[1], self._get_form_name(first[0]), mark_safe(''.join(valid_list)))) \ + mark_safe(format_html(self.ul_format, first[0], first[1], self._get_form_name(first[0]), mark_safe(''.join(invalid_list)))) return format_html( '<ul class="errorlist">{0}</ul>', format_html_join('', '<li>{0}</li>', ((force_text(e), ) for e in self)))
def format_value(self, suggestion): """ Turn the whole form in to a value string """ name = suggestion.name suggestion_dict = {"name": name, "object": suggestion} candidacies = (suggestion.memberships.select_related( "post", "party", "ballot__election").prefetch_related( Prefetch( "ballot__officialdocument_set", queryset=OfficialDocument.objects.filter( document_type=OfficialDocument.NOMINATION_PAPER). order_by("-modified"), )).order_by("-ballot__election__election_date")[:3]) if candidacies: suggestion_dict["previous_candidacies"] = [] for candidacy in candidacies: text = """{election}: {post} – {party}""".format( post=candidacy.ballot.post.short_label, election=candidacy.ballot.election.name, party=candidacy.party.name, ) sopn = candidacy.ballot.officialdocument_set.first() if sopn: text += ' (<a href="{0}">SOPN</a>)'.format( sopn.get_absolute_url()) suggestion_dict["previous_candidacies"].append(SafeText(text)) return [suggestion.pk, suggestion_dict]
def get_project_page_display(self): if not self.project_page: return url = reverse("wagtailadmin_pages:edit", args=(self.project_page.pk,)) return SafeText( f"<a href='{url}'>{self.project_page}</a>" )
def as_ul(self): if not self: return SafeText() first = self[0] if isinstance(first, tuple): error_lists = {'$pristine': [], '$dirty': []} for e in self: if e[5] == '$message': li_format = '<li ng-show="{0}.{1} && {0}.{3}" class="{2}" ng-bind="{0}.{3}"></li>' else: li_format = '<li ng-show="{0}.{1}" class="{2}">{3}</li>' err_tuple = (e[0], e[3], e[4], force_text(e[5])) error_lists[e[2]].append(format_html(li_format, *err_tuple)) # renders and combine both of these lists dirty_errors, pristine_errors = '', '' if len(error_lists['$dirty']) > 0: dirty_errors = format_html( '<ul ng-show="{0}.$dirty && !{0}.$untouched" class="{1}" ng-cloak>{2}</ul>', # duck typing: !...$untouched first[0], first[1], mark_safe(''.join(error_lists['$dirty']))) if len(error_lists['$pristine']) > 0: pristine_errors = format_html( '<ul ng-show="{0}.$pristine" class="{1}" ng-cloak>{2}</ul>', first[0], first[1], mark_safe(''.join(error_lists['$pristine']))) return format_html('{}{}', dirty_errors, pristine_errors) return format_html( '<ul class="errorlist">{0}</ul>', format_html_join('', '<li>{0}</li>', ((force_text(e), ) for e in self)))
def as_ul(self): if not self: return SafeText() first = self[0] if isinstance(first, tuple): error_lists = {'$pristine': [], '$dirty': []} for e in self: li_format = e[ 5] == '$message' and self.li_format_bind or self.li_format err_tuple = (e[0], e[3], e[4], force_text(e[5])) error_lists[e[2]].append(format_html(li_format, *err_tuple)) err_tuple = ("apiErrors." + first[0], "msg", first[4], "msg") error_lists["$dirty"].append( format_html(self.li_format_bind, *err_tuple)) # renders and combine both of these lists return mark_safe(''.join([ format_html(self.ul_format, first[0], first[1], prop, mark_safe(''.join(list_items))) for prop, list_items in error_lists.items() ])) return format_html( '<ul class="errorlist">{0}</ul>', format_html_join('', '<li>{0}</li>', ((force_text(e), ) for e in self)))
def new_render(cls, context): """ Override existing url method to use pluses instead of spaces """ get = "?%s=%s" % ('team', context.get('team', 'none')) s = SafeText(get) return str(old_render(cls, context)) + get
def generate_config_form(self, config): # Populate form with configured TAXII Servers choices = [(server, server) for server in config['taxii_servers']] form = forms.TAXIIServiceConfigForm(choices, initial=config) html = render_to_string('services_config_form.html', { 'name': self.name, 'form': form, 'config_error': None }) # Change form action from service default idx = html.find('action="') idx2 = html[idx:].find('" ') action = 'action="/services/taxii_service/configure/' html = html[0:idx] + action + html[idx + idx2:] # Add TAXII Server config buttons to form idx = html.rfind('</td></tr>\n </table>') buttons = '<br /><input class="form_submit_button" type="button" id="add" value="Add" /> <input class="form_submit_button" type="button" id="edit" value="Edit Selected" /> <input class="form_submit_button" type="button" id="remove" value="Remove Selected" />' html = html[0:idx] + buttons + html[idx:] # Add JS events for TAXII Server config buttons html = html + "\n<script>$('#add').click(function() {location.href = '/services/taxii_service/configure/';});$('#edit').click(function() {var data = $('#id_taxii_servers').val(); if (data) {location.href = '/services/taxii_service/configure/' + data + '/';}}); $('#remove').click(function() {var data = {'remove_server': $('#id_taxii_servers').val()}; var url = '/services/taxii_service/configure/'; $.ajax({async: false, type: 'POST', url: url, data: data, datatype: 'json', success: function(data) {if (data.success) {$('#id_taxii_servers').html(data.html);} else {$('#service_edit_results').text('Failed to remove server configuration.');}}});});</script>" return forms.TAXIIServiceConfigForm, SafeText(html)
def field_name(value, field): ''' Django template filter which returns the verbose name of an object's, model's or related manager's field. ''' title = value._meta.get_field(field).verbose_name.title() return SafeText('<label>{0}</label>'.format(title))
def render_html(self, product, postfix): """ Return a HTML snippet containing a rendered summary for the given product. This HTML snippet typically contains a ``<figure>`` element with a sample image ``<img src="..." >`` and a ``<figcaption>`` containing a short description of the product. Build a template search path with `postfix` distinction. """ if not self.label: msg = "The Product Serializer must be configured using a `label` field." raise exceptions.ImproperlyConfigured(msg) app_label = product._meta.app_label.lower() request = self.context['request'] cache_key = 'product:{0}|{1}-{2}-{3}-{4}-{5}'.format(product.id, app_label, self.label, product.product_model, postfix, get_language_from_request(request)) content = cache.get(cache_key) if content: return mark_safe(content) params = [ (app_label, self.label, product.product_model, postfix), (app_label, self.label, 'product', postfix), ('shop', self.label, product.product_model, postfix), ('shop', self.label, 'product', postfix), ] try: template = select_template(['{0}/products/{1}-{2}-{3}.html'.format(*p) for p in params]) except TemplateDoesNotExist: return SafeText("<!-- no such template: '{0}/products/{1}-{2}-{3}.html' -->".format(*params[0])) # when rendering emails, we require an absolute URI, so that media can be accessed from # the mail client absolute_base_uri = request.build_absolute_uri('/').rstrip('/') context = {'product': product, 'ABSOLUTE_BASE_URI': absolute_base_uri} content = strip_spaces_between_tags(template.render(context, request).strip()) cache.set(cache_key, content, app_settings.CACHE_DURATIONS['product_html_snippet']) return mark_safe(content)
def format_value(self, suggestion): """ Turn the whole form in to a value string """ name = suggestion.name try: candidacy = suggestion.object.memberships.select_related( 'post__extra', 'on_behalf_of', 'post_election__election').order_by( '-post_election__election__election_date').first() if candidacy: name = """ <strong>{name}</strong> (previously stood in {post} in the {election} as a {party} candidate) """.format( name=name, post=candidacy.post.extra.short_label, election=candidacy.extra.post_election.election.name, party=candidacy.on_behalf_of.name, ) name = SafeText(name) except AttributeError: pass return [suggestion.pk, name]
def join_admin_buttons(links: List['Hyperlink']) -> str: ''' Joins together multiple Hyperlinks into a single HTML string consisting of buttons. ''' return SafeText(' '.join(map(lambda link: link.admin_button_html, links)))
def test_weird_text_save(self): "test 'weird' text type (different in py2 vs py3)" from django.utils.safestring import SafeText key = 'test attr 2' value = SafeText('test attr value 2') self.obj1.attributes.add(key, value) self.assertEqual(self.obj1.attributes.get(key), value)
def intervention_message(request, intervention_id): intervention = get_object_or_404(Intervention, pk=intervention_id) practice_name = intervention.contact.cased_name context = {} show_header_from = True if intervention.method == "p": show_header_to = True else: show_header_to = False template = "intervention.html" encoded_image = make_chart(intervention.metadata["value"]) with open( os.path.join(settings.BASE_DIR, "nimodipine", "static", "header.png"), "rb") as img: header_image = base64.b64encode(img.read()).decode("ascii") with open( os.path.join(settings.BASE_DIR, "nimodipine", "static", "footer.png"), "rb") as img: footer_image = base64.b64encode(img.read()).decode("ascii") intervention_url = "op2.org.uk{}".format(intervention.get_absolute_url()) intervention_url = '<a href="http://{}">{}</a>'.format( intervention_url, intervention_url) context.update({ "intervention": intervention, "practice_name": practice_name, "intervention_url": SafeText(intervention_url), "encoded_image": encoded_image, "header_image": header_image, "footer_image": footer_image, "show_header_from": show_header_from, "show_header_to": show_header_to, }) return render(request, template, context=context)
def markdown(value, arg=None): markdown_raw = mark_safe(markdownify(value)) if not isinstance(arg, dict) and arg is not None: arg = [arg] for i in arg: markdown_raw = markdown_raw.replace('</{}'.format(i[1:]), '') markdown_raw = markdown_raw.replace(i, '') return SafeText(markdown_raw)
def format_time(iso_8601: str) -> SafeString: """ Transforms iso string to %a, %b %d, %Y %I %p %Z. Parameter: iso_8601 - the string to format Returns: An the input parameter on failure or an transformed SafeString with human readable time format. """ try: time = datetime.strptime(iso_8601, "%Y-%m-%dT%H:%M:%S%z") return SafeText(datetime.strftime(time, "%a, %b %d, %Y %I %p %Z")) except (ValueError, TypeError) as _: return SafeText(iso_8601)
def related_object_link(obj: Model, name: str = None) -> str: """ Generates a link to the selected value for a foreign key, for use in the admin change view. """ url = resolve_url(admin_urlname(obj._meta, SafeText("change")), obj.pk) if not name: name = str(obj) return format_html(f'<a href="{url}">{name}</a>')
def test_long_slugs_should_not_get_split_midword(self): """The slug should not get split mid-word.""" self.entry.title = SafeText( "Please tell me where everyone is getting their assumptions about me?" * 100) self.entry.save() # The ending should not be a split word. self.assertEqual(self.entry.slug[-25:], 'everyone-is-getting-their')
def success_message(self, result=None): old = ArticleSet.objects.get(pk=self.kwargs['articleset']) old_name = escape(old.name) new_name = escape(self.result.name) old_url = reverse('navigator:articleset-details', kwargs=self.kwargs) return SafeText("""Created sample set {new_name} as shown below. <a href='{old_url}'>Return to original set {old.id}: {old_name}</a>""" .format(**locals()))
def join_admin_buttons(links: List["Hyperlink"]) -> str: """ Joins together multiple Hyperlinks into a single HTML string consisting of buttons. """ return SafeText(" ".join( map(lambda link: link.admin_button_html, links)))
def chart(self, instance): return SafeText( format_html(""" <iframe src="{}" width="800px" height="600px"></iframe>""", reverse('deliverable_chart', kwargs={ 'deliverable_id': str(instance.id) })))
def render(self, context): if type(self.valuetoken) not in [str, unicode]: value = self.valuetoken.resolve(context) else: value = self.valuetoken context[self.newname] = value from django.utils.safestring import SafeText return SafeText('<!- rename to %s -->' % (self.newname))
def success_message(self, result=None): old = ArticleSet.objects.get(pk=self.kwargs['articleset_id']) return SafeText( "Created sample set {newname} as shown below. " "<a href='{oldurl}'>Return to original set {old.id} : {oldname}</a>" .format(newname=escape(self.result.name), oldurl=reverse('article set-details', kwargs=self.kwargs), oldname=escape(old.name), **locals()))