Skip to content

Commit

Permalink
ruff-format (#471)
Browse files Browse the repository at this point in the history
  • Loading branch information
Mogost authored Jun 14, 2024
1 parent 7abc956 commit 66034d8
Show file tree
Hide file tree
Showing 43 changed files with 1,150 additions and 745 deletions.
11 changes: 10 additions & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,16 @@ on:
permissions:
contents: read

jobs:
jobs:
ruff-format:
runs-on: ubuntu-latest
timeout-minutes: 1
steps:
- uses: actions/checkout@v3
- uses: chartboost/ruff-action@v1
with:
version: 0.4.8
args: 'format --check'

build:
runs-on: ubuntu-latest
Expand Down
2 changes: 1 addition & 1 deletion post_office/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from ast import literal_eval
from os.path import dirname, join

with open(join(dirname(__file__), "version.txt")) as fh:
with open(join(dirname(__file__), 'version.txt')) as fh:
VERSION = literal_eval(fh.read())

from .backends import EmailBackend
98 changes: 46 additions & 52 deletions post_office/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@
from django.db import models
from django.forms import BaseInlineFormSet
from django.forms.widgets import TextInput
from django.http.response import (HttpResponse, HttpResponseNotFound,
HttpResponseRedirect)
from django.http.response import HttpResponse, HttpResponseNotFound, HttpResponseRedirect
from django.template import Context, Template
from django.urls import re_path, reverse
from django.utils.html import format_html
Expand All @@ -22,8 +21,7 @@


def get_message_preview(instance):
return (f'{instance.message[:25]}...' if len(instance.message) > 25
else instance.message)
return f'{instance.message[:25]}...' if len(instance.message) > 25 else instance.message


get_message_preview.short_description = 'Message'
Expand All @@ -32,7 +30,7 @@ def get_message_preview(instance):
class AttachmentInline(admin.StackedInline):
model = Attachment.emails.through
extra = 0
autocomplete_fields = ["attachment"]
autocomplete_fields = ['attachment']

def get_formset(self, request, obj=None, **kwargs):
self.parent_obj = obj
Expand All @@ -51,7 +49,7 @@ def get_queryset(self, request):
a.id
for a in queryset
if isinstance(a.attachment.headers, dict)
and a.attachment.headers.get("Content-Disposition", "").startswith("inline")
and a.attachment.headers.get('Content-Disposition', '').startswith('inline')
]
return queryset.exclude(id__in=inlined_attachments)

Expand All @@ -69,7 +67,6 @@ def has_change_permission(self, request, obj=None):


class CommaSeparatedEmailWidget(TextInput):

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.attrs.update({'class': 'vTextField'})
Expand All @@ -79,7 +76,7 @@ def format_value(self, value):
if not value:
return ''
if isinstance(value, str):
value = [value, ]
value = [value]
return ','.join([item for item in value])


Expand All @@ -92,19 +89,29 @@ def requeue(modeladmin, request, queryset):


class EmailAdmin(admin.ModelAdmin):
list_display = ['truncated_message_id', 'to_display', 'shortened_subject', 'status', 'last_updated', 'scheduled_time', 'use_template']
list_display = [
'truncated_message_id',
'to_display',
'shortened_subject',
'status',
'last_updated',
'scheduled_time',
'use_template',
]
search_fields = ['to', 'subject']
readonly_fields = ['message_id', 'render_subject', 'render_plaintext_body', 'render_html_body']
readonly_fields = ['message_id', 'render_subject', 'render_plaintext_body', 'render_html_body']
inlines = [AttachmentInline, LogInline]
list_filter = ['status', 'template__language', 'template__name']
formfield_overrides = {
CommaSeparatedEmailField: {'widget': CommaSeparatedEmailWidget}
}
formfield_overrides = {CommaSeparatedEmailField: {'widget': CommaSeparatedEmailWidget}}
actions = [requeue]

def get_urls(self):
urls = [
re_path(r'^(?P<pk>\d+)/image/(?P<content_id>[0-9a-f]{32})$', self.fetch_email_image, name='post_office_email_image'),
re_path(
r'^(?P<pk>\d+)/image/(?P<content_id>[0-9a-f]{32})$',
self.fetch_email_image,
name='post_office_email_image',
),
re_path(r'^(?P<pk>\d+)/resend/$', self.resend, name='resend'),
]
urls.extend(super().get_urls())
Expand All @@ -121,9 +128,9 @@ def truncated_message_id(self, instance):
return Truncator(instance.message_id[1:-1]).chars(10)
return str(instance.id)

