Skip to content

Commit

Permalink
Merge pull request #3 from agroptima/ADJ-7423-upgrade-agroptima-to-dj…
Browse files Browse the repository at this point in the history
…ango-4-x

[ADJ-7423] Upgrade to Django 4.X
  • Loading branch information
josesalvador authored Nov 18, 2024
2 parents b75faba + 9d6ed5a commit b59de8e
Show file tree
Hide file tree
Showing 4 changed files with 100 additions and 82 deletions.
4 changes: 2 additions & 2 deletions .circleci/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ version: 2
jobs:
build:
docker:
- image: circleci/python:3.6.8-jessie
- image: cimg/python:3.10

steps:
- checkout
- run:
name: install dependencies
command: pip install --user Django==2.2.6
command: pip install --user Django==4.2.16
- run:
name: run tests
command: python -m mailviews.tests
125 changes: 73 additions & 52 deletions mailviews/previews.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@
from email.header import decode_header

import django
from django.urls import reverse
from django.http import Http404
from django.shortcuts import render
from django.urls import reverse

try:
from collections import OrderedDict
Expand All @@ -19,20 +19,18 @@
except ImportError:
from django.utils.importlib import import_module

from django.urls import include, re_path
from django.utils.module_loading import module_has_submodule

from mailviews.helpers import should_use_staticfiles
from mailviews.utils import split_docstring, unimplemented

from django.conf.urls import include, url


logger = logging.getLogger(__name__)


URL_NAMESPACE = 'mailviews'
URL_NAMESPACE = "mailviews"

ModulePreviews = namedtuple('ModulePreviews', ('module', 'previews'))
ModulePreviews = namedtuple("ModulePreviews", ("module", "previews"))


def maybe_decode_header(header):
Expand All @@ -58,51 +56,61 @@ def __iter__(self):
Returns an iterator of :class:`ModulePreviews` tuples, sorted by module nae.
"""
for module in sorted(self.__previews.keys()):
previews = ModulePreviews(module, sorted(self.__previews[module].values(), key=str))
previews = ModulePreviews(
module, sorted(self.__previews[module].values(), key=str)
)
yield previews

def register(self, cls):
"""
Adds a preview to the index.
"""
preview = cls(site=self)
logger.debug('Registering %r with %r', preview, self)
logger.debug("Registering %r with %r", preview, self)
index = self.__previews.setdefault(preview.module, {})
index[cls.__name__] = preview

@property
def urls(self):

urlpatterns = [
url(regex=r'^$',
view=self.list_view,
name='list'),
url(regex=r'^(?P<module>.+)/(?P<preview>.+)/$',
re_path(route=r"^$", view=self.list_view, name="list"),
re_path(
route=r"^(?P<module>.+)/(?P<preview>.+)/$",
view=self.detail_view,
name='detail'),
name="detail",
),
]

if not should_use_staticfiles():
url_staticsfiles = [
url(regex=r'^static/(?P<path>.*)$',
re_path(
route=r"^static/(?P<path>.*)$",
view=django.views.static.serve,
kwargs={
'document_root': os.path.join(os.path.dirname(__file__), 'static'),
"document_root": os.path.join(
os.path.dirname(__file__), "static"
),
},
name='static')
name="static",
)
]

urlpatterns += url_staticsfiles

return include((urlpatterns, 'mailviews'), namespace=URL_NAMESPACE)
return include((urlpatterns, "mailviews"), namespace=URL_NAMESPACE)

def list_view(self, request):
"""
Returns a list view response containing all of the registered previews.
"""
return render(request, 'mailviews/previews/list.html', {
'site': self,
})
return render(
request,
"mailviews/previews/list.html",
{
"site": self,
},
)

def detail_view(self, request, module, preview):
"""
Expand All @@ -121,7 +129,7 @@ class Preview(object):
message_view = property(unimplemented)

#: The subset of headers to show in the preview panel.
headers = ('Subject', 'From', 'To')
headers = ("Subject", "From", "To")

#: The title of this email message to use in the previewer. If not provided,
#: this will default to the name of the message view class.
Expand All @@ -132,7 +140,7 @@ class Preview(object):
form_class = None

#: The template that will be rendered for this preview.
template_name = 'mailviews/previews/detail.html'
template_name = "mailviews/previews/detail.html"

def __init__(self, site):
self.site = site
Expand All @@ -142,7 +150,7 @@ def __unicode__(self):

@property
def module(self):
return '%s' % self.message_view.__module__
return "%s" % self.message_view.__module__

