本文整理匯總了Python中django.conf.settings.ADMINS屬性的典型用法代碼示例。如果您正苦於以下問題:Python settings.ADMINS屬性的具體用法?Python settings.ADMINS怎麽用?Python settings.ADMINS使用的例子?那麽, 這裏精選的屬性代碼示例或許可以為您提供幫助。您也可以進一步了解該屬性所在類django.conf.settings
的用法示例。
在下文中一共展示了settings.ADMINS屬性的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: _set_email_alerts
# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import ADMINS [as 別名]
def _set_email_alerts(self, alert_policy):
"""
Set up email alerts.
We add emails here but never remove them - that must be done manually (or the monitor deleted)
in order to reduce the chance of bugs or misconfigurations accidentally suppressing monitors.
"""
emails_to_monitor = set([email for name, email in settings.ADMINS] + self.additional_monitoring_emails)
if emails_to_monitor:
emails_current = set(
NewRelicEmailNotificationChannel.objects.filter(
new_relic_alert_policies__id=alert_policy.id
).values_list('email', flat=True)
)
emails_to_add = list(emails_to_monitor - emails_current)
if emails_to_add:
self.logger.info(
'Adding email(s) to policy %s: %s', alert_policy.id, ', '.join(emails_to_add)
)
self._add_emails(alert_policy, emails_to_add)
示例2: provision_failed_email
# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import ADMINS [as 別名]
def provision_failed_email(self, reason, log=None):
"""
Send email notifications after a server's provisioning has failed.
This will happen once for each deployment attempt if there are many.
It will send notifications to settings.ADMINS.
"""
attachments = []
if log is not None:
log_str = "\n".join(log)
attachments.append(("provision.log", log_str, "text/plain"))
self._send_email(
self.EmailSubject.PROVISION_FAILED.format(name=self.name, instance_name=self.instance.name),
self.EmailBody.PROVISION_FAILED.format(name=self.name, instance_name=self.instance.name, reason=reason),
self._get_exc_info(default=None),
attachments=attachments,
extra_recipients=[],
)
示例3: users
# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import ADMINS [as 別名]
def users(self, **kargs):
"""
Here we define admin-level users based on settings.ADMINS.
Custom users at other permission levels should be
declared in the UserFixture of the appropriate ConfigEntity. For example,
users with Region permission should be declared in that region's UserFixture, unless
the user needs permission to multiple regions, in which case it should probably go here
:param kwargs:
:return: A list of dicts representing Users
"""
def create_admin_dict(admin_tuple):
first_name, last_name = admin_tuple[0].rsplit(' ', 1)
username = first_name.lower()
return dict(groups=[UserGroupKey.SUPERADMIN],
username=username,
# Default pw is name@uf
# The software should force this to be changed immediately
password='%s@uf' % username,
email=admin_tuple[1])
return map(lambda admin_tuple: create_admin_dict(admin_tuple),
settings.ADMINS)
示例4: create_profile
# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import ADMINS [as 別名]
def create_profile(sender, **kwargs):
user = kwargs["instance"]
if kwargs["created"]:
default_plan = Plan.objects.get(pk=Plan.DEFAULT_PK)
up = Profile(user=user, plan=default_plan)
up.save()
try:
for tg in TalkGroupAccess.objects.filter(default_group=True):
up.talkgroup_access.add(tg)
except OperationalError:
pass
try:
new_user_email = SiteOption.objects.get(name='SEND_ADMIN_EMAIL_ON_NEW_USER')
if new_user_email.value_boolean_or_string() == True:
send_mail(
'New {} User {}'.format(settings.SITE_TITLE, user.username),
'New User {} {} Username {} Email {} just registered'.format(user.first_name, user.last_name, user.username, user.email),
settings.SERVER_EMAIL,
[ mail for name, mail in settings.ADMINS],
fail_silently=False,
)
except (SiteOption.DoesNotExist, OperationalError):
pass
示例5: confirm_email
# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import ADMINS [as 別名]
def confirm_email(self, request, email_address):
"""
Give superuser privileges automagically if the email address of a
user confirming their email is listed in ``settings.ADMINS``.
"""
super().confirm_email(request, email_address)
if email_address.email in ADMIN_EMAIL_ADDRESSES:
user = email_address.user
user.is_staff = user.is_superuser = True
user.save()
messages.add_message(
request, messages.INFO,
_('Welcome Admin! You have been given superuser privileges. '
'Use them with caution.')
)
示例6: settings_check
# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import ADMINS [as 別名]
def settings_check(app_configs, **kwargs):
from django.conf import settings
errors = []
if not settings.ADMINS:
errors.append(Warning(
"""
The system admins are not set in the project settings
""",
obj=settings,
hint="""
In order to receive notifications when new videos are
created, define system admins in your settings, like:
ADMINS = (
("Admin", "administrator@example.com"),
)
""",
id="viral_videos.W001"))
return errors
示例7: test_admin_settings
# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import ADMINS [as 別名]
def test_admin_settings(self):
"""Verify that we configure email with environment variable"""
with mock.patch.dict('os.environ', {
**REQUIRED_SETTINGS,
'MICROMASTERS_ADMIN_EMAIL': ''
}, clear=True):
settings_vars = self.reload_settings()
self.assertFalse(settings_vars.get('ADMINS', False))
test_admin_email = 'cuddle_bunnies@example.com'
with mock.patch.dict('os.environ', {
**REQUIRED_SETTINGS,
'MICROMASTERS_ADMIN_EMAIL': test_admin_email,
}, clear=True):
settings_vars = self.reload_settings()
self.assertEqual(
(('Admins', test_admin_email),),
settings_vars['ADMINS']
)
# Manually set ADMIN to our test setting and verify e-mail
# goes where we expect
settings.ADMINS = (('Admins', test_admin_email),)
mail.mail_admins('Test', 'message')
self.assertIn(test_admin_email, mail.outbox[0].to)
示例8: settings_check
# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import ADMINS [as 別名]
def settings_check(app_configs, **kwargs):
from django.conf import settings
errors = []
if not settings.ADMINS:
errors.append(
Warning(
dedent("""
The system admins are not set in the project settings
"""),
obj=settings,
hint=dedent("""
In order to receive notifications when new videos are
created, define system admins in your settings, like:
ADMINS = (
("Admin", "administrator@example.com"),
)
"""),
id="viral_videos.W001",
)
)
return errors
示例9: report
# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import ADMINS [as 別名]
def report(request):
crashed = True
if request.method == 'POST':
form = ErrorForm(request.POST)
if form.is_valid():
ref = 'Error %s' % from_time()
recipient = settings.ADMINS[0][1]
send_mail(ref, form.cleaned_data['description'], request.user.email, [recipient])
crashed = False
else:
initial = _('Browser: %s') % request.META['HTTP_USER_AGENT']
form = ErrorForm(initial={'description': initial})
return render(request, 'error.html', locals())
示例10: mail_admins
# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import ADMINS [as 別名]
def mail_admins(subject, message, fail_silently=False, connection=None,
html_message=None):
"""Sends a message to the admins, as defined by the ADMINS setting."""
if not settings.ADMINS:
return
mail = EmailMultiAlternatives('%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject),
message, settings.SERVER_EMAIL, [a[1] for a in settings.ADMINS],
connection=connection)
if html_message:
mail.attach_alternative(html_message, 'text/html')
mail.send(fail_silently=fail_silently)
示例11: check_undelivered
# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import ADMINS [as 別名]
def check_undelivered(to: Optional[str] = None) -> int:
"""Sends a notification email if any undelivered dispatches.
Returns undelivered (failed) dispatches count.
:param to: Recipient address. If not set Django ADMINS setting is used.
"""
failed_count = Dispatch.objects.filter(dispatch_status=Dispatch.DISPATCH_STATUS_FAILED).count()
if failed_count:
from sitemessage.shortcuts import schedule_email
from sitemessage.messages.email import EmailTextMessage
if to is None:
admins = settings.ADMINS
if admins:
to = list(dict(admins).values())
if to:
priority = 999
register_message_types(EmailTextMessage)
schedule_email(
_('You have %(count)s undelivered dispatch(es) at %(url)s') % {
'count': failed_count,
'url': get_site_url(),
},
subject=_('[SITEMESSAGE] Undelivered dispatches'),
to=to, priority=priority)
send_scheduled_messages(priority=priority)
return failed_count
示例12: get
# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import ADMINS [as 別名]
def get(self, request, *args, **kwargs):
if request.user.is_authenticated:
# Only anonymous (non-authenticated) users are expected to access this page.
return HttpResponseRedirect(self.get_authenticated_redirect_url())
request_id = request.session.pop('restore_request_id', None)
if request_id is None or not isinstance(request_id[1], float):
# When the restore request ID is missing or invalid, just show the login page.
return HttpResponseRedirect(reverse_lazy('login'))
if datetime.now() - datetime.fromtimestamp(request_id[1]) > timedelta(hours=1):
# When the restore request ID is expired (older than 1 hour), redirect to the login page.
# This is to prevent abuse, when the user leaves their browser or device open and
# a different person attempts to (mis)use the restoration request functionality...
messages.warning(self.request, _("Something misfunctioned. Please log in again and retry."))
return HttpResponseRedirect(reverse_lazy('login'))
# Otherwise, send mail to admins.
send_mail(
'{prefix}{subject}'.format(
prefix=settings.EMAIL_SUBJECT_PREFIX,
subject=gettext(
# xgettext:python-brace-format
"Note to admin: User requests to reactivate their account; ref: {}."
).format(request_id[0])),
"--",
None,
['{} <{}>'.format(nick, addr) for nick, addr in settings.ADMINS],
fail_silently=False)
context = self.get_context_data(**kwargs)
return self.render_to_response(context)
示例13: _mail_admins_with_attachment
# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import ADMINS [as 別名]
def _mail_admins_with_attachment(
subject,
message,
fail_silently=True,
connection=None,
html_message=None,
attachments=None,
extra_recipients: Optional[List[str]] = None,
):
"""
Mimics mail_admins, but allows attaching files to the message
"""
if not settings.ADMINS and not extra_recipients:
return
recipients = [a[1] for a in settings.ADMINS] + extra_recipients
mail = EmailMultiAlternatives(
"%s%s" % (settings.EMAIL_SUBJECT_PREFIX, subject),
message, settings.SERVER_EMAIL, recipients,
connection=connection
)
if html_message:
mail.attach_alternative(html_message, "text/html")
if attachments:
for attachment_name, attachment_content, attachment_mime in attachments:
mail.attach(attachment_name, attachment_content, attachment_mime)
mail.send(fail_silently=fail_silently)
# Functions #####################################################################
示例14: test_provision_failed_email
# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import ADMINS [as 別名]
def test_provision_failed_email(self, mock_consul):
"""
Tests that provision_failed sends email when called from normal program flow
"""
additional_monitoring_emails = ['additionalmonitoring@localhost']
failure_emails = ['provisionfailed@localhost']
appserver = make_test_appserver()
appserver.instance.additional_monitoring_emails = additional_monitoring_emails
appserver.instance.provisioning_failure_notification_emails = failure_emails
reason = "something went wrong"
log_lines = ["log line1", "log_line2"]
appserver.provision_failed_email(reason, log_lines)
expected_subject = OpenEdXAppServer.EmailSubject.PROVISION_FAILED.format(
name=appserver.name, instance_name=appserver.instance.name,
)
# failure_emails isn't included here because they get a different type of email (an urgent one)
expected_recipients = [admin_tuple[1] for admin_tuple in settings.ADMINS]
self.assertEqual(len(django_mail.outbox), 1)
mail = django_mail.outbox[0]
self.assertIn(expected_subject, mail.subject)
self.assertIn(appserver.name, mail.body)
self.assertIn(appserver.instance.name, mail.body)
self.assertIn(reason, mail.body)
self.assertEqual(mail.from_email, settings.SERVER_EMAIL)
self.assertEqual(mail.to, expected_recipients)
self.assertEqual(len(mail.attachments), 1)
self.assertEqual(mail.attachments[0], ("provision.log", "\n".join(log_lines), "text/plain"))
示例15: test_provision_failed_exception_email
# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import ADMINS [as 別名]
def test_provision_failed_exception_email(self, mock_consul):
"""
Tests that provision_failed sends email when called from exception handler
"""
appserver = make_test_appserver()
reason = "something went wrong"
log_lines = ["log line1", "log_line2"]
exception_message = "Something Bad happened Unexpectedly"
exception = Exception(exception_message)
try:
raise exception
except Exception: # pylint: disable=broad-except
appserver.provision_failed_email(reason, log_lines)
expected_subject = OpenEdXAppServer.EmailSubject.PROVISION_FAILED.format(
name=appserver.name, instance_name=appserver.instance.name,
)
expected_recipients = [admin_tuple[1] for admin_tuple in settings.ADMINS]
self.assertEqual(len(django_mail.outbox), 1)
mail = django_mail.outbox[0]
self.assertIn(expected_subject, mail.subject)
self.assertIn(appserver.name, mail.body)
self.assertIn(appserver.instance.name, mail.body)
self.assertIn(reason, mail.body)
self.assertEqual(mail.from_email, settings.SERVER_EMAIL)
self.assertEqual(mail.to, expected_recipients)
self.assertEqual(len(mail.attachments), 2)
self.assertEqual(mail.attachments[0], ("provision.log", "\n".join(log_lines), "text/plain"))
name, content, mime_type = mail.attachments[1]
self.assertEqual(name, "debug.html")
self.assertIn(exception_message, content)
self.assertEqual(mime_type, "text/html")