Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/export subscribers #234

Merged
merged 5 commits into from
Jan 13, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions server/apps/newsletter/management/commands/export_subscribers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import csv
import os
from django.core.management.base import BaseCommand
from django.conf import settings
from django.utils import timezone
from apps.newsletter.models import Subscriber

class Command(BaseCommand):
help = 'Export subscribers to a CSV file'

def handle(self, *args, **kwargs):
try:
export_dir = os.path.join(settings.MEDIA_ROOT, 'exports')
os.makedirs(export_dir, exist_ok=True)

csv_filename = os.path.join(export_dir, 'subscribers_export.csv')

subscribers = Subscriber.objects.iterator()

with open(csv_filename, mode='w', newline='', encoding='utf-8') as csv_file:
fieldnames = ['email', 'is_active', 'subscribed_at']
writer = csv.DictWriter(csv_file, fieldnames=fieldnames, escapechar='\\', quoting=csv.QUOTE_ALL)

writer.writeheader()

for subscriber in subscribers:
safe_email = subscriber.email.replace('\n', '').replace('\r', '') if subscriber.email else ''
writer.writerow({
'email': safe_email,
'is_active': 'Yes' if subscriber.is_active else 'No',
'subscribed_at': timezone.localtime(subscriber.subscribed_at).isoformat() if subscriber.subscribed_at else ''
})

self.stdout.write(self.style.SUCCESS(f'Successfully exported subscribers to {csv_filename}'))

except Exception as e:
self.stderr.write(self.style.ERROR(f'Error exporting subscribers: {str(e)}'))
raise
Loading