to_display.short_description = _("To")
to_display.short_description = _('To')
to_display.admin_order_field = 'to'
truncated_message_id.short_description = "Message-ID"
truncated_message_id.short_description = 'Message-ID'

def has_add_permission(self, request):
return False
Expand All @@ -141,13 +148,13 @@ def shortened_subject(self, instance):
subject = instance.subject
return Truncator(subject).chars(100)

shortened_subject.short_description = _("Subject")
shortened_subject.short_description = _('Subject')
shortened_subject.admin_order_field = 'subject'

def use_template(self, instance):
return bool(instance.template_id)

use_template.short_description = _("Use Template")
use_template.short_description = _('Use Template')
use_template.boolean = True

def get_fieldsets(self, request, obj=None):
Expand All @@ -166,32 +173,26 @@ def get_fieldsets(self, request, obj=None):
has_html_content = True

if has_html_content:
fieldsets.append(
(_("HTML Email"), {'fields': ['render_subject', 'render_html_body']})
)
fieldsets.append((_('HTML Email'), {'fields': ['render_subject', 'render_html_body']}))
if has_plaintext_content:
fieldsets.append(
(_("Text Email"), {'classes': ['collapse'], 'fields': ['render_plaintext_body']})
)
fieldsets.append((_('Text Email'), {'classes': ['collapse'], 'fields': ['render_plaintext_body']}))
elif has_plaintext_content:
fieldsets.append(
(_("Text Email"), {'fields': ['render_subject', 'render_plaintext_body']})
)
fieldsets.append((_('Text Email'), {'fields': ['render_subject', 'render_plaintext_body']}))

return fieldsets

def render_subject(self, instance):
message = instance.email_message()
return message.subject

render_subject.short_description = _("Subject")
render_subject.short_description = _('Subject')

def render_plaintext_body(self, instance):
for message in instance.email_message().message().walk():
if isinstance(message, SafeMIMEText) and message.get_content_type() == 'text/plain':
return format_html('<pre>{}</pre>', message.get_payload())

render_plaintext_body.short_description = _("Mail Body")
render_plaintext_body.short_description = _('Mail Body')

def render_html_body(self, instance):
pattern = re.compile('cid:([0-9a-f]{32})')
Expand All @@ -202,7 +203,7 @@ def render_html_body(self, instance):
payload = message.get_payload(decode=True).decode('utf-8')
return clean_html(pattern.sub(url, payload))

render_html_body.short_description = _("HTML Body")
render_html_body.short_description = _('HTML Body')

def fetch_email_image(self, request, pk, content_id):
instance = self.get_object(request, pk)
Expand All @@ -214,7 +215,7 @@ def fetch_email_image(self, request, pk, content_id):
def resend(self, request, pk):
instance = self.get_object(request, pk)
instance.dispatch()
messages.info(request, "Email has been sent again")
messages.info(request, 'Email has been sent again')
return HttpResponseRedirect(reverse('admin:post_office_email_change', args=[instance.pk]))


Expand Down Expand Up @@ -249,14 +250,13 @@ class EmailTemplateAdminForm(forms.ModelForm):
language = forms.ChoiceField(
choices=settings.LANGUAGES,
required=False,
label=_("Language"),
help_text=_("Render template in alternative language"),
label=_('Language'),
help_text=_('Render template in alternative language'),
)

class Meta:
model = EmailTemplate
fields = ['name', 'description', 'subject', 'content', 'html_content', 'language',
'default_template']
fields = ['name', 'description', 'subject', 'content', 'html_content', 'language', 'default_template']

def __init__(self, *args, **kwargs):
instance = kwargs.get('instance')
Expand All @@ -270,10 +270,8 @@ class EmailTemplateInline(admin.StackedInline):
formset = EmailTemplateAdminFormSet
model = EmailTemplate
extra = 0
fields = ('language', 'subject', 'content', 'html_content',)
formfield_overrides = {
models.CharField: {'widget': SubjectField}
}
fields = ('language', 'subject', 'content', 'html_content')
formfield_overrides = {models.CharField: {'widget': SubjectField}}

