django-email-testview


Namedjango-email-testview JSON
Version 0.1.2 PyPI version JSON
download
home_pagehttps://github.com/theartling/django-email-testview/
SummaryStrongly opinionated way to handle emails with Django
upload_time2023-01-03 13:09:53
maintainer
docs_urlNone
authorMartin Brochhaus
requires_python
licenseMIT License
keywords
VCS
bugtrack_url
requirements Django
Travis-CI No Travis.
coveralls test coverage
            # Django Email Testview

This is a highly opinionated little helper tool that helps us at The Artling to
test our email templates. It is quite possible that you will not be able to use
this in your project because it would require you to refactor tons of your code,
which might not be worth the effort.

However, you could always add this app to your project and then just use it for
new email templates and you can gradually migrate old emails to this new
framework over time.

## The problem

Our app sends tons of different email notifications to our users and our admins.
In the worst situation, a developer would click around in the frontend until
they reach the point where a certain email would be triggered. Then keep
refreshing GMail until the email arrives, look at it, then make a few changes,
then trigger it again. This is an incredibly frustrating and time consuming
workflow.

## The solution

We would like to have one view `/emails/test/` which can only be accessed by
admins and which shows a list of all emails that are registered in the system.
When you click at one of those links, it should show a view that simply renders
that email template in the browser.

The only tricky part with this is that most emails need quite complicated
template contexts in order to render all the stuff that should be shown in the
email. It would be nice if this "email testview" would not just render the
template with fixture values, but even call the real function that prepares the
email context, so that this view would crash in the case when there are bugs in
that function.

## The opinionated approach

With this app, you will create your emails as follows:

### Step 1: Create your email template

Let's say you have an app called `contact`. First, you will create the email
templates in that app:

```
contact
    └── templates
        └── contact
            └── email
                ├── body
                │   └── new_contact_request.html
                └── subject
                    └── new_contact_request.html
```

By convention, the files for the email `body` and the email `subject` must have
an identical name and they must be located in an
`appname/templates/appname/email/` folder .

### Step 2: Create your email function

Just like many Django apps have a `models.py` or an `admin.py`, you will now
add an `emails.py` to your app. It will look something like this:

```py
from email_testview.registry import registry


def new_contact_email_fixtures():
    return ['Test message'], {'first_name': 'First', 'last_name': 'Last'}


def new_contact_email(message, first_name=None, last_name=None):
    return {
        'context': {
            'message': message,
            'first_name': first_name,
            'last_name': last_name,
        },
        # These are optional:
        # 'from_email': 'someone@example.com',  # default: settings.FROM_EMAIL
        # 'recipients': ['someone@example.com'],  # default: the first from settings.ADMINS
    }


registry.register('contact.new_contact_email', new_contact_email, new_contact_email_fixtures)
```

You can see that writing an email consists of three parts:

1. First you write your actual email function (here: `new_contact_email()`).
   Your email function will probably take in some arguments, usually some
   instance from your database or other values that should be rendered in the
   email. This function simply returns the context that shall be passed into the
   email template.
