Merge branch 'feature/LIL-718' into 'master'

LIL-718 Отправлять почты в sendgrid

Closes LIL-718

See merge request lilcity/backend!233
remotes/origin/editis_13-01-19
cfwme 7 years ago
commit 044d15b547
  1. 3
      api/v1/views.py
  2. 10
      apps/user/management/commands/subscribers_to_sendgrid.py
  3. 25
      apps/user/migrations/0028_auto_20181214_0107.py
  4. 2
      apps/user/models.py
  5. 45
      apps/user/tasks.py

@ -686,7 +686,6 @@ class CaptureEmail(views.APIView):
def post(self, request):
list_id = None
list_name = 'captured-emails'
recipient_id = None
email = request.data.get('email')
sg = get_sendgrid_client()
@ -709,7 +708,7 @@ class CaptureEmail(views.APIView):
response = sg.client.contactdb.recipients.patch(request_body=[{
'email': email,
}])
if response.status_code != 201:
if response.status_code != 201 or not response.to_dict.get('persisted_recipients'):
return Response({'error': 'Cannot update recipients'}, status=status.HTTP_400_BAD_REQUEST)
recipient_id = response.to_dict.get('persisted_recipients')[0]
# добавляем получателя в отдельный список

@ -0,0 +1,10 @@
from django.core.management.base import BaseCommand
from apps.user.tasks import subscribers_to_sendgrid
class Command(BaseCommand):
help = 'Send subscribers to sendgrid'
def handle(self, *args, **options):
subscribers_to_sendgrid()

@ -0,0 +1,25 @@
# Generated by Django 2.0.7 on 2018-12-14 01:07
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('user', '0027_user_gallery'),
]
operations = [
migrations.AddField(
model_name='emailsubscription',
name='created_at',
field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now),
preserve_default=False,
),
migrations.AddField(
model_name='emailsubscription',
name='sendgrid_sent',
field=models.BooleanField(default=False),
),
]

@ -285,6 +285,8 @@ class EmailSubscription(models.Model):
email = models.EmailField(_('email address'), unique=True)
categories = models.ManyToManyField(SubscriptionCategory)
mailchimp_status = models.PositiveSmallIntegerField(choices=MAILCHIMP_STATUS_CHOICES, default=ERROR)
created_at = models.DateTimeField(auto_now_add=True)
sendgrid_sent = models.BooleanField(default=False)
class Referral(models.Model):

@ -6,6 +6,7 @@ from django.conf import settings
from django.contrib.auth import get_user_model
from project.celery import app
from project.sengrid import get_sendgrid_client
@app.task
@ -43,3 +44,47 @@ def users_to_roistat():
key = settings.ROISTAT_KEY
url = settings.ROISTAT_API_URL + f'/project/clients/import?key={key}&project={project}'
resp = requests.post(url, json=users)
@app.task
def subscribers_to_sendgrid():
from apps.user.models import EmailSubscription
list_id = None
list_name = 'subscribed'
sg = get_sendgrid_client()
# берем все списки
response = sg.client.contactdb.lists.get()
if response.status_code != 200:
print('Cannot get list of lists')
return
# ищем нужный список
for sg_list in response.to_dict.get('lists'):
if sg_list.get('name') == list_name:
list_id = sg_list.get('id')
break
# не нашли - создаем
if not list_id:
response = sg.client.contactdb.lists.post(request_body={'name': list_name})
if response.status_code != 201:
print('List was not created')
return
list_id = response.to_dict.get('id')
for subscriber in EmailSubscription.objects.filter(sendgrid_sent=False):
print('Adding subscriber %s ...' % subscriber.email, end=' ')
# добавляем получателя
response = sg.client.contactdb.recipients.patch(request_body=[{
'email': subscriber.email,
}])
if response.status_code != 201 or not response.to_dict.get('persisted_recipients'):
print('Cannot update recipients')
continue
recipient_id = response.to_dict.get('persisted_recipients')[0]
# добавляем получателя в отдельный список
response = sg.client.contactdb.lists._(list_id).recipients._(recipient_id).post()
if response.status_code != 201:
print('Cannot add recipient to list')
else:
print('OK')
subscriber.sendgrid_sent = True
subscriber.save()

Loading…
Cancel
Save