def get_max_num(self, request, obj=None, **kwargs):
return len(settings.LANGUAGES)
Expand All @@ -284,30 +282,26 @@ class EmailTemplateAdmin(admin.ModelAdmin):
list_display = ('name', 'description_shortened', 'subject', 'languages_compact', 'created')
search_fields = ('name', 'description', 'subject')
fieldsets = [
(None, {
'fields': ('name', 'description'),
}),
(_("Default Content"), {
'fields': ('subject', 'content', 'html_content'),
}),
(None, {'fields': ('name', 'description')}),
(_('Default Content'), {'fields': ('subject', 'content', 'html_content')}),
]
inlines = (EmailTemplateInline,) if settings.USE_I18N else ()
formfield_overrides = {
models.CharField: {'widget': SubjectField}
}
formfield_overrides = {models.CharField: {'widget': SubjectField}}

def get_queryset(self, request):
return self.model.objects.filter(default_template__isnull=True)

def description_shortened(self, instance):
return Truncator(instance.description.split('\n')[0]).chars(200)
description_shortened.short_description = _("Description")

description_shortened.short_description = _('Description')
description_shortened.admin_order_field = 'description'

def languages_compact(self, instance):
languages = [tt.language for tt in instance.translated_templates.order_by('language')]
return ', '.join(languages)
languages_compact.short_description = _("Languages")

languages_compact.short_description = _('Languages')

def save_model(self, request, obj, form, change):
obj.save()
Expand All @@ -320,8 +314,8 @@ def save_model(self, request, obj, form, change):
class AttachmentAdmin(admin.ModelAdmin):
list_display = ['name', 'file']
filter_horizontal = ['emails']
search_fields = ["name"]
autocomplete_fields = ["emails"]
search_fields = ['name']
autocomplete_fields = ['emails']


admin.site.register(Email, EmailAdmin)
Expand Down
2 changes: 1 addition & 1 deletion post_office/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

class PostOfficeConfig(AppConfig):
name = 'post_office'
verbose_name = _("Post Office")
verbose_name = _('Post Office')
default_auto_field = 'django.db.models.AutoField'

def ready(self):
Expand Down
25 changes: 15 additions & 10 deletions post_office/backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
from django.core.mail.backends.base import BaseEmailBackend
from .settings import get_default_priority

class EmailBackend(BaseEmailBackend):

class EmailBackend(BaseEmailBackend):
def open(self):
pass

Expand Down Expand Up @@ -33,14 +33,14 @@ def send_messages(self, email_messages):
from_email = email_message.from_email
headers = email_message.extra_headers
if email_message.reply_to:
reply_to_header = ", ".join(str(v) for v in email_message.reply_to)
headers.setdefault("Reply-To", reply_to_header)
message = email_message.body # The plaintext message is called body
reply_to_header = ', '.join(str(v) for v in email_message.reply_to)
headers.setdefault('Reply-To', reply_to_header)
message = email_message.body # The plaintext message is called body
html_body = '' # The default if no html body can be found
if hasattr(email_message, 'alternatives') and len(email_message.alternatives) > 0:
for alternative in email_message.alternatives:
if alternative[1] == 'text/html':
html_body = alternative[0]
html_body = alternative[0]

attachment_files = {}
for attachment in email_message.attachments:
Expand All @@ -53,11 +53,16 @@ def send_messages(self, email_messages):
else:
attachment_files[attachment[0]] = ContentFile(attachment[1])

email = create(sender=from_email,
recipients=email_message.to, cc=email_message.cc,
bcc=email_message.bcc, subject=subject,
message=message, html_message=html_body,
headers=headers)
email = create(
sender=from_email,
recipients=email_message.to,
cc=email_message.cc,
bcc=email_message.bcc,
subject=subject,
message=message,
html_message=html_body,
headers=headers,
)

if attachment_files:
attachments = create_attachments(attachment_files)
Expand Down
1 change: 1 addition & 0 deletions post_office/connections.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ class ConnectionHandler:
Ensures only one instance of each alias exists per thread.
"""

def __init__(self):
self._connections = local()

Expand Down
3 changes: 2 additions & 1 deletion post_office/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

class CommaSeparatedEmailField(TextField):
default_validators = [validate_comma_separated_emails]
description = _("Comma-separated emails")
description = _('Comma-separated emails')

def __init__(self, *args, **kwargs):
kwargs['blank'] = True
Expand Down Expand Up @@ -52,6 +52,7 @@ def south_field_triple(self):
Taken from smiley chris' easy_thumbnails
"""
from south.modelsinspector import introspector

field_class = 'django.db.models.fields.TextField'
args, kwargs = introspector(self)
return (field_class, args, kwargs)
Loading

0 comments on commit 66034d8

Please sign in to comment.