add mail sender in admin
authorHongyuan Ma <CS_MaleicAcid@163.com>
Wed, 1 Aug 2018 13:51:57 +0000 (21:51 +0800)
committerHongyuan Ma <CS_MaleicAcid@163.com>
Wed, 1 Aug 2018 13:51:57 +0000 (21:51 +0800)
web/apps/test_records/models.py
web/apps/users/admin.py
web/apps/users/models.py
web/extra_apps/asynchronous_send_mail/__init__.py [new file with mode: 0644]
web/extra_apps/asynchronous_send_mail/models.py [new file with mode: 0644]
web/extra_apps/asynchronous_send_mail/tests.py [new file with mode: 0644]
web/extra_apps/asynchronous_send_mail/views.py [new file with mode: 0644]
web/pgperffarm/settings.py
web/pgperffarm/settings_local.py.in

index 6bb1d3d5916906984141928e8db43cffa4aaa8f8..2d9e2ad768a3d173ba12f945f57c3e6e16cdb93f 100644 (file)
@@ -3,7 +3,7 @@ from django.utils import timezone
 from django.db import models
 
 # Create your models here.
-from users.models import UserProfile, UserMachine
+from users.models import UserMachine
 
 
 class TestBranch(models.Model):
index 16fc2e88d5d4bed81f43db896071433dd9f1eaca..8d675c2c0e30ddb958b045362d360752cc1901e4 100644 (file)
@@ -2,11 +2,13 @@
 from __future__ import unicode_literals
 
 from django.contrib import admin
-
+from asynchronous_send_mail import send_mail
+from django.conf import settings
 # Register your models here.
 from serializer import UserMachineSerializer
 from .models import UserMachine
 
+
 class UserMachineAdmin(admin.ModelAdmin):
     list_display = ('alias', 'machine_sn', 'state')
     list_filter = ('state',)
@@ -16,23 +18,38 @@ class UserMachineAdmin(admin.ModelAdmin):
 
         total = 0
         error = 0
-        success =0
+        success = 0
         for machine in queryset:
 
             ret = machine.approve_machine()
-            '''
-                ret = {"is_success": True, "alias": 'alias', "secrct": 'machine_secret', }
-            '''
-            if ret.is_success:
+            # ret = {"is_success": True, "alias": 'alias', "secrct": 'machine_secret', "email":user_email}
+
+            if ret['is_success']:
                 success += 1
+                # send email to notice user
+                content = "The machine you have applied for has been approved.\n\
+Here is the information about it: \n \
+\n \
+alias: %s\n \
+secret: %s\n \
+\n \
+Regards,\n \
+PG PERF FARM" % (ret['alias'], ret['secret'])
+                #  ret['alias'] + ': ' + ret['secret']
+
+                send_mail('[PG PERF FARM]Machine Approval Notice', content, settings.EMAIL_HOST_USER, [ret['email']],
+                          fail_silently=False)
+
             else:
                 error += 1
 
-            total +=1
+            total += 1
 
         # rows_updated = queryset.update(state=1)
         # message_bit = "%s machine(s)" % rows_updated
-        self.message_user(request, "Total: %s ,Success: %s ,Error: %s. Please make sure there are enough unused aliases" % (total,success,error))
+        self.message_user(request,
+                          "Total: %s ,Success: %s ,Error: %s. Please make sure there are enough unused aliases." % (
+                              total, success, error))
 
     approve_machine.short_description = u'Approve Machine(Modify the state to active, generate machine_sn, machine_secret, and assign an alias)'
 
index 8f40dd81ed8ee254194d6621e9b6e9f66d9acb3f..4e05a47a6f1e2450aaa7afd202717d3bb1b58351 100644 (file)
@@ -9,6 +9,8 @@ from django.contrib.auth.models import AbstractUser
 
 
 # Create your models here.
