本文整理汇总了Python中pyramid.renderers.render函数的典型用法代码示例。如果您正苦于以下问题:Python render函数的具体用法?Python render怎么用?Python render使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了render函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: send_collaborator_added_email
def send_collaborator_added_email(request, user, submitter, project_name, role,
email_recipients):
fields = {
'username': user.username,
'project': project_name,
'submitter': submitter.username,
'role': role
}
subject = render(
'email/collaborator-added.subject.txt', fields, request=request
)
body = render(
'email/collaborator-added.body.txt', fields, request=request
)
for recipient in email_recipients:
request.task(send_email).delay(
subject,
body,
recipient=_compute_recipient(recipient),
)
return fields
示例2: send_email_verification_email
def send_email_verification_email(request, user, email):
token_service = request.find_service(ITokenService, name='email')
token = token_service.dumps({
"action": "email-verify",
"email.id": email.id,
})
fields = {
'token': token,
'email_address': email.email,
'n_hours': token_service.max_age // 60 // 60,
}
subject = render(
'email/verify-email.subject.txt', fields, request=request
)
body = render(
'email/verify-email.body.txt', fields, request=request
)
request.task(send_email).delay(
subject,
body,
recipient=_compute_recipient(user, email=email.email),
)
return fields
示例3: send_termination_mail
def send_termination_mail(request, user):
mailer = get_mailer(request)
support_email = request.registry.settings.get('mail.support_email', '[email protected]')
site_name = request.registry.settings.get("site.name", "eduID")
context = {
'support_mail': support_email,
'displayName': user.get_display_name()
}
message = Message(
subject=_("{site_name} account termination").format(
site_name=site_name),
sender=request.registry.settings.get("mail.default_sender"),
recipients=[user.get_mail()],
body=render(
"templates/termination_email.txt.jinja2",
context,
request,
),
html=render(
"templates/termination_email.html.jinja2",
context,
request,
),
)
# Development
if request.registry.settings.get("development", '') == 'true':
print message.body
else:
mailer.send(message)
log.debug("Sent termination mail to user {!r} with address {!s}.".format(user, user.get_mail()))
request.stats.count('dashboard/email_send_termination_mail', 1)
示例4: generate
def generate(request, user):
"""
Generate an email for a user password reset request.
:param request: the current request
:type request: pyramid.request.Request
:param user: the user to whom to send the reset code
:type user: h.models.User
:returns: a 4-element tuple containing: recipients, subject, text, html
"""
serializer = request.registry.password_reset_serializer
code = serializer.dumps(user.username)
context = {
'username': user.username,
'reset_code': code,
'reset_link': request.route_url('account_reset_with_code', code=code)
}
subject = _('Reset your password')
text = render('h:templates/emails/reset_password.txt.jinja2',
context,
request=request)
html = render('h:templates/emails/reset_password.html.jinja2',
context,
request=request)
return [user.email], subject, text, html
示例5: send_verification_mail
def send_verification_mail(request, email, code=None):
mailer = get_mailer(request)
if code is None:
code = new_verification_code(request, "mailAliases", email, request.context.user, hasher=get_short_hash)
verification_link = generate_verification_link(request, code, "mailAliases")
site_name = request.registry.settings.get("site.name", "eduID")
context = {
"email": email,
"verification_link": verification_link,
"site_url": request.context.safe_route_url("home"),
"site_name": site_name,
"code": code,
}
message = Message(
subject=_("{site_name} confirmation email").format(site_name=site_name),
sender=request.registry.settings.get("mail.default_sender"),
recipients=[email],
body=render("templates/verification_email.txt.jinja2", context, request),
html=render("templates/verification_email.html.jinja2", context, request),
)
mailer.send(message)
示例6: testRenderInlineCached
def testRenderInlineCached(self):
self.config.add_renderer(name='chart',
factory='chartfood.InlineChartRenderer')
cache = DummyCache()
rendered = render('chart', {'datasource_url': 'http://test.com/data',
'cache': cache,
'container_id': 'foo'})
expected = '\n'.join((
self.inline_prefix,
" containerId: 'foo',",
" chartType: 'LineChart',",
" dataSourceUrl: 'http://test.com/data',",
self.inline_postfix))
self.assertEqual(rendered, expected)
cache['http://test.com/data'] = self.day_score
rendered = render('chart', {'datasource_url': 'http://test.com/data',
'cache': cache,
'container_id': 'foo'})
expected = '\n'.join((
self.inline_prefix,
" containerId: 'foo',",
" chartType: 'LineChart',",
" dataTable: {},".format(self.day_score_json),
self.inline_postfix))
self.assertEqual(rendered, expected)
示例7: test_with_request_content_type_notset
def test_with_request_content_type_notset(self):
from pyramid.renderers import render
from mootiro_web.crypto import enable_crypto
enable_crypto(self.config, rsa_key=self.rsa_key)
request = testing.DummyRequest()
render('json.encrypted', {'a': 1}, request)
self.assertEqual(request.response.content_type, 'application/json')
示例8: email_preview
def email_preview(context, request):
notification_email_data = {
'document_title': 'A very important article',
'document_path': 'http://example.com/article?some-long=query',
'parent_text': 'This is the parent comment',
'parent_user': 'toby',
'parent_tags': 'comment, important, news',
'parent_timestamp': datetime.now() - timedelta(hours=1),
'parent_user_profile': 'https://hypothes.is/u/toby',
'parent_path': 'https://hypothes.is/a/123456789',
'reply_text': 'This is a reply to the parent comment',
'reply_user': 'anna',
'reply_timestamp': datetime.now(),
'reply_user_profile': 'https://hypothes.is/u/anna',
'reply_path': 'http://hypothes.is/a/abcdefghijk',
}
return {
'emails': (
{
'title': 'Notification Email',
'subject': render(ReplyTemplate.subject,
notification_email_data, request),
'text': render(ReplyTemplate.text_template,
notification_email_data, request),
'html': render(ReplyTemplate.html_template,
notification_email_data, request),
},
)
}
示例9: start
def start(self, context, request, appstruct, **kw):
user = get_current()
source = appstruct['source']
targets = appstruct['targets']
if can_access(user, source) and all(can_access(user, target)
for target in targets):
diff_bodies = {}
source_view = renderers.render(
source.templates.get('diff', None),
{'object': source},
request)
for target in targets:
target_view = renderers.render(
target.templates.get('diff', None),
{'object': target},
request)
soupt, textdiff = html_diff_wrapper.render_html_diff(
source_view, target_view)
diff_bodies[target] = (textdiff, get_oid(target))
return {'context_view': source_view,
'contents': diff_bodies}
return {}
示例10: password_reminder
def password_reminder(email, request):
"""
For an email address, find the corresponding team and send a password
reset token. If no team is found send an email that no user was found for
this address.
"""
mailer = get_mailer(request)
team = DBSession.query(Team).filter(Team.email == email).first()
if team:
# send mail with reset token
team.reset_token = random_token()
html = render('mail_password_reset_valid.mako', {'team': team},
request=request)
recipients = [team.email]
else:
# send mail with information that no team was found for that address.
html = render('mail_password_reset_invalid.mako', {'email': email},
request=request)
recipients = [email]
competition = request.registry.settings['competition_title']
message = Message(subject="Password Reset for %s" % competition,
recipients=recipients,
html=html,
)
mailer.send(message)
return team
示例11: _add_modal
def _add_modal(self, explanations, process, soup, tag, context, request):
context_oid = get_oid(context)
dace_ui_api = get_current_registry().getUtility(IDaceUIAPI,
'dace_ui_api')
explanationitemaction = None
explanationitem_actions = process.get_actions('explanationitem')
if explanationitem_actions:
explanationitemaction = explanationitem_actions[0]
if explanationitemaction:
values = {'url': request.resource_url(context, '@@explanationjson',
query={'op': 'getform',
'itemid': tag['data-item']}),
'item': explanations[tag['data-item']],
}
body = renderers.render(self.explanation_template, values, request)
explanation_item_soup = BeautifulSoup(body)
actionurl_update = dace_ui_api.updateaction_viewurl(
request=request,
action_uid=str(get_oid(explanationitemaction)),
context_uid=str(context_oid))
values = {'url': actionurl_update,
'item': explanations[tag['data-item']],
}
modal_body = renderers.render(self.modal_template, values, request)
explanation_item_modal_soup = BeautifulSoup(modal_body)
soup.body.append(explanation_item_modal_soup.body)
tag.append(explanation_item_soup.body)
tag.body.unwrap()
示例12: send_password_reset_email
def send_password_reset_email(request, user):
token_service = request.find_service(ITokenService, name='password')
token = token_service.dumps({
'action': 'password-reset',
'user.id': str(user.id),
'user.last_login': str(user.last_login),
'user.password_date': str(user.password_date),
})
fields = {
'token': token,
'username': user.username,
'n_hours': token_service.max_age // 60 // 60,
}
subject = render(
'email/password-reset.subject.txt',
fields,
request=request,
)
body = render(
'email/password-reset.body.txt',
fields,
request=request,
)
request.task(send_email).delay(body, [user.email], subject)
# Return the fields we used, in case we need to show any of them to the
# user
return fields
示例13: repr_filter
def repr_filter(filter_data, request, template_type='default'):
filter_schema = FilterSchema()
global_template = FILTER_TEMPLATES['global'][template_type]
filter_template = FILTER_TEMPLATES['filter'][template_type]
all_filters = []
for filter_ in filter_data:
filter_values = []
for child in filter_schema.children:
name = child.name
value = filter_.get(name, _marker)
if hasattr(child, 'repr_value') and \
value is not _marker:
filter_values.append(
child.repr_value(
value, request, template_type))
values = {'bodies': filter_values}
all_filters.append(renderers.render(
filter_template,
values, request))
values = {'bodies': all_filters}
body = renderers.render(
global_template,
values, request)
return body
示例14: test_render
def test_render(self):
from pyramid.renderers import render
from mootiro_web.crypto import enable_crypto
enable_crypto(self.config, rsa_key=self.rsa_key)
result_normal = render('json', {'a': 1})
result_encrypted = render('json.encrypted', {'a': 1})
self.assertNotEqual(result_normal, result_encrypted)
示例15: export_chat
def export_chat(chat_id: int, user_id: int):
settings = app.conf["PYRAMID_REGISTRY"].settings
log.info("Starting export for chat %s, user %s." % (chat_id, user_id))
with db_session() as db, TemporaryDirectory() as workspace:
start_time = datetime.datetime.now()
chat = db.query(Chat).filter(Chat.id == chat_id).one()
user = db.query(User).filter(User.id == user_id).one()
try:
chat_user = db.query(ChatUser).filter(and_(ChatUser.chat_id == chat_id, ChatUser.user_id == user_id)).one()
except NoResultFound:
# ChatUser has probably been deleted since the export was triggered.
delete_expired_export.apply_async((chat_id, user_id), countdown=5)
raise
chat_export = db.query(ChatExport).filter(and_(ChatExport.chat_id == chat_id, ChatExport.user_id == user_id)).one()
if export_chat.request.id and chat_export.celery_task_id != export_chat.request.id:
raise RuntimeError("Current task ID doesn't match value in database.")
message_count = db.query(func.count("*")).select_from(Message).filter(Message.chat_id == chat_id).scalar()
page_count = int(math.ceil(message_count/MESSAGES_PER_PAGE))
filename = "%s.zip" % chat.url
file_in_workspace = os.path.join(workspace, filename)
with ZipFile(file_in_workspace, "w", ZIP_DEFLATED) as f:
f.write(resource_filename("cherubplay", "static/cherubplay2.css"), "cherubplay2.css")
f.write(resource_filename("cherubplay", "static/logo.png"), "logo.png")
for n in range(page_count):
log.info("Processing page %s of %s." % (n+1, page_count))
messages = (
db.query(Message)
.filter(Message.chat_id == chat_id)
.order_by(Message.id)
.offset(n * MESSAGES_PER_PAGE).limit(MESSAGES_PER_PAGE).all()
)
f.writestr("%s.html" % (n+1), render("export/chat.mako", {
"chat": chat,
"user": user,
"chat_user": chat_user,
"messages": messages,
"current_page": n+1,
"messages_per_page": MESSAGES_PER_PAGE,
"message_count": message_count,
}))
f.writestr("%s.json" % (n+1), render("json", messages))
f.writestr("chat.json", render("json", chat))
f.writestr("chat_user.json", render("json", chat_user))
chat_export.filename = filename
chat_export.generated = start_time
chat_export.expires = datetime.datetime.now() + datetime.timedelta(int(settings["export.expiry_days"]))
pathlib.Path(os.path.join(app.conf["PYRAMID_REGISTRY"].settings["export.destination"], chat_export.file_directory)).mkdir(parents=True, exist_ok=True)
os.rename(file_in_workspace, os.path.join(app.conf["PYRAMID_REGISTRY"].settings["export.destination"], chat_export.file_path))
log.info("Finished export for chat %s, user %s." % (chat_id, user_id))