def checksums(request, sha1):
buildinfo = Buildinfo.objects.filter(
checksums__checksum_sha1=sha1,
).select_related(
'source',
'architecture',
).order_by()
return JsonResponse({'buildinfos': [{
'uri': '{}{}'.format(
settings.SITE_URL,
x.get_absolute_url(),
),
'raw-uri': '{}{}'.format(
settings.SITE_URL,
x.get_absolute_raw_url(),
),
'source': x.source.name,
'version': x.version,
'architecture': x.architecture.name,
} for x in buildinfo]})
python类SITE_URL的实例源码
def send_summary(report_pk):
report = Report.objects.get(pk=report_pk)
daily = report.get_daily()
messages = []
questions = daily.report.question_set.active()
surveys = daily.survey_set.all()
for user in report.stakeholders:
context = Context({'user': user,
'daily': daily,
'surveys': surveys,
'questions': questions})
context['SITE_URL'] = settings.SITE_URL
subject = render_to_string('email/summary_subject.txt', context)
text = get_template('email/summary.txt')
html = get_template('email/summary.html')
text_content = text.render(context)
html_content = html.render(context)
messages.append([subject, text_content, html_content, settings.DEFAULT_FROM_EMAIL, [user.email]])
send_mass_html_mail(messages)
daily.summary_submitted = now()
daily.save()
def shorten_url(request):
url = request.POST.get("url", '')
valid_url,url=validate_url(url)
if valid_url:
if url in record:
short_id = record.get(url)
response_data = {}
response_data['url'] = settings.SITE_URL + "/" + short_id
return HttpResponse(json.dumps(response_data), content_type="application/json")
else:
# check whether input is already short
if is_already_short(url):
response_data = {}
return HttpResponse(json.dumps({"already_short": True}), content_type="application/json")
else:
short_id = get_short_code()
record.update({url:short_id})
b = urls(httpurl=url, short_id=short_id)
b.save()
response_data = {}
response_data['url'] = settings.SITE_URL + "/" + short_id
return HttpResponse(json.dumps(response_data), content_type="application/json")
return HttpResponse(json.dumps({"error": "error occurs", "valid_url":valid_url,'url':url}), content_type="application/json")
def is_already_short(url):
popular_shortening_urls = [
'bit.ly/',
'goo.gl/',
'ow.ly/',
'is.gd/',
'buff.ly/',
'adf.ly/',
'tinyurl.com/',
'bit.do/',
'mcaf.ee/',
't.co/',
'tiny.cc/',
'shorte.st/',
'idek.net/',
'po.st/',
'yep.it/',
'tr.im/',
settings.SITE_URL,
]
for shortening_url in popular_shortening_urls:
if shortening_url in url:
return True
return False
def _build_url(self):
"""
Generate frontend url to granted object
:return: str
"""
u = urlparse.urljoin(settings.SITE_URL, '/#/')
m = self.object.__class__.__name__
if m == 'Workspace':
return urlparse.urljoin(
u, 'workspaces/w/{}'.format(self.object.slug)
)
elif m == 'Vault':
return urlparse.urljoin(
u, 'workspaces/w/{}/vaults/v/{}'.format(
self.object.workspace.slug, self.object.slug))
elif m == 'Card':
return urlparse.urljoin(
u, '/workspaces/w/{}/vaults/v/{}/cards/c/{}'.format(
self.object.vault.workspace.slug, self.object.vault.slug,
self.object.slug))
return None
def form_valid(self, form):
email = form.cleaned_data['email']
user = User.objects.get(username=email)
safe = URLSafeTimedSerializer(settings.SECRET_KEY)
url = '{site}{path}?key={key}'.format(
site=settings.SITE_URL,
path=reverse('login'),
key=safe.dumps(user.id),
)
send_mail(
_('Link to login into the Knowledge Base'),
url,
settings.DEFAULT_FROM_EMAIL,
[email],
fail_silently=False,
html_message=render_to_string(
'login_email.html', {'url': url}
),
)
return redirect('home')
def check_production_settings(app_configs, **kwargs):
issues = []
if settings.DEBUG:
return issues
if not settings.EMAIL_HOST_PASSWORD or 'TODO' in settings.EMAIL_HOST_PASSWORD:
issues.append(
Warning(
"EMAIL_HOST_PASSWORD setting is not set to proper value",
id='tg_utils.W001',
)
)
if 'TODO' in settings.SITE_URL:
issues.append(
Warning(
"SITE_URL setting is not set to proper value",
id='tg_utils.W002',
)
)
return issues
def get_external_url(self):
url = '{}{}'.format(settings.SITE_URL, self.get_absolute_url())
return url
def _sign(self, q, a, expires):
plain = [getattr(settings, 'SITE_URL', ''), settings.SECRET_KEY,
q, a, expires]
plain = "".join([str(p) for p in plain])
return sha1(plain).hexdigest()
def app_settings(request):
"""
A context processor with all APP settings.
"""
return {
'app': settings.PORTAILVA_APP,
'site_url': settings.SITE_URL
}
def submit(request):
try:
submission, created = parse_submission(request)
except InvalidSubmission as exc:
return HttpResponseBadRequest("Rejecting submission: {}\n".format(exc))
return HttpResponse('{}{}\n'.format(
settings.SITE_URL,
submission.buildinfo.get_absolute_url(),
), status=201 if created else 200)
def send_survey(survey_pk):
survey = Survey.objects.get(pk=survey_pk)
context = Context({'survey': survey,
'questions': survey.report.question_set.active()})
context['SITE_URL'] = settings.SITE_URL
subject = render_to_string('email/survey_subject.txt', context)
text = get_template('email/survey.txt')
html = get_template('email/survey.html')
text_content = text.render(context)
html_content = html.render(context)
survey.user.email_user(subject, text_content, settings.DEFAULT_FROM_EMAIL, html_message=html_content)
def env(event):
settings.SITE_URL = 'http://example.com'
settings.SITE_NETLOC = urlparse(settings.SITE_URL).netloc
def get(self, request, event, **kwargs):
talk = self.get_object().slots.get(schedule=self.request.event.current_schedule)
netloc = urlparse(settings.SITE_URL).netloc
cal = vobject.iCalendar()
cal.add('prodid').value = '-//pretalx//{}//{}'.format(netloc, talk.submission.code)
talk.build_ical(cal)
resp = HttpResponse(cal.serialize(), content_type='text/calendar')
resp['Content-Disposition'] = f'attachment; filename="{request.event.slug}-{talk.submission.code}.ics"'
return resp
def send_password_reset(user, uid, token):
try:
email_subject = _('No Design Slack Clone password reset')
confirm_reset_url = "%s%s" % (settings.SITE_URL,
reverse('password_reset_confirm', kwargs={'uidb64': uid, 'token': token}))
return send_email(user.email, email_subject, 'emails/password_reset.html', {
'user': user,
'confirm_reset_url': confirm_reset_url,
})
except Exception:
logger.exception("Couldn't send password reset to %s (%d)", user.email, user.id)
def _build_url(self):
"""
Generate frontend url to lost key page
:return:
"""
return urlparse.urljoin(
settings.SITE_URL,
'#/lostkey/{}/{}/'.format(self.object.id, self.object.hash)
)
def _build_context(self, **kwargs):
"""
Adds extra variables to template Context
:param kwargs: dict
:return: Context
"""
kwargs.update({
'SITE_URL': settings.SITE_URL,
'url': self._build_url()
})
return super(InvitationMailer, self)._build_context(**kwargs)
def _build_url(self):
"""
Generate frontend url to granted object
:return: str
"""
return urlparse.urljoin(
settings.SITE_URL, '#/invitations/use/{}/{}/'.format(
self.object.id, self.object.invitation_hash
)
)
def _build_url(self):
"""
Generate frontend url to granted object
:return: str
"""
return urlparse.urljoin(settings.SITE_URL, '#/workspaces/w/{}/'.format(
self.object.workspace.slug))
def _build_context(self, **kwargs):
"""
Must return an instance of django.template.context.Context
with the template variables set for each implementation
:return: None
"""
# adding full url to logo
kwargs.update({
'logo_url': "{}vaultier/images/logo-email.png".format(
urljoin(settings.SITE_URL, settings.STATIC_URL))
})
return Context(kwargs)
def make_context(self, ir, template, data):
context = dict(template.form)
context.update({
'url': settings.SITE_URL + ir.get_absolute_url(),
})
context.update(data)
return context
def send_password_reset(user, uid, token):
try:
email_subject = _('{{cookiecutter.project_title}} password reset')
confirm_reset_url = "%s%s" % (settings.SITE_URL,
reverse('password_reset_confirm', kwargs={'uidb64': uid, 'token': token}))
return send_email(user.email, email_subject, 'emails/password_reset.html', {
'user': user,
'confirm_reset_url': confirm_reset_url,
})
except Exception:
logger.exception("Couldn't send password reset to %s (%d)", user.email, user.id)
def post(self, request, *args, **kwargs):
""" Sends the feedback email to admin.
"""
obj = self.get_object()
form = FeedbackForm(request.POST)
if not form.is_valid():
return render(request, 'app/article_detail.html', {
'feedback_form': form,
'object': obj,
'already_voted': False,
'display_form': True,
})
email = form.cleaned_data['email']
email_message = EmailMessage(
subject=_('New feedback from article {0}'.format(obj.name)),
body=render_to_string('feedback_email.html', {
'feedback_message': form.cleaned_data['description'],
'feedback_email': email,
'article': obj,
'base_url': settings.SITE_URL,
}),
to=[settings.SUPPORT_EMAIL],
reply_to=[email],
)
email_message.content_subtype = 'html'
email_message.send()
messages.success(
request,
_('Thank you for sending your feedback!')
)
return redirect(obj)
def send_email(rcpt_email, email_subject, template_name, template_vars, from_email=None, html=True):
logger.info("Sending %s to %s", template_name, rcpt_email)
template_vars.update({
'SITE_URL': settings.SITE_URL,
})
email_content = render_to_string(template_name, template_vars)
# Send HTML-only email. Mandrill will automatically add the text variant.
msg = EmailMessage(email_subject, email_content, from_email, [rcpt_email])
if html:
msg.content_subtype = "html"
msg.send()
def add_site(apps, schema_editor):
Site = apps.get_model('sites', 'Site')
db_alias = schema_editor.connection.alias
domain = urlparse(settings.SITE_URL)
Site.objects.using(db_alias).get_or_create(
id=settings.SITE_ID,
defaults={'domain': domain.netloc, 'name': domain.netloc}
)
def full_url(url):
"""
A Django template filter to prepend the given URL path with the full
site URL.
"""
return urljoin(settings.SITE_URL, url)
def load_breadcrumb(article):
"""
???????
:param article:
:return:
"""
names = article.get_category_tree()
names.append((settings.SITE_NAME, settings.SITE_URL))
names = names[::-1]
return {
'names': names,
'title': article.title
}
def save_submit(request, contest_id):
contest = Contest.objects.get(pk=contest_id)
if request.method == 'POST':
submit_form = SubmitForm(request.POST, request.FILES, contest=contest)
print(str(request.FILES))
if submit_form.is_valid():
webhook_secret = _generate_webhook_secret()
submit = Submit()
submit.submitter = request.user
submit.task = submit_form.cleaned_data['task']
submit.solution = bytes(request.FILES['solution'].read())
submit.webhook_secret = webhook_secret
submit.save()
template_id = submit.task.test_environment.template_name
template = heraclient.Template(template_id)
sandbox = heraclient.Sandbox(submit.id)
webhook_url = 'http://' if settings.DEBUG else 'https://'
host = request.get_host() if settings.DEBUG else settings.SITE_URL
webhook_url += host
webhook_url += reverse('checker_check', args=[submit.pk])
sandbox.create(10,
template,
memory=512,
whole_node=False if settings.DEBUG else True,
async=True,
webhook_url=webhook_url,
webhook_secret=webhook_secret,
priority=None,
priority_growth=None)
return HttpResponseRedirect(reverse('submit_details',
args=[submit.pk]))
return render(request, 'contest/contest_submit.html', {
'submit_form': submit_form,
'contest_id': contest_id,
})
def send_password_reset(user, uid, token):
try:
email_subject = 'onepager password reset'
confirm_reset_url = "%s%s" % (settings.SITE_URL,
reverse('password_reset_confirm', kwargs={'uidb64': uid, 'token': token}))
return send_email(user.email, email_subject, 'emails/password_reset.html', {
'user': user,
'confirm_reset_url': confirm_reset_url,
})
except:
logger.exception("Couldn't send password reset to %s (%d)", user.email, user.id)
def activate_user_email(self):
activation_url = "%s%s" %(settings.SITE_URL, reverse("activation_view", args=[self.activation_key]))
context = {"activation_key": self.activation_key, "activation_url": activation_url, "user": self.user.username}
message = render_to_string("accounts/activation_message.txt", context)
subject = "Activate your email"
self.email_user(subject, message, settings.DEFAULT_FROM_EMAIL)