2. Next you write a fixtures function that will return exactly the `*args` and
   `**kwargs` that your email function needs. We use tools like `mixer` here
   (with `commit=False`) in order to create complex object structures (like a
   user's cart with cart items and all that) with just a few lines of code.
3. Finally you register this email to a central registry, similar how you would
   also register your Django admin classes.

**Why do we like this?**

The nice thing about all this is that whenever someone needs to design a new
email, they will probably look into an already existing `emails.py` and quickly
understand this three-step-pattern, then copy and paste one old email and just
change around all the values as needed. Also, whenever you need to change the
context for an old email, you will have the corresponding fixtures function
right above it and you will remember that you might have to change the fixtures
as well.

Another cool thing is, that in both cases, when the server actually sends an
email and when the developer looks at the email in the `/emails/test/` view, the
exact same email function will be called, so if there are bugs in that email
function, it is more likely that the developer is going to see them while
designing the email.

### Step 3: Send your email

This app comes with a `send_mail` function that you can use like this:

```py
from email_testview.utils import send_mail

message = 'Some message'
first_name = 'First'
last_name = 'Last'
send_mail('contact.new_contact_email', message, first_name=first_name, last_name=last_name)
```

The `send_mail` function will pass the given `*args` and `**kwargs` into your
email function `new_contact_email()`. It will then look at the email identifier
that you have given (`contact.new_contact_email`) and figure out the template
name.

This means: Your email function name and the template name must be identical!

### Step 4: Profit

You can now login as an admin, go to `/emails/test/` click at the email that you
want to modify, see the email in your browser and start modifying the html and
the css and see the results in your browser immediately.

# Installation

Install via pip:

```
pip install django-email-testview
```

Add to your `INSTALLED_APPS` settings:

```py
INSTALLED_APPS = [
    # ...
    'email_testview',
]
```

Add to your main `urls.py`:

```py
urlpatterns = [
    re_path(r'admin/', admin.site.urls),
    # ...
    re_path(r'emails/', include('email_testview.urls')),
]
```

Add to your `local_settings.py`:

```py
ENVIRONMENT = 'local'
```

This is just another safeguard to make sure that this view can never be accessed
on a production environment. Our production environments have this setting set
to `prod` and when that is the case, then the view will return a 403 error..

Create an `emails.py` file in one of your apps, as described above. Make sure
that you are logged in as an admin user and visit `/emails/test/`.

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/theartling/django-email-testview/",
    "name": "django-email-testview",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "",
    "maintainer_email": "",
    "keywords": "",
    "author": "Martin Brochhaus",
    "author_email": "mbrochh@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/82/0a/798109fab4be62c4547bc0ff2133fa4b664799863d039df9a90083630053/django-email-testview-0.1.2.tar.gz",
    "platform": null,
    "description": "# Django Email Testview\n\nThis is a highly opinionated little helper tool that helps us at The Artling to\ntest our email templates. It is quite possible that you will not be able to use\nthis in your project because it would require you to refactor tons of your code,\nwhich might not be worth the effort.\n\nHowever, you could always add this app to your project and then just use it for\nnew email templates and you can gradually migrate old emails to this new\nframework over time.\n\n## The problem\n\nOur app sends tons of different email notifications to our users and our admins.\nIn the worst situation, a developer would click around in the frontend until\nthey reach the point where a certain email would be triggered. Then keep\nrefreshing GMail until the email arrives, look at it, then make a few changes,\nthen trigger it again. This is an incredibly frustrating and time consuming\nworkflow.\n\n## The solution\n\nWe would like to have one view `/emails/test/` which can only be accessed by\nadmins and which shows a list of all emails that are registered in the system.\nWhen you click at one of those links, it should show a view that simply renders\nthat email template in the browser.\n\nThe only tricky part with this is that most emails need quite complicated\ntemplate contexts in order to render all the stuff that should be shown in the\nemail. It would be nice if this \"email testview\" would not just render the\ntemplate with fixture values, but even call the real function that prepares the\nemail context, so that this view would crash in the case when there are bugs in\nthat function.\n\n## The opinionated approach\n\nWith this app, you will create your emails as follows:\n\n### Step 1: Create your email template\n\nLet's say you have an app called `contact`. First, you will create the email\ntemplates in that app:\n\n```\ncontact\n    \u2514\u2500\u2500 templates\n        \u2514\u2500\u2500 contact\n            \u2514\u2500\u2500 email\n                \u251c\u2500\u2500 body\n                \u2502\u00a0\u00a0 \u2514\u2500\u2500 new_contact_request.html\n                \u2514\u2500\u2500 subject\n                    \u2514\u2500\u2500 new_contact_request.html\n```\n\nBy convention, the files for the email `body` and the email `subject` must have\nan identical name and they must be located in an\n`appname/templates/appname/email/` folder .\n\n### Step 2: Create your email function\n\nJust like many Django apps have a `models.py` or an `admin.py`, you will now\nadd an `emails.py` to your app. It will look something like this:\n\n```py\nfrom email_testview.registry import registry\n\n\ndef new_contact_email_fixtures():\n    return ['Test message'], {'first_name': 'First', 'last_name': 'Last'}\n\n\ndef new_contact_email(message, first_name=None, last_name=None):\n    return {\n        'context': {\n            'message': message,\n            'first_name': first_name,\n            'last_name': last_name,\n        },\n        # These are optional:\n        # 'from_email': 'someone@example.com',  # default: settings.FROM_EMAIL\n        # 'recipients': ['someone@example.com'],  # default: the first from settings.ADMINS\n    }\n\n\nregistry.register('contact.new_contact_email', new_contact_email, new_contact_email_fixtures)\n```\n\nYou can see that writing an email consists of three parts:\n\n1. First you write your actual email function (here: `new_contact_email()`).\n   Your email function will probably take in some arguments, usually some\n   instance from your database or other values that should be rendered in the\n   email. This function simply returns the context that shall be passed into the\n   email template.\n2. Next you write a fixtures function that will return exactly the `*args` and\n   `**kwargs` that your email function needs. We use tools like `mixer` here\n   (with `commit=False`) in order to create complex object structures (like a\n   user's cart with cart items and all that) with just a few lines of code.\n3. Finally you register this email to a central registry, similar how you would\n   also register your Django admin classes.\n\n**Why do we like this?**\n\nThe nice thing about all this is that whenever someone needs to design a new\nemail, they will probably look into an already existing `emails.py` and quickly\nunderstand this three-step-pattern, then copy and paste one old email and just\nchange around all the values as needed. Also, whenever you need to change the\ncontext for an old email, you will have the corresponding fixtures function\nright above it and you will remember that you might have to change the fixtures\nas well.\n\nAnother cool thing is, that in both cases, when the server actually sends an\nemail and when the developer looks at the email in the `/emails/test/` view, the\nexact same email function will be called, so if there are bugs in that email\nfunction, it is more likely that the developer is going to see them while\ndesigning the email.\n\n### Step 3: Send your email\n\nThis app comes with a `send_mail` function that you can use like this:\n\n```py\nfrom email_testview.utils import send_mail\n\nmessage = 'Some message'\nfirst_name = 'First'\nlast_name = 'Last'\nsend_mail('contact.new_contact_email', message, first_name=first_name, last_name=last_name)\n```\n\nThe `send_mail` function will pass the given `*args` and `**kwargs` into your\nemail function `new_contact_email()`. It will then look at the email identifier\nthat you have given (`contact.new_contact_email`) and figure out the template\nname.\n\nThis means: Your email function name and the template name must be identical!\n\n### Step 4: Profit\n\nYou can now login as an admin, go to `/emails/test/` click at the email that you\nwant to modify, see the email in your browser and start modifying the html and\nthe css and see the results in your browser immediately.\n\n# Installation\n\nInstall via pip:\n\n```\npip install django-email-testview\n```\n\nAdd to your `INSTALLED_APPS` settings:\n\n```py\nINSTALLED_APPS = [\n    # ...\n    'email_testview',\n]\n```\n\nAdd to your main `urls.py`:\n\n```py\nurlpatterns = [\n    re_path(r'admin/', admin.site.urls),\n    # ...\n    re_path(r'emails/', include('email_testview.urls')),\n]\n```\n\nAdd to your `local_settings.py`:\n\n```py\nENVIRONMENT = 'local'\n```\n\nThis is just another safeguard to make sure that this view can never be accessed\non a production environment. Our production environments have this setting set\nto `prod` and when that is the case, then the view will return a 403 error..\n\nCreate an `emails.py` file in one of your apps, as described above. Make sure\nthat you are logged in as an admin user and visit `/emails/test/`.\n",
    "bugtrack_url": null,
    "license": "MIT License",
    "summary": "Strongly opinionated way to handle emails with Django",
    "version": "0.1.2",
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "27b0b2ea187ceac152fba4fc2f01abf746b5170c528fcc1fc61f95a3a8ee7371",
                "md5": "96587ef3e535dfc55e2919adfdd5c9b6",
                "sha256": "e6a7d8e121b6eed9a993ad868d9f2fe9b0972793d167ac8d0fd39c0f9217e87a"
            },
            "downloads": -1,
            "filename": "django_email_testview-0.1.2-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "96587ef3e535dfc55e2919adfdd5c9b6",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": null,
            "size": 7608,
            "upload_time": "2023-01-03T13:09:51",
            "upload_time_iso_8601": "2023-01-03T13:09:51.003828Z",
            "url": "https://files.pythonhosted.org/packages/27/b0/b2ea187ceac152fba4fc2f01abf746b5170c528fcc1fc61f95a3a8ee7371/django_email_testview-0.1.2-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "820a798109fab4be62c4547bc0ff2133fa4b664799863d039df9a90083630053",
                "md5": "b7a6b213e1b3aff7dc1c80ff1593442e",
                "sha256": "cbc07562253c390387141d8090289bb48f6c92db5500a6c202a807e7c9ae5a01"
            },
            "downloads": -1,
            "filename": "django-email-testview-0.1.2.tar.gz",
            "has_sig": false,
            "md5_digest": "b7a6b213e1b3aff7dc1c80ff1593442e",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 6882,
            "upload_time": "2023-01-03T13:09:53",
            "upload_time_iso_8601": "2023-01-03T13:09:53.037598Z",
            "url": "https://files.pythonhosted.org/packages/82/0a/798109fab4be62c4547bc0ff2133fa4b664799863d039df9a90083630053/django-email-testview-0.1.2.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-01-03 13:09:53",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "github_user": "theartling",
    "github_project": "django-email-testview",
    "travis_ci": false,
    "coveralls": true,
    "github_actions": false,
    "requirements": [
        {
            "name": "Django",
            "specs": [
                [
                    ">=",
                    "2"
                ]
            ]
        }
    ],
    "test_requirements": [
        {
            "name": "ipdb",
            "specs": []
        },
        {
            "name": "fabric",
            "specs": []
        },
        {
            "name": "mixer",
            "specs": []
        },
        {
            "name": "pytest-cov",
            "specs": []
        },
        {
            "name": "pytest-django",
            "specs": []
        },
        {
            "name": "pytest",
            "specs": []
        }
    ],
    "lcname": "django-email-testview"
}
        
Elapsed time: 0.23648s