+# from .serializer import JWTUserProfileSerializer
+
 
 class UserProfile(AbstractUser):
     """
@@ -42,7 +44,7 @@ class UserMachine(models.Model):
     machine_sn = models.CharField(max_length=16, verbose_name="machine sn")
     machine_secret = models.CharField(max_length=32, verbose_name="machine secret")
     machine_owner = models.ForeignKey(UserProfile)
-    alias = models.ForeignKey(Alias,blank=True ,verbose_name="alias", help_text="alias")
+    alias = models.ForeignKey(Alias,blank=True, default=None, verbose_name="alias", help_text="alias")
     os_name = models.CharField(max_length=32, verbose_name="operation system name")
     os_version = models.CharField(max_length=32, verbose_name="operation system version")
     comp_name = models.CharField(max_length=32, verbose_name="compiler name")
@@ -68,7 +70,7 @@ class UserMachine(models.Model):
         "Approve Machine(Modify the state to active, generate machine_sn, machine_secret, and assign an alias)"
         alias = Alias.objects.filter(is_used=False).order_by('?').first()
         if not alias:
-            return {"is_success": False, "alias": '', "secrct": ''}
+            return {"is_success": False, "alias": '', "secret": '', "email":''}
         from django.db import transaction
         with transaction.atomic():
             alias.is_used=True
@@ -88,5 +90,8 @@ class UserMachine(models.Model):
 
             self.save()
 
-        user_email = 
-        return  {"is_success": True, "alias": self.alias, "secrct": self.machine_secret, "email":}
\ No newline at end of file
+
+        # serializer = JWTUserProfileSerializer(user)
+        print(self.machine_owner.email)
+        user_email = self.machine_owner.email
+        return  {"is_success": True, "alias": self.alias.name, "secret": self.machine_secret, "email":user_email}
\ No newline at end of file
diff --git a/web/extra_apps/asynchronous_send_mail/__init__.py b/web/extra_apps/asynchronous_send_mail/__init__.py
new file mode 100644 (file)
index 0000000..fb85442
--- /dev/null
@@ -0,0 +1,24 @@
+from django.core.mail import send_mail as core_send_mail
+from django.core.mail import EmailMultiAlternatives
+import threading
+
+class EmailThread(threading.Thread):
+    def __init__(self, subject, body, from_email, recipient_list, fail_silently, html):
+        self.subject = subject
+        self.body = body
+        self.recipient_list = recipient_list
+        self.from_email = from_email
+        self.fail_silently = fail_silently
+        self.html = html
+        threading.Thread.__init__(self)
+
+    def run (self):
+        msg = EmailMultiAlternatives(self.subject, self.body, self.from_email, self.recipient_list)
+        if self.html:
+            msg.attach_alternative(self.html, "text/html")
+        msg.send(self.fail_silently)
+
+def send_mail(subject, body, from_email, recipient_list, fail_silently=False, html=None, *args, **kwargs):
+    EmailThread(subject, body, from_email, recipient_list, fail_silently, html).start()
+            
+
diff --git a/web/extra_apps/asynchronous_send_mail/models.py b/web/extra_apps/asynchronous_send_mail/models.py
new file mode 100644 (file)
index 0000000..71a8362
--- /dev/null
@@ -0,0 +1,3 @@
+from django.db import models
+
+# Create your models here.
diff --git a/web/extra_apps/asynchronous_send_mail/tests.py b/web/extra_apps/asynchronous_send_mail/tests.py
new file mode 100644 (file)
index 0000000..2247054
--- /dev/null
@@ -0,0 +1,23 @@
+"""
+This file demonstrates two different styles of tests (one doctest and one
+unittest). These will both pass when you run "manage.py test".
+
+Replace these with more appropriate tests for your application.
+"""
+
+from django.test import TestCase
+
+class SimpleTest(TestCase):
+    def test_basic_addition(self):
+        """
+        Tests that 1 + 1 always equals 2.
+        """
+        self.failUnlessEqual(1 + 1, 2)
+
+__test__ = {"doctest": """
+Another way to test that 1 + 1 is equal to 2.
+
+>>> 1 + 1 == 2
+True
+"""}
+
diff --git a/web/extra_apps/asynchronous_send_mail/views.py b/web/extra_apps/asynchronous_send_mail/views.py
new file mode 100644 (file)
index 0000000..e69de29
index fad5ec7beea5a23a9b6aa558905b432c1952809d..e572856b827ec0059c1e393bbfbeaa412cb3ffd8 100644 (file)
@@ -53,6 +53,7 @@ INSTALLED_APPS = (
     'test_records',
     'crispy_forms',
     'user_operation',
+    'asynchronous_send_mail'
 )
 
 MIDDLEWARE_CLASSES = (
@@ -217,3 +218,11 @@ JWT_AUTH = {
     'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=7200),
     'JWT_AUTH_HEADER_PREFIX': 'Token',
 }
+
+EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
+EMAIL_USE_SSL = True
+EMAIL_HOST = 'smtp.163.com'
+EMAIL_PORT = 465
+EMAIL_HOST_USER = ''
+EMAIL_HOST_PASSWORD = ''  # individual password
+DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
index 39618d47b419f45e9ab773f0de272d70e3a33d63..26d1559b5e258f8cb35aca1f7bf595f8236fe308 100644 (file)
@@ -11,4 +11,11 @@ DATABASES={
         }
 
 PGAUTH_REDIRECT=''
-PGAUTH_KEY=''
\ No newline at end of file
+PGAUTH_KEY=''
+
+PORJECT_PATH = '/var/www/web/pgperffarm' # 'D:\GitSpace\pgperffarm\web\pgperffarm'
+PGAUTH_REDIRECT=''
+PGAUTH_KEY=''
+
+EMAIL_HOST_USER = ''
+EMAIL_HOST_PASSWORD = ''  # individual smtp password
\ No newline at end of file