def report_problem(request): ret = {} if request.method == 'POST': email = request.POST.get("email") description = request.POST.get("description") please_reply = request.POST.get("please_reply", False) feelings = request.POST.get("feelings") if hasattr(request, "browser") and request.browser: # Don't use browser ID user provided - it either matches request.browser or is completely bogus. bid_public = request.browser.bid_public else: bid_public = "-" ret["email"] = email ret["description"] = description ret["please_reply"] = please_reply dont_send = False try: validate_email(email) except: if please_reply: dont_send = True messages.warning(request, "If you want a reply to your report, please enter proper email address") if not dont_send: ret["report_sent"] = True contents = "%s: feelings %s with %s. [%s] reply.\n\n%s" % (email, feelings, bid_public, please_reply, description) mail_admins("Bug report from login service", contents) custom_log(request, "Received feedback from user: %s" % contents, level="warn") return render_to_response("login_frontend/report_problem.html", ret, context_instance=RequestContext(request))
def contactview(request): name = request.POST.get('name', '') subject = request.POST.get('topic', '') message = request.POST.get('message', '') from_email = request.POST.get('email', '') if name and message and from_email: t = get_template('contact_message.txt') c = Context({ 'name': name, 'from_email': from_email, 'message': message }) email_message = t.render(c) try: mail_admins(subject, email_message) except BadHeaderError: return HttpResponse('Invalid header found.') return HttpResponseRedirect('/contact/thankyou/') else: return render_to_response('contact/contacts.html', {'form': ContactForm()}, RequestContext(request)) return render_to_response('contact/contacts.html', {'form': ContactForm()}, RequestContext(request))
def candidate_change_request_form(request): if request.method == 'GET': return render_to_response('political/candidate_change_request_ok.html', context_instance=RequestContext(request)) args = request.POST try: cand_id = int(args['candidate-id']) request_str = args['request'] except: return HttpResponseRedirect(reverse('political.views.candidate_change_request')) try: cand = Candidate.objects.get(pk=cand_id) except Candidate.DoesNotExist: return HttpResponseRedirect(reverse('political.views.candidate_change_request')) subject = "Change request: %s" % unicode(cand) message = """ Info ---- """ message += "Candidate: %s\n" % unicode(cand) message += "Request:\n%s" % unicode(request_str) mail_admins(subject, message, fail_silently=False) return HttpResponseRedirect(reverse('political.views.candidate_change_request_form'))
def wrap(request, *a, **kw): response = None try: response = func(request, *a, **kw) if isinstance(response, dict): response = dict(response) if 'result' not in response: response['result'] = 'ok' except KeyboardInterrupt: # Allow keyboard interrupts through for debugging. raise except Http404: raise Http404 except Exception, e: # Mail the admins with the error exc_info = sys.exc_info() subject = 'JSON view error: %s' % request.path try: request_repr = repr(request) except: request_repr = 'Request repr() unavailable' import traceback message = 'Traceback:\n%s\n\nRequest:\n%s' % ( '\n'.join(traceback.format_exception(*exc_info)), request_repr, ) # print message mail_admins(subject, message, fail_silently=True) response = {'result': 'error', 'text': unicode(e)}
def form_valid(self, form): ''' Set the user that submitted the exercise If admin, set appropriate status ''' form.instance.language = load_language() if self.request.user.has_perm('exercises.add_exercise'): form.instance.status = Exercise.EXERCISE_STATUS_ADMIN if not form.instance.license_author: form.instance.license_author = 'wger.de' else: if not form.instance.license_author: form.instance.license_author = self.request.user.username subject = _('New user submitted exercise') message = _(u'''The user {0} submitted a new exercise "{1}".'''.format( self.request.user.username, form.instance.name)) mail.mail_admins(subject, message, fail_silently=True) return super(ExerciseAddView, self).form_valid(form)
def about(request): o = {} if request.method == 'POST': bad_answers = request.session.setdefault('bad_answers', 0) if bad_answers > 3: return HttpResponseForbidden( 'Too many failed attempts. Try again later.') o['form'] = main_forms.FeedbackForm(request.POST) if o['form'].is_valid(): test_answer = request.POST.get('testanswer') or '999' if int(test_answer, 10) != request.session['test_answer']: request.session['bad_answers'] = bad_answers + 1 o['bad_answer'] = True return render_to_response( 'about.html', o, context_instance=RequestContext(request)) request.session.pop('bad_answers') choice = o['form'].cleaned_data['purpose'] subj = '(%s) %s' % ( dict(o['form'].fields['purpose'].choices)[choice], o['form'].cleaned_data['name']) msg = 'reply to: %(email)s\n\n%(message)s' % o['form'].cleaned_data mail_admins(subj, msg, fail_silently=True) messages.add_message( request, messages.SUCCESS, 'Thank you. Your feedback has been submitted.') return HttpResponseRedirect('/about/') else: o['form'] = main_forms.FeedbackForm() return render_to_response( 'about.html', o, context_instance=RequestContext(request))
def handle(self, *args, **options): module = getattr(settings, "EXCHANGE_RATE_MODULE", "ecb") if module == "fixer": client = FixerExchangeRateClient() else: client = EcbExchangeRateClient() exchange_rates = client.update_exchange_rates() for exchange_rate in exchange_rates: self.stdout.write('Successfully updated "%s"' % exchange_rate) subject = "Updated {num} currencies".format(num=len(exchange_rates)) message = """Howdy, Here are the latest exchange rates: {rates} See you again soon! -- JellyRoll """.format( rates="\n".join("* {rate}".format(rate=rate) for rate in exchange_rates) ) mail_admins(subject, message)
def emit(self, record): try: request = record.request subject = "%s (%s IP): %s" % ( record.levelname, ("internal" if request.META.get("REMOTE_ADDR") in settings.INTERNAL_IPS else "EXTERNAL"), record.getMessage(), ) filter = get_exception_reporter_filter(request) request_repr = filter.get_request_repr(request) except Exception: subject = "%s: %s" % (record.levelname, record.getMessage()) request = None request_repr = "Request repr() unavailable." subject = self.format_subject(subject) if record.exc_info: exc_info = record.exc_info stack_trace = "\n".join(traceback.format_exception(*record.exc_info)) else: exc_info = (None, record.getMessage(), None) stack_trace = "No stack trace available" message = "%s\n\n%s" % (stack_trace, request_repr) reporter = ExceptionReporter(request, is_email=True, *exc_info) html_message = reporter.get_traceback_html() if self.include_html else None mail.mail_admins(subject, message, fail_silently=True, html_message=html_message, connection=self.connection())
def test_empty_admins(self): """ Test that mail_admins/mail_managers doesn't connect to the mail server if there are no recipients (#9383) """ old_admins = settings.ADMINS old_managers = settings.MANAGERS settings.ADMINS = settings.MANAGERS = [('nobody','*****@*****.**')] mail.outbox = [] mail_admins('hi', 'there') self.assertEqual(len(mail.outbox), 1) mail.outbox = [] mail_managers('hi', 'there') self.assertEqual(len(mail.outbox), 1) settings.ADMINS = settings.MANAGERS = [] mail.outbox = [] mail_admins('hi', 'there') self.assertEqual(len(mail.outbox), 0) mail.outbox = [] mail_managers('hi', 'there') self.assertEqual(len(mail.outbox), 0) settings.ADMINS = old_admins settings.MANAGERS = old_managers
def profile_is_premium(request): # Check tries code = 0 retries = int(request.GET['retries']) profile = Profile.objects.get(user=request.user) subs = UserSubscription.objects.filter(user=request.user) total_subs = subs.count() activated_subs = subs.filter(active=True).count() if retries >= 30: code = -1 if not request.user.profile.is_premium: subject = "高级帐户激活失败:%s (%s/%s)" % (request.user, activated_subs, total_subs) message = """User: %s (%s) -- Email: %s""" % (request.user.username, request.user.pk, request.user.email) mail_admins(subject, message, fail_silently=True) request.user.profile.is_premium = True request.user.profile.save() return { 'is_premium': profile.is_premium, 'code': code, 'activated_subs': activated_subs, 'total_subs': total_subs, }
def emit(self, record): try: request = record.request subject = '%s (%s IP): %s' % ( record.levelname, (request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS and 'internal' or 'EXTERNAL'), record.msg ) filter = get_exception_reporter_filter(request) request_repr = filter.get_request_repr(request) except: subject = '%s: %s' % ( record.levelname, record.getMessage() ) request = None request_repr = "Request repr() unavailable." if record.exc_info: exc_info = record.exc_info stack_trace = '\n'.join(traceback.format_exception(*record.exc_info)) else: exc_info = (None, record.getMessage(), None) stack_trace = 'No stack trace available' message = "%s\n\n%s" % (stack_trace, request_repr) reporter = ExceptionReporter(request, is_email=True, *exc_info) html_message = self.include_html and reporter.get_traceback_html() or None mail.mail_admins(subject, message, fail_silently=True, html_message=html_message)
def _2(*args, **kw): class Dispatch(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.result = None self.error = None self.setDaemon(True) self.start() def run(self): try: self.result = function(*args, **kw) except: self.error = sys.exc_info() c = Dispatch() c.join(timeout) if c.isAlive(): raise TimeoutError, 'took too long' if c.error: tb = ''.join(traceback.format_exception(c.error[0], c.error[1], c.error[2])) logging.debug(tb) mail_admins('Error in timeout: %s' % c.error[0], tb) raise c.error[0], c.error[1], c.error[2] return c.result
def topic_create(request): if request.method == 'POST': topicForm = TopicForm(request.POST, prefix="topic") messageForm = MessageForm(request.POST, prefix="message") if topicForm.is_valid() and messageForm.is_valid(): topic = topicForm.save(commit=False) topic.author = request.user topic.creation_date = datetime.datetime.now() topic.save() message = messageForm.save(commit=False) message.author = request.user message.creation_date = datetime.datetime.now() message.topic = topic message.save() domain = Site.objects.get_current().domain mail_subject = _('A new topic has been posted') mail_message = _('%(topic)s : %(topic_url)s') % {'topic': topic.title, 'topic_url': 'https://%s%s' % (domain, reverse('topic_detail', kwargs={'id': topic.id}))} mail_admins(mail_subject, mail_message, fail_silently=(not settings.DEBUG)) messages.success(request, _('The topic has been saved successfully')) return redirect(reverse('topic_detail', kwargs={'id': topic.id})) else: messages.error(request, _('Data provided are invalid')) else: topicForm = TopicForm(prefix="topic") messageForm = MessageForm(prefix="message") return render_to_response('topic/create.html', {'active': 'help', 'title': _('New topic'), 'topicForm': topicForm, 'messageForm': messageForm}, context_instance=RequestContext(request))
def _rebuild_kb_chunk(data, **kwargs): """Re-render a chunk of documents.""" log.info('Rebuilding %s documents.' % len(data)) pin_this_thread() # Stick to master. messages = [] for pk in data: message = None try: document = Document.objects.get(pk=pk) document.html = document.current_revision.content_cleaned document.save() except Document.DoesNotExist: message = 'Missing document: %d' % pk except ValidationError as e: message = 'ValidationError for %d: %s' % (pk, e.messages[0]) except SlugCollision: message = 'SlugCollision: %d' % pk if message: log.debug(message) messages.append(message) if messages: subject = ('[%s] Exceptions raised in _rebuild_kb_chunk()' % settings.PLATFORM_NAME) mail_admins(subject=subject, message='\n'.join(messages)) unpin_this_thread() # Not all tasks need to do use the master.
def test_connection_arg(self): """Test connection argument to send_mail(), et. al.""" mail.outbox = [] # Send using non-default connection connection = mail.get_connection('mail.custombackend.EmailBackend') send_mail('Subject', 'Content', '*****@*****.**', ['*****@*****.**'], connection=connection) self.assertEqual(mail.outbox, []) self.assertEqual(len(connection.test_outbox), 1) self.assertEqual(connection.test_outbox[0].subject, 'Subject') connection = mail.get_connection('mail.custombackend.EmailBackend') send_mass_mail([ ('Subject1', 'Content1', '*****@*****.**', ['*****@*****.**']), ('Subject2', 'Content2', '*****@*****.**', ['*****@*****.**']), ], connection=connection) self.assertEqual(mail.outbox, []) self.assertEqual(len(connection.test_outbox), 2) self.assertEqual(connection.test_outbox[0].subject, 'Subject1') self.assertEqual(connection.test_outbox[1].subject, 'Subject2') connection = mail.get_connection('mail.custombackend.EmailBackend') mail_admins('Admin message', 'Content', connection=connection) self.assertEqual(mail.outbox, []) self.assertEqual(len(connection.test_outbox), 1) self.assertEqual(connection.test_outbox[0].subject, '[Django] Admin message') connection = mail.get_connection('mail.custombackend.EmailBackend') mail_managers('Manager message', 'Content', connection=connection) self.assertEqual(mail.outbox, []) self.assertEqual(len(connection.test_outbox), 1) self.assertEqual(connection.test_outbox[0].subject, '[Django] Manager message')
def send_new_premium_email(self, force=False): subs = UserSubscription.objects.filter(user=self.user) message = """Woohoo! User: %(user)s Feeds: %(feeds)s Sincerely, NewsBlur""" % {'user': self.user.username, 'feeds': subs.count()} mail_admins('New premium account', message, fail_silently=True) if not self.user.email or not self.send_emails: return sent_email, created = MSentEmail.objects.get_or_create(receiver_user_id=self.user.pk, email_type='new_premium') if not created and not force: return user = self.user text = render_to_string('mail/email_new_premium.txt', locals()) html = render_to_string('mail/email_new_premium.xhtml', locals()) subject = "Thanks for going premium on NewsBlur!" msg = EmailMultiAlternatives(subject, text, from_email='NewsBlur <%s>' % settings.HELLO_EMAIL, to=['%s <%s>' % (user, user.email)]) msg.attach_alternative(html, "text/html") msg.send(fail_silently=True) logging.user(self.user, "~BB~FM~SBSending email for new premium: %s" % self.user.email)
def handle(self, **options): from karaage.common import log from karaage.people.models import Person from django.core.mail import mail_admins import datetime today = datetime.date.today() verbose = int(options.get('verbosity')) for p in Person.objects.filter(expires__lte=today): try: if not p.is_locked(): p.lock() p.expires = None p.save() message = "%s's account has expired and their account " \ "has been locked. %s does not know this" % (p, p) mail_admins( 'Locked expired user %s' % p, message, fail_silently=False) log.change(p, 'Account auto expired') if verbose >= 1: print("Locked account for %s - %s" % (p.username, p)) except: print("Failed to lock %s" % p)
def contact2(request): t = 'contact2.html' if request.method == 'POST': form = Contact2Form(request.POST) if form.is_valid(): nameField = form.cleaned_data['nameField'] firstNameField = form.cleaned_data['firstNameField'] descField = form.cleaned_data['descField'] emailField = form.cleaned_data['emailField'] #send_mail('Feedback from your site, topic: %s' % topic,message, sender,['*****@*****.**']) #mail_managers(topic + " from " + sender, message, fail_silently=False, connection=None, html_message=None) if nameField and firstNameField and descField: #mail_admins(topic + " from " + sender, message, fail_silently=False, connection=None, html_message=None) mail_admins("from " + prenom + " " + nom, "nom" + nom + "prenom = " + prenom + "description = " + description + " phone=" + telephone + "email = " + email , fail_silently=False, connection=None, html_message=None) form.save() return render_to_response('thanks.html') else: return HttpResponse('Make sure all fields are entered and valid.') else: return render(request, t, {'form': form}) else: form = Contact2Form() return render(request, t, {'form': form })
def form_valid(self, form): response = super(MessageCreateView, self).form_valid(form) site_url = settings.SITE_URL url = reverse('admin:writing_message_change', args=(self.object.id, )) mail_admins('New message on Wizzarding', 'Check the admin page for details', html_message=settings.NEW_MESSAGE_TEMPLATE.format(site_url, url), fail_silently=True) return response
def contact(request): t = 'contact2.html' if request.method == 'POST': form = Contact2Form(request.POST) if form.is_valid(): nom = form.cleaned_data['nameField'] prenom = form.cleaned_data['firstNameField'] email = form.cleaned_data['emailField'] telephone = form.cleaned_data['phoneField'] description = form.cleaned_data['descField'] #send_mail('Feedback from your site, topic: %s' % topic,message, sender,['*****@*****.**']) #mail_managers(topic + " from " + sender, message, fail_silently=False, connection=None, html_message=None) if nom and prenom and email: try: mail_admins("from " + prenom + " " + nom, "nom" + nom + "\nprenom = " + prenom + "\ndescription = " + description + "\nphone=" + telephone + "\nemail = " + email , fail_silently=False, connection=None, html_message=None) form.save() except BadHeaderError: return HttpResponse('Invalid header found.') return render_to_response('thanks.html' , {'prenom': prenom} ) else: return render(request, t, {'form': form }) else: return render(request, t, {'form': form }) else: form = ContactForm() return render(request, t, {'form': form })
def new_order(request): if request.method == "POST": form = OrderForm(request.POST) if form.is_valid(): data = form.cleaned_data meal = data['meal'] person = data['person'] email = data['email'] byn = data['byn'] byr = data['byr'] comment = data['comment'] if byn is None and byr is None: return HttpResponse("мы работаем только по предоплате") d_now = datetime.datetime.now().time() d1 = datetime.time(hour=13) d2 = datetime.time(hour=15) if d1 <= d_now <= d2: mail_admins(u'заказ', u'получен новый заказ') Order.objects.create(meal=meal, person=person, email=email, byn=byn, byr=byr, comment=comment) return redirect(go_main) data = form.errors return HttpResponse("{0}".format(data)) else: d_now = datetime.datetime.now().time() d1 = datetime.time(hour=15) if d1 < d_now: context = {'my_form': OrderForm(), 'state':'off'} else: context = {'my_form':OrderForm()} return render(request, 'new_order_page.html', context)
def contactFeed(request): if request.method == 'POST': form = ContactFeedForm(request.POST) if form.is_valid(): topic = form.cleaned_data['topic'] message = form.cleaned_data['message'] sender = form.cleaned_data['sender'] #send_mail('Feedback from your site, topic: %s' % topic,message, sender,['*****@*****.**']) #mail_managers(topic + " from " + sender, message, fail_silently=False, connection=None, html_message=None) if topic and message and sender: try: mail_admins(topic + " from " + sender, message, fail_silently=False, connection=None, html_message=None) except BadHeaderError: return HttpResponse('Invalid header found.') return render_to_response('thanks.html') else: # In reality we'd use a form class # to get proper validation errors. return HttpResponse('Make sure all fields are entered and valid.') else: return render(request, 'contactfeedform.html', {'form': form}) else: form = ContactFeedForm() return render(request, "contactfeedform.html", {'form': form })
def post(self,request,format=None): postData=request.data postData['is_active']=False postData['profile']['validatedcode']= self.get_validationcode() serializer=UserSerializer(data=postData) if serializer.is_valid() : serializer.save() ## send email pending_message="Hello %s,\n\nThank you for your registration.\n Your account is pendinng. We will review and activate in a due course and send you a notification then.\nRegards,\nSite admin\n\n" % (serializer.data['first_name'],) send_mail("Pending account",pending_message,"*****@*****.**",[serializer.data['email']], fail_silently=True) url="http://%s/accounts/validate" % (request.get_host,) pending_message="Hello %s,\n\nA new account as been added. Please reivew and activate it by clicking on the below url:\n%s\n\nSite admin\n\n" % ('Admin',url,) mail_admins("Pending account",pending_message, fail_silently=True) return Response(serializer.data) error =ResponseRes.get_serializer_error(serializer.errors) return Response({ 'status': 'Failed', 'message': 'This account could not be created. Reason:' + error})
def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): cd = form.cleaned_data if form.check_md5(cd): payment = self.get_payment(cd) if payment: try: self.validate(cd, payment) except YandexValidationError as exc: params = exc.params else: params = self.get_response_params(payment, cd) self.mark_payment(payment, cd) payment.send_signals() else: params = {'code': '1000'} else: params = {'code': '1'} else: params = {'code': '200'} self.logging(request, params) content = self.get_xml(params) if ( getattr(settings, 'YANDEX_MONEY_MAIL_ADMINS_ON_PAYMENT_ERROR', True) and params.get('code') != '0' ): mail_admins('yandexmoney_django error', 'post data: {post_data}\n\nresponse:{response}'.format( post_data=request.POST, response=content, )) return HttpResponse(content, content_type='application/xml')
def send_error_report(request): """ View used by users to send an error report when a 404 or a 500 error page is displayed. This view receives 3 parameters via POST request and returns a json with a success or error feedback. POST params: message: a message written by the user describing what occurred. info: information about the error collected automatically. url: in which page the error occurred. """ user = request.user user_message = request.POST.get('message', '') info = request.POST.get('info', '') url = request.POST.get('url', '') message = _(""" Url: {0} Reporter: {1} (id: {2}, email: {3}) Info: {4} Message: {5} """).format(url, user, user.id, user.email, info, user_message) try: mail_admins(_('Error report'), message, fail_silently=False) status = 'sent' success = 'true' except SMTPException: status = 'failed' success = 'false' finally: return {'status': status, 'success': success}
def handle_uncaught_exception(self, request, resolver, exc_info): """ Processing for any otherwise uncaught exceptions (those that will generate HTTP 500 responses). Can be overridden by subclasses who want customised 500 handling. Be *very* careful when overriding this because the error could be caused by anything, so assuming something like the database is always available would be an error. """ from django.conf import settings from django.core.mail import mail_admins if settings.DEBUG_PROPAGATE_EXCEPTIONS: raise if settings.DEBUG: from django.views import debug return debug.technical_500_response(request, *exc_info) # When DEBUG is False, send an error message to the admins. subject = "Error (%s IP): %s" % ( (request.META.get("REMOTE_ADDR") in settings.INTERNAL_IPS and "internal" or "EXTERNAL"), request.path, ) try: request_repr = repr(request) except: request_repr = "Request repr() unavailable" message = "%s\n\n%s" % (self._get_traceback(exc_info), request_repr) mail_admins(subject, message, fail_silently=True) # Return an HttpResponse that displays a friendly error message. callback, param_dict = resolver.resolve500() return callback(request, **param_dict)
def handle_noargs(self, *args, **options): database = [] print "Init done" for query_info in conf.IPGEOBASE_COUNTRY_INFO: content = self.get_contents(query_info) for line in content.decode(query_info['coding']).split("\n"): line = line.strip() if not line: continue row = self.get_row(line.split("\t"), query_info) row = self.preprocess_row(row) database.append( (row['start_ip'], row['end_ip'], row['city'], row['region'], row['country'], row['ip_block']), ) try: cursor = connection.cursor() cursor.execute("TRUNCATE TABLE django_ipgeobase_ipgeobase") print cursor.executemany(""" INSERT INTO django_ipgeobase_ipgeobase (start_ip, end_ip, city_id, region_id, country_id, ip_block) VALUES (%s, %s, %s, %s, %s, %s ) """, database) transaction.commit() except Exception, e: transaction.rollback() message = "The data not updated:", e if send_message: mail_admins(subject=ERROR_SUBJECT, message=message) raise CommandError(message)
def notify(access_attempt, **kwargs): site = Site.objects.get_current() ip_address = access_attempt.ip_address fqdn = _resolve_ip_address_to_fqdn(ip_address) if access_attempt.failures == 0: login_success_msg = 'successful' login_success = True else: login_success_msg = 'failed' login_success = False context = dict( current_time=now(), attempt_time=access_attempt.attempt_time, failures=access_attempt.failures, fqdn=fqdn, site_domain=site.domain, site=site, ip_address=ip_address, login_success=login_success, login_success_msg=login_success_msg, user_agent=access_attempt.user_agent, username=access_attempt.username) subject = 'Security: %(site_domain)s: %(login_success_msg)s login attempt by %(ip_address)s (%(fqdn)s)' % context message = _render_email_message(context) mail_admins(subject, message, fail_silently=False)
def handle(self, *args, **options): result = 0 subject = "Deployment Test Message" message = "Deployment Test Message Body. This was sent using" \ " django_deployment to test the email configuration of a" \ " deployed project." sent_msg = False if options["verbosity"] > "1": print "Using %s" % settings.EMAIL_BACKEND if options['admins']: mail_admins(subject, message, fail_silently=False) sent_msg = True if options['managers']: mail_managers(subject, message, fail_silently=False) sent_msg = True if args: send_mail(subject, message, options["from"], args, fail_silently=False) elif not sent_msg: raise CommandError("No recipient addresses were specified on the" " command line") return result
def authenticate(self, email=None, password=None, *args, **kwargs): if email is None: if 'username' not in kwargs or kwargs['username'] is None: return None clean_email = normalise_email(kwargs['username']) else: clean_email = normalise_email(email) # Check if we're dealing with an email address if '@' not in clean_email: return None # Since Django doesn't enforce emails to be unique, we look for all # matching users and try to authenticate them all. If we get more than # one success, then we mail admins as this is a problem. authenticated_users = [] matching_users = User.objects.filter(email=clean_email) for user in matching_users: if user.check_password(password): authenticated_users.append(user) if len(authenticated_users) == 1: # Happy path return authenticated_users[0] elif len(authenticated_users) > 1: # This is the problem scenario where we have multiple users with # the same email address AND password. We can't safely authentiate # either. This situation requires intervention by an admin and so # we mail them to let them know! mail_admins( "There are multiple users with email address: %s" % clean_email, ("There are %s users with email %s and the same password " "which means none of them are able to authenticate") % (len(authenticated_users), clean_email)) return None
class Command(BaseCommand): help = 'A simple cron job to verify if the celery daemon is running and tasks can round-trip sucessfully.' def add_arguments(self, parser): # Named (optional) arguments parser.add_argument('--email-admins', action='store_true', dest='email_admins', default=False, help='Email the admins on error..') parser.add_argument( '--timeout', type='int', action='store', dest='timeout', default=600, help= 'Specify how long to wait before considering the task failed (default is 600 seconds)' ) def handle(self, *args, **options): ''' Check to see if we can run a celery task and get a suitable result back. ''' if not settings.NMTK_SERVER: raise CommandError('The NMTK Server is not currently enabled') try: result = tasks.verify_celery.delay() task_output = result.get(timeout=options['timeout']) except Exception, e: task_output = False if task_output: exit(0) elif options['email_admins']: url = 'http{0}://{1}{2}'.format('s' if settings.SSL else '', settings.SITE_DOMAIN, settings.PORT) context = {'timeout': options['timeout'], 'url': url} subject = render_to_string('NMTK_server/verify_celery_subject.txt', context).strip().replace('\n', ' ') message = render_to_string('NMTK_server/verify_celery_message.txt', context) logger.debug( 'Celery job validation failed, sending notification email to admins' ) mail_admins(subject, message) exit(1) else: raise CommandError( 'The celery task has not returned after {0} seconds!'.format( options['timeout']))
def emit(self, record): import traceback from django.conf import settings from django.views.debug import ExceptionReporter try: if sys.version_info < (2, 5): # A nasty workaround required because Python 2.4's logging # module doesn't support passing in extra context. # For this handler, the only extra data we need is the # request, and that's in the top stack frame. request = record.exc_info[2].tb_frame.f_locals['request'] else: request = record.request subject = '%s (%s IP): %s' % (record.levelname, ( request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS and 'internal' or 'EXTERNAL'), record.msg) request_repr = repr(request) except: subject = 'Error: Unknown URL' request = None request_repr = "Request repr() unavailable" if record.exc_info: exc_info = record.exc_info stack_trace = '\n'.join( traceback.format_exception(*record.exc_info)) else: exc_info = () stack_trace = 'No stack trace available' message = "%s\n\n%s" % (stack_trace, request_repr) reporter = ExceptionReporter(request, is_email=True, *exc_info) html_message = reporter.get_traceback_html() mail.mail_admins(subject, message, fail_silently=True, html_message=html_message)
def notify_admin(request): """ Url to notify the administrators regarding the user dialer settings configuration via mail """ # Get all the admin users - admin superuser all_admin_user = User.objects.filter(is_superuser=True) for user in all_admin_user: recipient = user if not 'has_notified' in request.session: frontend_send_notification( request, NOTIFICATION_NAME.dialer_setting_configuration, recipient) # Send mail to ADMINS subject = _('dialer setting configuration').title() message = _('Notification - User Dialer Setting. The user "%(user)s" - "%(user_id)s" is not properly ' 'configured to use the system, please configure their dialer settings.') % \ {'user': request.user, 'user_id': request.user.id} # mail_admins() is a shortcut for sending an email to the site admins, # as defined in the ADMINS setting mail_admins(subject, message) request.session['has_notified'] = True return HttpResponseRedirect('/dashboard/')
def authenticate(self, username=None, password=None): if not password: return None if username.lower() != username: # The LDAP doesn't check the case of the user name (whyever). # Therefore, in order to avoid creation of duplicates, all LDAP # accounts must have all-lowercase usernames. return None ldap_connection = LDAPConnection() if not ldap_connection.is_valid(username, password): return None user, created = User.objects.get_or_create(username=username) if not user.is_active: mail_admins("Inactive user back?", message=("""User “{0}” tried to login but is set to inactive. However, the Active Directory knows him/her. There are two possibilities: Either this is the former collegue, then just set him/her to “active”. Or, they just happen to have the same login, then change the former collegue's login name. """.format(user.username)).encode("utf-8")) ldap_connection.synchronize_with_ad(user) return user
def auto_buy(request): user_prof = request.visitor["user"] brand = request.visitor["base_brand"] owner = None # users email matched existing if brand: # subscribed brand => go to search if brand.is_subscribed: return HttpResponseRedirect( request.user.userprofile.after_login_url) else: # brand mismatch, figure out whom the user claims he is try: brand = Brands.objects.get( domain_name__iexact=user_prof.temp_brand_domain) except Brands.DoesNotExist: mail_admins("No brand for user: %i during account_views.auto_buy" % (user_prof.id, )) raise Http404() except MultipleObjectsReturned: mail_admins( "Multiple brands for user: %i during account_views.auto_buy" % (user_prof.id, )) raise Http404() owner = brand.related_user_profiles.get( permissions=UserProfileBrandPrivilages.PRIVILAGE_OWNER ).user_profile return render( request, 'registration/auto_buy.html', { 'brand': brand, 'owner': owner, 'stripe_key': STRIPE_TEST_PUBLISHABLE_KEY if settings.DEBUG else STRIPE_LIVE_PUBLISHABLE_KEY, })
def save(self, *args, **kargs): super(Person, self).save(*args, **kargs) data = {'cliente': self.first_name} plain_text = render_to_string('clientes/emails/novo_cliente.txt', data) html_email = render_to_string('clientes/emails/novo_cliente.html', data) send_mail( 'Novo Cliente Cadastrado', plain_text, settings.EMAIL_HOST_USER, ['*****@*****.**'], html_message=html_email, fail_silently=False, ) mail_admins( 'Novo Cliente Cadastrado', plain_text, html_message=html_email, fail_silently=False, )
def emailGroup(country, group, link, subject, message, submiter=None): #email incident to admins in each country assoicated with the projects program for single_country in country.all(): country = Country.objects.all().filter(country=single_country) getGroupEmails = User.objects.all().filter( tola_user=group, tola_user__country=country).values_list('email', flat=True) email_link = link formatted_email = email_link subject = str(subject) message = str(message) + formatted_email to = [str(item) for item in getGroupEmails] if submiter: to.append(submiter) print to email = EmailMessage(subject, message, '*****@*****.**', to) email.send() mail_admins(subject, message, fail_silently=False)
def setEmail(request): if request.method == 'POST': # 方式一: # from django.core.mail import send_mail # send_mail('subject', 'this is the message of email', '*****@*****.**', # ['*****@*****.**', '*****@*****.**'], fail_silently=False) # # 方式二: # message1 = ('subject', 'text', '*****@*****.**', # ['*****@*****.**', '*****@*****.**'] ) # message2 = ('subject', 'text', '*****@*****.**', # ['*****@*****.**', '*****@*****.**'] ) # send_mass_mail((message1, message2), fail_silently=False) # # 方式三: 防止邮件头注入 # try: # send_mail(subject, message, from_email, recipient_list, fail_silently, auth_user, auth_password, connection) # except BadHeaderError: # return HttpResponse('Invalid header fount.') # 方式四: EmailMessage() # #首先实例化一个EmaiMessage()对象 # em = EmailMessage('subject', 'body', '*****@*****.**', ['*****@*****.**'],['*****@*****.**'], header={'Reply-to': '*****@*****.**'}) # #调用相应的方法 # # 方式五:发送多用途邮件 subject, from_email, to = 'hello', '*****@*****.**', '*****@*****.**' text_content = 'This is an important message' html_content = u"<b>激活链接:</b><a href='http://www.baidu.com'>http:www.baidu.com</a>" msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, 'text/html') msg.send() # 发送邮件成功给管理员发送一个反馈 mail_admins(u'用户注册反馈', u'当前xx用户注册成功', fail_silently = True) return HttpResponse('success') return render(request,'')
def contact_admins(request): if request.method == 'POST': form = ContactForm(request.POST or None, ) if form.is_valid(): sujet = form.cleaned_data['sujet'] message_txt = request.user.username + " a envoyé le message suivant : " message_html = form.cleaned_data['msg'] try: mail_admins(sujet, message_txt, html_message=message_html) if form.cleaned_data['renvoi']: send_mail(sujet, message_txt, request.user.email, request.user.email, fail_silently=False, html_message=message_html) return render(request, 'message_envoye.html', {'sujet': sujet, 'msg': message_html, 'envoyeur': request.user.username + " (" + request.user.email + ")", "destinataire": "administrateurs "}) except BadHeaderError: return render(request, 'erreur.html', {'msg':'Invalid header found.'}) return render(request, 'erreur.html', {'msg':"Désolé, une ereur s'est produite"}) else: form = ContactForm() return render(request, 'contact.html', {'form': form, "isContactProducteur":False})
def about(request): o = {} if request.method == 'POST': bad_answers = request.session.setdefault('bad_answers', 0) if bad_answers > 3: return HttpResponseForbidden( 'Too many failed attempts. Try again later.') o['form'] = FeedbackForm(request.POST) if o['form'].is_valid(): test_answer = request.POST.get('testanswer', '') if test_answer.isdigit() and int( test_answer) == request.session['test_answer']: request.session.pop('bad_answers') choice = o['form'].cleaned_data['purpose'] subj = '(%s) %s' % (dict( o['form'].fields['purpose'].choices)[choice], o['form'].cleaned_data['name']) msg = 'reply to: %(email)s\n\n%(message)s' % o[ 'form'].cleaned_data mail_admins(subj, msg, fail_silently=True) messages.add_message( request, messages.SUCCESS, 'Thank you. Your feedback has been submitted.') return HttpResponseRedirect('/about/') else: request.session['bad_answers'] = bad_answers + 1 o['bad_answer'] = True return render_to_response( 'about.html', o, context_instance=RequestContext(request)) else: o['form'] = FeedbackForm() return render_to_response('about.html', o, context_instance=RequestContext(request))
def inform_administrators(sender, **kwargs): from django.core.mail import mail_admins instance = kwargs["instance"] created = kwargs["created"] if created: context = { "title": instance.title, "link": instance.get_url(), } plain_text_message = render_to_string( 'viral_videos/email/administrator/message.txt', context) html_message = render_to_string( 'viral_videos/email/administrator/message.html', context) subject = render_to_string( 'viral_videos/email/administrator/subject.txt', context) mail_admins(subject=subject.strip(), message=plain_text_message, html_message=html_message, fail_silently=True)
def set_author(self, request): ''' Set author and status This is only used when creating images (via web or API) ''' if request.user.has_perm('exercises.add_exerciseimage'): self.status = self.STATUS_ACCEPTED if not self.license_author: self.license_author = request.get_host().split(':')[0] else: if not self.license_author: self.license_author = request.user.username subject = _('New user submitted image') message = _( u'The user {0} submitted a new image "{1}" for exercise {2}.' ).format(request.user.username, self.name, self.exercise) mail.mail_admins(six.text_type(subject), six.text_type(message), fail_silently=True)
def profil_contact(request, user_id): form = ContactForm(request.POST or None) recepteur = Profil.objects.get(id=user_id) if form.is_valid(): sujet = form.cleaned_data['sujet'] message = form.cleaned_data['message'] + '(par : ' + form.cleaned_data[ 'envoyeur'] + ')' mail_admins(sujet, message) send_mail( sujet, message, request.user.email, recepteur.user.email, fail_silently=False, ) # if renvoi: # mess = "message envoyé a la bourse libre : \\n" # send_mail( sujet,mess + message, envoyeur, to=[envoyeur], fail_silently=False,) return render(request, 'profil_contact.html', { 'form': form, 'recepteur': recepteur })
def alerting_healthcheck(): name = 'external-timestamp.desec.test' try: models.Domain.objects.get(name=name) except models.Domain.DoesNotExist: print( f'{name} zone is not configured; skipping alerting health check' ) return timestamps = [] qname = dns.name.from_text(name) query = dns.message.make_query(qname, dns.rdatatype.TXT) server = gethostbyname('ns1.desec.io') response = None try: response = dns.query.tcp(query, server, timeout=5) for content in response.find_rrset(dns.message.ANSWER, qname, dns.rdataclass.IN, dns.rdatatype.TXT): timestamps.append(str(content)[1:-1]) except Exception: pass now = time.time() if any(now - 600 <= int(timestamp) <= now for timestamp in timestamps): print(f'TXT {name} up to date.') return timestamps = ', '.join(timestamps) print(f'TXT {name} out of date! Timestamps: {timestamps}') subject = 'ALERT Alerting system down?' message = f'TXT query for {name} on {server} gave the following response:\n' message += f'{str(response)}\n\n' message += f'Extracted timestamps in TXT RRset:\n{timestamps}' mail_admins(subject, message, connection=get_connection( 'django.core.mail.backends.smtp.EmailBackend'))
def form_valid(self, form): ''' If the form is valid send email notifications to the site administrators. We don't return the super().form_valid because we don't want the data to be saved. ''' subject = 'Correction submitted for exercise #{0}'.format( self.get_object().pk) context = { 'exercise': self.get_object(), 'form_data': form.cleaned_data, 'user': self.request.user } message = render_to_string('exercise/email_correction.tpl', context) mail.mail_admins(six.text_type(subject), six.text_type(message), fail_silently=True) messages.success(self.request, self.messages) return HttpResponseRedirect( reverse('exercise:exercise:view', kwargs={'id': self.object.id}))
def check_for_unusual_sender(self): for ident in self.identity.all(): for permitted_domain in ident.service.permitted_senders: if permitted_domain in self.h_from: self.suspected_spam = False self.save() return # If we reach this point, h_from is not in any permitted sender list # Set it to be suspected spam and send a notification. self.suspected_spam = True subject = "Third-Party spam is suspected" message = render_to_string( "third_party_spam.txt", { "ident": ident, "mail": self, "URL": settings.SYSTEM_ROOT_URL }, ) if not settings.DISABLE_ADMIN_MAILS: mail_admins(subject, message) self.save()
def execute_redirect_chain(self, Action, link, landingPage=""): # Link is the link object passed to the function, df is the datafeed. try: method = lambda: 'POST' if Action.ape_redirect_id == None: success, content = self.execute_redirect_create() if success: Action.ape_redirect_id = content['redirect_id'] Action.save() if landingPage == None or landingPage == "": return False, None data = dict( url=landingPage, is_active=True, ) request_url = settings.APE_CREATE + 'redirect/' + str( Action.ape_redirect_id) + "/urls/" request_param = simplejson.dumps(data) headers = { 'Content-Type': 'application/application/json', 'Content-Length': len(request_param) } success, content = self.__execute__(request_url, method, request_param, headers) if success: if link != None: link.ape_url_id = content["url_id"] link.save() else: return content["url_id"] return True except Exception, e: print str(e) mail_admins('Adquotient: APE Chain Creation failed', '\r\n Failed: %s ' % (str(e)), True)
def send_error_report(request): user = request.user user_message = request.POST.get('message', '') info = request.POST.get('info', '') url = request.POST.get('url', '') message = _(""" Url: {0} Reporter: {1} (id: {2}, email: {3}) Info: {4} Message: {5} """).format(url, user, user.id, user.email, info, user_message) try: mail_admins(_('Error report'), message, fail_silently=False) status = 'sent' success = 'true' except SMTPException: status = 'failed' success = 'false' finally: return {'status': status, 'success': success}
def form_valid(self, form): form.instance.created_by = self.request.user response = super().form_valid(form) if self.object: messages.add_message( self.request, messages.SUCCESS, "Welcome to your new microcope page! You can find this " "page any time in your profile, and share this link with " "others. To <strong>update</strong> or <strong>delete</strong> this microscope, " "click the <i class='fas fa-cog mx-1'></i> icon below the graph." ) if not self.request.user.is_staff: try: mail_admins('Microscope Created', "User: {}\nMicroscope: {}\n{}".format( self.request.user.username, self.object, self.request.build_absolute_uri( self.object.get_absolute_url())), fail_silently=True) except Exception: pass return response
def create_new_videos_template(videos): template = loader.get_template('email-new-videos.html') content = template.render({ 'videos': videos, 'WEBSITE_URL': settings.WEBSITE_URL[:-1] }) url = 'https://us16.api.mailchimp.com/3.0/templates/' shortuuid.set_alphabet("abcdefghijklmnopqrstuvwxyz0123456789") template_name = 'new-videos-' + str( date.today()) + '-' + shortuuid.uuid()[:4] json_data = {'name': template_name, 'html': content} json_data = json.dumps(json_data) json_data = json_data.encode('utf8') r = requests.post(url, auth=('ILoveBlowjobs', settings.MAILCHIMP_API_KEY), data=json_data) if r.status_code / 100 != 2: mail_admins(subject='problem creating template for auto email', message=str(r.status_code) + " " + str(r.content)) return None r_content = json.loads(r.content) return r_content['id']
def csrf_failure(request, reason=""): email = "unknown" if request.user.is_authenticated(): email = request.user.email else: if request.method == 'POST': email = request.POST.get('email', None) if not email: email = request.POST.get('username', 'unknown') subject = _('CSRF error') message = _( "An error occured for %(email)s on %(path)s, reason : %(reason)s") % { 'email': email, 'path': request.path, 'reason': reason } mail_admins(subject, message) response = render_to_response('csrf.html', {'title': _('Error')}, context_instance=RequestContext(request)) response.status_code = 403 return response
def ssh_sftp_checker(): app_path = settings.BASE_DIR + "/AndroidRequestsBackups/" command = "bash " + app_path + "test/test_remote.bash" args = " " + settings.ANDROID_REQUESTS_BACKUPS['REMOTE_USER'] args += " " + settings.ANDROID_REQUESTS_BACKUPS['REMOTE_HOST'] args += " " + settings.ANDROID_REQUESTS_BACKUPS['PRIVATE_KEY'] args += " " + settings.ANDROID_REQUESTS_BACKUPS['REMOTE_BKP_FLDR'] + "/test" ret_val = subprocess.call(command + args, shell=True) if ret_val == 0: # we are done return # something failed, sending email subject = "Warning!: AndroidRequestsBackups connectivity check has failed." message = "Dear admins,\n" message += "\n" message += "With date %s, " % datetime.datetime.now().isoformat() message += "the AndroidRequestsBackups test for ssh and sftp connectivity " message += "has failed. This test attempts to stablish a ssh connection " message += "from the (TranSapp) to the (TranSappViz) server, and run a " message += "script on the remote. Then it stablishes an sftp connection " message += "to send a dummy file to the remote.\n" message += "\n" message += "\n" message += "Please, inspect the related log file, defined on the " message += "settings.py file. See the CRONJOBS variable. E.G: Run the " message += "following on the server:\n" message += "$ cat /tmp/android_request_bkps_ssh_sftp_checker_log.txt\n" message += "\n" message += "Bye.\n" message += "\n" mail_admins(subject, message, fail_silently=True) print "---" print "Emailed message" print "subject: " + subject print "message: " print message print "---"
def test_admin_settings(self): """Verify that we configure email with environment variable""" settings_vars = self.patch_settings({ **REQUIRED_SETTINGS, "MITXPRO_ADMIN_EMAIL": "" }) self.assertFalse(settings_vars.get("ADMINS", False)) test_admin_email = "*****@*****.**" settings_vars = self.patch_settings({ **REQUIRED_SETTINGS, "MITXPRO_ADMIN_EMAIL": test_admin_email }) 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)
def handle(self, message, **options): if options['stdin']: message = sys.stdin.read() else: message = ' '.join(message) html = None if options['html']: html = message mail_admins(options['subject'], message, html_message=html) if options['slack'] and hasattr(settings, 'MIA_THE_DEPLOY_BOT_API'): if options.get('environment') == 'staging': channel = '#staging' else: channel = '#hq-ops' requests.post(settings.MIA_THE_DEPLOY_BOT_API, data=json.dumps({ "channel": channel, "username": "******", "text": options['subject'], }))
def save(self, *args, **kwargs): super(Person, self).save(*args, **kwargs) data = {'cliente': self.first_name} plain_text = render_to_string('emails/novo_cliente.txt', data) html_text = render_to_string('emails/novo_cliente.html', data) send_mail( 'Novo cliente cadastrado', plain_text, '*****@*****.**', ['*****@*****.**'], html_message=html_text, fail_silently=False, ) mail_admins( 'Novo cliente cadastrado', plain_text, html_message=html_text, fail_silently=False, )
def save(self): message = self.cleaned_data['reference'] statuscode = self.cleaned_data['status'] now = datetime.datetime.now() # The filters below allow status to be out even though they're # already set to pnd by the send-algorithm. In case of a race, # allowing out as well, is beneficial. if statuscode == 50: # ack = success filter = {'status__in': ('out', 'pnd')} update = {'status': 'ack', 'delivery_date': now, 'modified': now} elif statuscode in (51, 52): # pnd = pending # (because this doesn't include pnd, we do not update) filter = {'status': 'out'} update = {'status': 'pnd', 'modified': now} else: # nak = failed filter = {'status__in': ('out', 'pnd')} update = {'status': 'nak', 'delivery_date': now, 'modified': now} rowcount = TextMessage.objects.filter(id=message.id, delivery_date=None, **filter).update(**update) assert rowcount in (0, 1) if (rowcount == 0 and # pnd => pnd is okay not (message.status == 'pnd' == update.get('status'))): # This should not happen. Possible cases when this might, # are when an ack is sent twice (delivery_date is set on the # second try) or if DLRs are sent out of order. mail_admins( u'SMS API warn: sms_mollie2 reference %s' % (message.id, ), (u'DLR caused an update of 0 rows.\nIn data: %r\n' u'Orig data: %r\n') % (self.cleaned_data, (message.status, message.delivery_date)), fail_silently=True) return message
def enviar(self): from django.core.mail import mail_admins subject = 'Un ciudadano está interesado en más información sobre tu candidatura [ID=#' + str( self.id) + ']' candidatos = Candidato.objects.filter(pregunta=self) current_site = Site.objects.get_current() for candidato in candidatos: texto_introduccion = u'Estimado(a) ' + candidato.nombre + ',\reste mensaje ha sido enviado desde ' + current_site.domain + ' por un ciudadano con el deseo de informarse sobre su candidatura:' texto_cierre = u'\r\r--\r*para responder a esta pregunta responda este mismo correo sin cambiar el asunto/subject. Gracias.\rLa respuesta quedará publicada en http://' + current_site.domain mensaje = texto_introduccion + u'\r\rYo, ' + self.remitente + ' quiero saber: \r\r' + self.texto_pregunta + texto_cierre destinaciones = Contacto.objects.filter(candidato=candidato) for destinacion in destinaciones: store_mail(subject, mensaje, settings.DEFAULT_FROM_EMAIL, [destinacion.valor]) #post to write-it #Esta wea no me gusta eleccion = candidatos[0].eleccion writeit_message = WriteItMessage.objects.create( author_name=self.remitente, author_email=settings.DEFAULT_FROM_EMAIL, subject=settings.DEFAULT_WRITEIT_SUBJECT + u" [ID=#" + str(self.id) + "]", writeitinstance=eleccion.write_it_instance, api_instance=eleccion.write_it_instance.api_instance, content=self.texto_pregunta, ) for candidato in candidatos: writeit_message.people.add(candidato.person) writeit_message.save() error = False try: writeit_message.push_to_the_api() except: mail_admins( 'Nos pegamos un cagazo mandando a la API de writeit la pregunta con id ' + str(self.id), 'Porfa arreglenlo =(')
def json_response(request, response=None): code = 200 if isinstance(response, HttpResponseForbidden): return response try: if isinstance(response, dict): response = dict(response) if 'result' not in response: response['result'] = 'ok' authenticated = request.user.is_authenticated() response['authenticated'] = authenticated except KeyboardInterrupt: # Allow keyboard interrupts through for debugging. raise except Http404: raise Http404 except Exception, e: # Mail the admins with the error exc_info = sys.exc_info() subject = 'JSON view error: %s' % request.path try: request_repr = repr(request) except: request_repr = 'Request repr() unavailable' import traceback message = 'Traceback:\n%s\n\nRequest:\n%s' % ( '\n'.join(traceback.format_exception(*exc_info)), request_repr, ) response = {'result': 'error', 'text': unicode(e)} code = 500 if not settings.DEBUG: mail_admins(subject, message, fail_silently=True) else: print '\n'.join(traceback.format_exception(*exc_info))
def create_caught_error(request, epoch, traceback, subject_prefix=""): error_obj = CaughtError.objects.create(epoch_time=epoch, user=request.user, error_time=datetime.datetime.now(), simple_traceback=traceback) try: detail_page_url = request.build_absolute_uri(error_obj.view_url) subject = "%s500 - %s" % (subject_prefix, error_obj) body = render_to_string("better500s/admin_email.txt", locals(), context_instance=RequestContext(request)) mail_admins(subject, body, fail_silently=True) if telegram and getattr(settings, 'BETTER_500_NOTIFICATION_CHANNEL', False): telegram.broadcast(settings.BETTER_500_NOTIFICATION_CHANNEL, subject, detail_page_url, add_to_queue=False) except: log = logging.getLogger("better500s") log.error(exception_string()) pass
def getChild(self, path, request): if 'dynamicforms' in request.postpath or 'staticforms' in request.postpath or 'guestpictures' in request.postpath: from django.contrib.auth.models import User from datetime import datetime from django.contrib.sessions.models import Session from guestmanagement.views import testPermission headers = request.received_headers cookies = { i.split('=')[0].strip(): i.split('=')[1].strip() for i in headers['cookie'].split(';') } session_id = cookies.get('sessionid', None) if not session_id: return Redirect('/guestmanagement/') sessions = Session.objects.filter(session_key=session_id, expire_date__gte=datetime.now()) user = None session = {} if sessions: session = sessions[0].get_decoded() users = User.objects.filter( id=session.get('_auth_user_id', None)) if users: user = users[0] try: if not testPermission( request.path, user, session, testurl=True): return Redirect('/guestmanagement/') except Exception, e: from django.core import mail import traceback, sys exc = sys.exc_info() subject = e.message.replace('\n', '\\n').replace('\r', '\\r')[:989] message = "%s\n\nglobals=%s\n\nlocals=%s" % ('\n'.join( traceback.format_exception(*exc)), str( globals()), str(locals())) mail.mail_admins(subject, message, fail_silently=True) return Redirect('/guestmanagement/')