@property
def description(self):
Expand All @@ -152,17 +160,20 @@ def description(self):
If not provided, this defaults to the first paragraph of the underlying
message view class' docstring.
"""
return getattr(split_docstring(self.message_view), 'summary', None)
return getattr(split_docstring(self.message_view), "summary", None)

@property
def url(self):
"""
The URL to access this preview.
"""
return reverse('%s:detail' % URL_NAMESPACE, kwargs={
'module': self.module,
'preview': type(self).__name__,
})
return reverse(
"%s:detail" % URL_NAMESPACE,
kwargs={
"module": self.module,
"preview": type(self).__name__,
},
)

def get_message_view(self, request, **kwargs):
return self.message_view(**kwargs)
Expand All @@ -172,7 +183,7 @@ def detail_view(self, request):
Renders the message view to a response.
"""
context = {
'preview': self,
"preview": self,
}

kwargs = {}
Expand All @@ -182,34 +193,43 @@ def detail_view(self, request):
else:
form = self.form_class()

context['form'] = form
context["form"] = form
if not form.is_bound or not form.is_valid():
return render(request, 'mailviews/previews/detail.html', context)
return render(request, "mailviews/previews/detail.html", context)

kwargs.update(form.get_message_view_kwargs())

message_view = self.get_message_view(request, **kwargs)

message = message_view.render_to_message()
raw = message.message()
headers = OrderedDict((header, maybe_decode_header(raw[header])) for header in self.headers)

context.update({
'message': message,
'subject': message.subject,
'body': message.body,
'headers': headers,
'raw': raw.as_string(),
})

alternatives = getattr(message, 'alternatives', [])
headers = OrderedDict(
(header, maybe_decode_header(raw[header])) for header in self.headers
)

context.update(
{
"message": message,
"subject": message.subject,
"body": message.body,
"headers": headers,
"raw": raw.as_string(),
}
)

alternatives = getattr(message, "alternatives", [])
try:
html = next(alternative[0] for alternative in alternatives
if alternative[1] == 'text/html')
context.update({
'html': html,
'escaped_html': b64encode(html.encode('utf-8')),
})
html = next(
alternative[0]
for alternative in alternatives
if alternative[1] == "text/html"
)
context.update(
{
"html": html,
"escaped_html": b64encode(html.encode("utf-8")),
}
)
except StopIteration:
pass

Expand All @@ -221,18 +241,19 @@ def autodiscover():
Imports all available previews classes.
"""
from django.conf import settings

for application in settings.INSTALLED_APPS:
module = import_module(application)

if module_has_submodule(module, 'emails'):
emails = import_module('%s.emails' % application)
if module_has_submodule(module, "emails"):
emails = import_module("%s.emails" % application)
try:
import_module('%s.emails.previews' % application)
import_module("%s.emails.previews" % application)
except ImportError:
# Only raise the exception if this module contains previews and
# there was a problem importing them. (An emails module that
# does not contain previews is not an error.)
if module_has_submodule(emails, 'previews'):
if module_has_submodule(emails, "previews"):
raise


Expand Down
10 changes: 3 additions & 7 deletions mailviews/tests/urls.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,9 @@
from django.conf.urls import include, url

from django.urls import re_path

from mailviews.previews import autodiscover, site


autodiscover()

app_name = 'mailviews'
app_name = "mailviews"

urlpatterns = [
url(regex=r'', view=site.urls)
]
urlpatterns = [re_path(route=r"", view=site.urls)]
43 changes: 22 additions & 21 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,31 +2,32 @@
from setuptools import find_packages, setup


setup(name='django-mailviews',
version='0.7.5',
url='http://github.com/disqus/django-mailviews/',
author='ted kaemming',
author_email='[email protected]',
description='Class-based mail views for Django',
setup(
name="django-mailviews",
version="0.7.5",
url="http://github.com/disqus/django-mailviews/",
author="ted kaemming",
author_email="[email protected]",
description="Class-based mail views for Django",
packages=find_packages(),
include_package_data=True,
install_requires=[
'Django>=2.2.6',
"Django>=4.2.16",
],
test_suite='mailviews.tests.__main__.__main__',
test_suite="mailviews.tests.__main__.__main__",
zip_safe=False,
license='Apache License 2.0',
license="Apache License 2.0",
classifiers=[
'Development Status :: 5 - Production/Stable',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache License 2.0',
'Operating System :: OS Independent',
'Topic :: Software Development',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
]
"Development Status :: 5 - Production/Stable",
"Framework :: Django",
"Intended Audience :: Developers",
"License :: OSI Approved :: Apache License 2.0",
"Operating System :: OS Independent",
"Topic :: Software Development",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.4",
],
)

0 comments on commit b59de8e

Please sign in to comment.