/
async.py
49 lines (35 loc) · 1.09 KB
/
async.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# -*- encoding: utf-8 -*-
from __future__ import unicode_literals
import functools
from concurrent.futures import Future, ThreadPoolExecutor
from django.db import connection
from . import base
from .. import core
# TODO: parametrize this
executor = ThreadPoolExecutor(max_workers=1)
def _close_connection_on_finish(function):
"""
Decorator for future task, that closes
Django database connection when it ends.
"""
@functools.wraps(function)
def _decorator(*args, **kwargs):
try:
return function(*args, **kwargs)
finally:
connection.close()
return _decorator
class EmailBackend(base.BaseEmailBackend):
"""
Asynchronous email back-end that uses a
thread pool for sending emails.
"""
def send_messages(self, email_messages):
if len(email_messages) == 0:
future = Future()
future.set_result(0)
return future
@_close_connection_on_finish
def _send(messages):
return core._send_messages(messages)
return executor.submit(_send, email_messages)