def add_sharing_banner(page, response):
if not getattr(settings, 'WAGTAILSHARING_BANNER', True):
return
if hasattr(response, 'render') and callable(response.render):
response.render()
html = force_text(response.content)
body = re.search(r'(?i)<body.*?>', html)
if body:
endpos = body.end()
banner_template_name = 'wagtailsharing/banner.html'
banner_template = loader.get_template(banner_template_name)
banner_html = banner_template.render()
banner_html = force_text(banner_html)
content_with_banner = html[:endpos] + banner_html + html[endpos:]
response.content = content_with_banner
python类get_template()的实例源码
test_integrates_with_template_rendering.py 文件源码
项目:django-performance-testing
作者: PaesslerAG
项目源码
文件源码
阅读 35
收藏 0
点赞 0
评论 0
def test_has_support_for_elapsed_time_in_template_render(settings):
settings.PERFORMANCE_LIMITS = {
'Template.render': {
'time': {
'total': 0
}
}
}
template = loader.get_template('all-group-names.markdown')
with freeze_time('2016-09-29 15:52:01') as frozen_time:
class SlowIterable(object):
def __iter__(self):
yield 'foo'
frozen_time.tick(timedelta(seconds=5))
yield 'bar'
with pytest.raises(LimitViolationError) as excinfo:
template.render(context={'groups': SlowIterable()})
assert excinfo.value.context == {'template': ['all-group-names.markdown']}
def handler500(request, template_name='500.html'):
t = get_template(template_name)
tt, value, tb = sys.exc_info()
ctx = Context({'exception_value': value,
'value': tt,
'tb': traceback.format_exception(tt, value, tb)})
return HttpResponseServerError(t.render(ctx))
def _send_invitation_mail(request, invitation, subject, template_name):
if not invitation.invitee.email:
return
old_lang = translation.get_language()
translation.activate(invitation.invitee.language)
template = loader.get_template('groups/mail_{0}.txt'.format(template_name))
message = template.render({
'invitation': invitation,
'site': get_current_site(request)
})
translation.activate(old_lang)
send_mail(settings.EMAIL_SUBJECT_PREFIX + subject,
message,
settings.DEFAULT_FROM_EMAIL,
[invitation.invitee.email],
fail_silently=True)
def send_notification_message(build_id, user_id):
reset_database_connection()
build = Build.objects.get(id=build_id)
user = User.objects.get(id=user_id)
try:
log_lines = build.flows.order_by('-date_end')[0].log.split('\n')
except:
log_lines = build.log.split('\n')
log_lines = '\n'.join(log_lines[-25:])
template_txt = get_template('build/email.txt')
template_html = get_template('build/email.html')
context = {
'build': build,
'log_lines': log_lines,
}
subject = '[{}] Build #{} of {} {} - {}'.format(build.repo.name, build.id, build.branch.name, build.plan.name, build.get_status().upper())
message = template_txt.render(Context(context))
html_message = template_html.render(Context(context))
return send_mail(subject, message, settings.FROM_EMAIL, [user.email], html_message=html_message)
def send_order_email_confirmation(sender, instance, **kwargs):
"""
Send email to customer with order details.
"""
order = instance
message = get_template("emails/order_conf.html").render(Context({
'order': order.get_serialized_data()
}))
mail = EmailMessage(
subject="Order confirmation",
body=message,
from_email=EMAIL_ADMIN,
to=[order.email],
reply_to=[EMAIL_ADMIN],
)
mail.content_subtype = "html"
return mail.send()
def gen_sudo_script(role_list, sudo_list):
# receive role_list = [role1, role2] sudo_list = [sudo1, sudo2]
# return sudo_alias={'NETWORK': '/sbin/ifconfig, /ls'} sudo_user={'user1': ['NETWORK', 'SYSTEM']}
sudo_alias = {}
sudo_user = {}
for sudo in sudo_list:
sudo_alias[sudo.name] = sudo.commands
for role in role_list:
sudo_user[role.name] = ','.join(sudo_alias.keys())
sudo_j2 = get_template('jperm/role_sudo.j2')
sudo_content = sudo_j2.render(Context({"sudo_alias": sudo_alias, "sudo_user": sudo_user}))
sudo_file = NamedTemporaryFile(delete=False)
sudo_file.write(sudo_content)
sudo_file.close()
return sudo_file.name
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK):
success_url = form.opts.get('success_url', '')
delete_url = form.opts.get('delete_url', '')
if delete_url:
delete_url += '&' if '?' in delete_url else '?'
delete_url += 'success_url=' + force_text(form.opts.get('delete_success_url', success_url))
template = get_template(form.opts.get('form_actions_template', 'ajaxviews/_form_controls.html'))
btn_group = template.render({
'delete_url': delete_url,
'success_url': force_text(success_url),
'modal_form': form.opts.get('modal_form', False),
'form_preview': form.opts.get('preview_stage', False),
'delete_confirmation': form.opts.get('delete_confirmation', False),
'form_cfg': json.dumps(form.form_cfg) if getattr(form, 'form_cfg', None) else None,
})
layout_object = FormActions(
Submit('save', form.opts.get('save_button_name', 'Save')),
HTML(btn_group),
style='margin-bottom: 0;'
)
return layout_object.render(form, form_style, context)
def process_response(self, request, response):
if not request.is_ajax() and not isinstance(response, HttpResponseRedirect) and hasattr(response, 'content'):
content = force_text(response.content, encoding=response.charset)
if '</body>' not in content:
return response
json_cfg = {}
if hasattr(response, 'context_data'):
json_cfg = response.context_data.get('json_cfg', {})
template = get_template('ajaxviews/_middleware.html')
html = template.render({
'json_cfg': json_cfg,
'main_name': settings.REQUIRE_MAIN_NAME,
})
l_content, r_content = content.rsplit('</body>', 1)
content = ''.join([l_content, html, '</body>', r_content])
response.content = response.make_bytes(content)
if response.get('Content-Length', None):
response['Content-Length'] = len(response.content)
return response
def search(request):
if request.method == 'GET':
search_text = request.GET.get('search_text')
groupname = request.session.get('user_group')
hasgroup = Group.objects.get(name=groupname)
print search_text
print hasgroup.name
filelist = File.objects.filter(Q(name__icontains=search_text)&(Q(perm__groups=hasgroup)|Q(ispublic="True"))).distinct()
# filelist = File.objects.filter((Q(name=search_text)|Q(ispublic="True"))).distinct()
listoffiledir=list(filelist)
folderlist = {}
template = loader.get_template('wxWeb/index2.html')
context = Context({
'filepath': listoffiledir,
'foldlist': folderlist,
})
return HttpResponse(template.render(context))
def index(request):
fileindexfolder = get_object_or_404(Folder, name="ab")
# listoffiledir = [singlefile.file for singlefile in fileindexfolder.files ]
hasuser = 'sclmmanager'
listoffiledir = list(fileindexfolder.get_childfile_read())
can_read_folder = list(fileindexfolder.get_childfolder_read())
# can_read_folder = fileindexfolder.get_children()
folderlist = []
for id in can_read_folder:
fold = Folder.objects.get(id=id)
folderlist.append(fold)
template = loader.get_template('wxWeb/index.html')
context = Context({
'filepath':listoffiledir,
'foldlist': folderlist,
})
#print template.render(context)
return HttpResponse(template.render(context))
def render_flatpage(request, f):
"""
Internal interface to the flat page view.
"""
# If registration is required for accessing this page, and the user isn't
# logged in, redirect to the login page.
if f.registration_required and not request.user.is_authenticated():
from django.contrib.auth.views import redirect_to_login
return redirect_to_login(request.path)
if f.template_name:
template = loader.select_template((f.template_name, DEFAULT_TEMPLATE))
else:
template = loader.get_template(DEFAULT_TEMPLATE)
# To avoid having to always use the "|safe" filter in flatpage templates,
# mark the title and content as already safe (since they are raw HTML
# content in the first place).
f.title = mark_safe(f.title)
f.content = mark_safe(f.content)
response = HttpResponse(template.render({'flatpage': f}, request))
return response
def bad_request(request, exception, template_name='400.html'):
"""
400 error handler.
Templates: :template:`400.html`
Context: None
"""
try:
template = loader.get_template(template_name)
except TemplateDoesNotExist:
return http.HttpResponseBadRequest('<h1>Bad Request (400)</h1>', content_type='text/html')
# No exception content is passed to the template, to not disclose any sensitive information.
return http.HttpResponseBadRequest(template.render())
# This can be called when CsrfViewMiddleware.process_view has not run,
# therefore need @requires_csrf_token in case the template needs
# {% csrf_token %}.
def render_flatpage(request, f):
"""
Internal interface to the flat page view.
"""
# If registration is required for accessing this page, and the user isn't
# logged in, redirect to the login page.
if f.registration_required and not request.user.is_authenticated:
from django.contrib.auth.views import redirect_to_login
return redirect_to_login(request.path)
if f.template_name:
template = loader.select_template((f.template_name, DEFAULT_TEMPLATE))
else:
template = loader.get_template(DEFAULT_TEMPLATE)
# To avoid having to always use the "|safe" filter in flatpage templates,
# mark the title and content as already safe (since they are raw HTML
# content in the first place).
f.title = mark_safe(f.title)
f.content = mark_safe(f.content)
response = HttpResponse(template.render({'flatpage': f}, request))
return response
def render(element, markup_classes):
element_type = element.__class__.__name__.lower()
if element_type == 'boundfield':
add_input_classes(element)
template = get_template("materializecssform/field.html")
context = {'field': element, 'classes': markup_classes}
else:
has_management = getattr(element, 'management_form', None)
if has_management:
for form in element.forms:
for field in form.visible_fields():
add_input_classes(field)
template = get_template("materializecssform/formset.html")
context = {'formset': element, 'classes': markup_classes}
else:
for field in element.visible_fields():
add_input_classes(field)
template = get_template("materializecssform/form.html")
context = {'form': element, 'classes': markup_classes}
return template.render(context)
def schedule_list_csv(request, slug=None):
schedule = fetch_schedule(slug)
presentations = Presentation.objects.filter(section=schedule.section)
presentations = presentations.exclude(cancelled=True).order_by("id")
response = HttpResponse(mimetype="text/csv")
if slug:
file_slug = slug
else:
file_slug = "presentations"
response["Content-Disposition"] = 'attachment; filename="%s.csv"' % file_slug
response.write(loader.get_template("schedule/schedule_list.csv").render(Context({
"presentations": presentations,
})))
return response
def render(self, name, value, attrs=None):
# Prepare values
attrs = self.build_attrs(attrs, name=name)
if not value:
value = ''
options = getattr(settings, 'MARKEDIT_DEFAULT_SETTINGS', {})
if 'options' in attrs:
options = self._eval_value(attrs['options'], {})
del attrs['options']
# Render widget to HTML
t = loader.get_template('markedit/ui.html')
c = Context({
'attributes': self._render_attrs(attrs),
'value': conditional_escape(force_unicode(value)),
'id': attrs['id'],
'options': options,
})
return t.render(c)
def do_loadmacros(parser, token):
try:
tag_name, filename = token.split_contents()
except IndexError:
m = ("'%s' tag requires at least one argument (macro name)"
% token.contents.split()[0])
raise template.TemplateSyntaxError, m
if filename[0] in ('"', "'") and filename[-1] == filename[0]:
filename = filename[1:-1]
t = get_template(filename)
macros = t.nodelist.get_nodes_by_type(DefineMacroNode)
## Metadata of each macro are stored in a new attribute
## of 'parser' class. That way we can access it later
## in the template when processing 'usemacro' tags.
_setup_macros_dict(parser)
for macro in macros:
parser._macros[macro.name] = macro
return LoadMacrosNode()
def render(self, name, value, attrs=None):
if attrs is None:
attrs = {}
# it's called "original" because it will be replaced by a copy
attrs['class'] = 'hstore-original-textarea'
# get default HTML from AdminTextareaWidget
html = super(BaseAdminHStoreWidget, self).render(name, value, attrs)
# prepare template context
template_context = Context({
'field_name': name,
'STATIC_URL': settings.STATIC_URL,
'use_svg': django.VERSION >= (1, 9), # use svg icons if django >= 1.9
})
# get template object
template = get_template('happenings/hstore_%s_widget.html' % self.admin_style)
# render additional html
additional_html = template.render(template_context)
# append additional HTML and mark as safe
html = html + additional_html
html = mark_safe(html)
return html
def get_learning_result(request):
if request.method == 'GET':
learning_form = QueryLearningForm(request.GET)
if learning_form.is_valid():
cd = learning_form.cleaned_data
try:
train = Prediction.objects.get(step_hash=cd['stephash'], type=cd['type'])
template = loader.get_template('ui/get_learning_result.html')
context = {
'hit': train,
}
return success(template.render(context))
except Exception as e:
return error(e)
else:
return error(str(learning_form.errors))
else:
return error('Error Method.')
def show_learning_steps(request):
if request.method == 'GET':
if 'parent' in request.GET:
if request.user.is_superuser:
step_list = Protocol.objects.filter(parent=int(request.GET['parent'])).all()
else:
step_list = Protocol.objects.filter(parent=
int(request.GET['parent'])).filter(user_id=request.user.id).all()
template = loader.get_template('ui/show_learning_steps.html')
context = {
'step_list': step_list,
}
return success(template.render(context))
else:
return error('Wrong parameter.')
else:
return error('Method error.')
def _get_critical_checks_snippet(request, unit):
"""Retrieves the critical checks snippet.
:param request: an `HttpRequest` object
:param unit: a `Unit` instance for which critical checks need to be
rendered.
:return: rendered HTML snippet with the failing checks, or `None` if
there are no critical failing checks.
"""
if not unit.has_critical_checks():
return None
can_review = check_user_permission(request.user, 'review',
unit.store.parent)
ctx = {
'canreview': can_review,
'unit': unit,
}
template = loader.get_template('editor/units/xhr_checks.html')
return template.render(context=ctx, request=request)
def render_flatpage(request, f):
"""
Internal interface to the flat page view.
"""
# If registration is required for accessing this page, and the user isn't
# logged in, redirect to the login page.
if f.registration_required and not request.user.is_authenticated:
from django.contrib.auth.views import redirect_to_login
return redirect_to_login(request.path)
if f.template_name:
template = loader.select_template((f.template_name, DEFAULT_TEMPLATE))
else:
template = loader.get_template(DEFAULT_TEMPLATE)
# To avoid having to always use the "|safe" filter in flatpage templates,
# mark the title and content as already safe (since they are raw HTML
# content in the first place).
f.title = mark_safe(f.title)
f.content = mark_safe(f.content)
response = HttpResponse(template.render({'flatpage': f}, request))
return response
def view_error(request, analysis_type, country_abbrev, state_name, error_id):
"""View the error with the given error_id."""
error = models.MapError.objects.get(id=error_id)
if request.POST:
if request.GET.get('flag_error'):
error.flagged_count += 1
error.save()
context = {
'center': ((error.ne_lon + error.sw_lon) / 2, (error.ne_lat + error.sw_lat) / 2),
'error': error,
'country_abbrev': country_abbrev,
'state_title': state_name.replace('-', ' ').title(),
'state_name': state_name,
'analysis_title': analysis_type.replace('-', ' ').title(),
'analysis_type': analysis_type
}
template = loader.get_template('view_error.html')
return HttpResponse(template.render(context, request))
def inclusion_tag(file_name, context_class=Context, takes_context=False):
def wrap(func):
@functools.wraps(func)
def method(self, context, nodes, *arg, **kwargs):
_dict = func(self, context, nodes, *arg, **kwargs)
from django.template.loader import get_template, select_template
if isinstance(file_name, Template):
t = file_name
elif not isinstance(file_name, basestring) and is_iterable(file_name):
t = select_template(file_name)
else:
t = get_template(file_name)
_dict['autoescape'] = context.autoescape
_dict['use_l10n'] = context.use_l10n
_dict['use_tz'] = context.use_tz
_dict['admin_view'] = context['admin_view']
csrf_token = context.get('csrf_token', None)
if csrf_token is not None:
_dict['csrf_token'] = csrf_token
nodes.append(t.render(_dict))
return method
return wrap
def hijack_field(self, obj):
hijack_attributes = hijack_settings.HIJACK_URL_ALLOWED_ATTRIBUTES
if 'user_id' in hijack_attributes:
hijack_url = reverse('hijack:login_with_id', args=(obj.pk, ))
elif 'email' in hijack_attributes:
hijack_url = reverse('hijack:login_with_email', args=(obj.email, ))
else:
hijack_url = reverse('hijack:login_with_username', args=(obj.username, ))
button_template = get_template(hijack_admin_settings.HIJACK_BUTTON_TEMPLATE)
button_context = {
'hijack_url': hijack_url,
'username': str(obj),
}
if VERSION < (1, 8):
button_context = Context(button_context)
return button_template.render(button_context)
def send_email_ticket_confirm(request, payment_info):
"""
:param request Django request object
:param payment_info Registration object
"""
mail_title = u"PyCon APAC 2016 ???? ??(Registration confirmation)"
product = Product()
variables = Context({
'request': request,
'payment_info': payment_info,
'amount': product.price
})
html = get_template('mail/ticket_registered_html.html').render(variables)
text = get_template('mail/ticket_registered_text.html').render(variables)
msg = EmailMultiAlternatives(
mail_title,
text,
settings.EMAIL_SENDER,
[payment_info.email])
msg.attach_alternative(html, "text/html")
msg.send(fail_silently=False)
def render_flatpage(request, f):
"""
Internal interface to the flat page view.
"""
# If registration is required for accessing this page, and the user isn't
# logged in, redirect to the login page.
if f.registration_required and not request.user.is_authenticated:
from django.contrib.auth.views import redirect_to_login
return redirect_to_login(request.path)
if f.template_name:
template = loader.select_template((f.template_name, DEFAULT_TEMPLATE))
else:
template = loader.get_template(DEFAULT_TEMPLATE)
# To avoid having to always use the "|safe" filter in flatpage templates,
# mark the title and content as already safe (since they are raw HTML
# content in the first place).
f.title = mark_safe(f.title)
f.content = mark_safe(f.content)
response = HttpResponse(template.render({'flatpage': f}, request))
return response
def log_tests(request):
es = get_elastic()
if not es:
return HttpResponse('not able to connect to elasticsearch')
res = es.search(index="message-log", doc_type='message', body={
"size": 0,
"aggs" : {
"test_ids" : {
"terms" : { "field" : "test_id", "size" : 500 }
}
}})
test_ids = []
for bucket in res['aggregations']['test_ids']['buckets']:
test_id = bucket['key']
test_ids.append({'id':'test_id_'+test_id, 'name':test_id})
context = {
'groups' : test_ids
}
template = loader.get_template('golem/log.html')
return HttpResponse(template.render(context,request))
def pdfPG(request, nrop):
if not request.session['nropreinscripto'] == nrop:
return HttpResponse("ERROR AL GENERAR EL COMPROBANTE")
template = get_template('pg/pg/comprobante.html')
postulante = Postulante.objects.get(pg__nro_de_preinscripto=nrop)
contexto = {'postulante' : postulante }
pdf = render_to_pdf('pg/pg/comprobante.html', contexto)
if pdf:
response = HttpResponse(pdf, content_type='application/pdf')
filename = "Comprobante_Preinscripcion"
content = "inline; filename='%s'" % (filename)
return response
return HttpResponse("ERROR AL GENERAR EL COMPROBANTE")
####
#listado de todas las preinscripciones