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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
|
import python_http_client
region_host_dict = {'eu':'https://api.eu.sendgrid.com','global':'https://api.sendgrid.com'}
class BaseInterface(object):
def __init__(self, auth, host, impersonate_subuser):
"""
Construct the Twilio SendGrid v3 API object.
Note that the underlying client is being set up during initialization,
therefore changing attributes in runtime will not affect HTTP client
behaviour.
:param auth: the authorization header
:type auth: string
:param impersonate_subuser: the subuser to impersonate. Will be passed
by "On-Behalf-Of" header by underlying
client. See
https://sendgrid.com/docs/User_Guide/Settings/subusers.html
for more details
:type impersonate_subuser: string
:param host: base URL for API calls
:type host: string
"""
from . import __version__
self.auth = auth
self.impersonate_subuser = impersonate_subuser
self.version = __version__
self.useragent = 'sendgrid/{};python'.format(self.version)
self.host = host
self.client = python_http_client.Client(
host=self.host,
request_headers=self._default_headers,
version=3)
@property
def _default_headers(self):
"""Set the default header for a Twilio SendGrid v3 API call"""
headers = {
"Authorization": self.auth,
"User-Agent": self.useragent,
"Accept": 'application/json'
}
if self.impersonate_subuser:
headers['On-Behalf-Of'] = self.impersonate_subuser
return headers
def reset_request_headers(self):
self.client.request_headers = self._default_headers
def send(self, message):
"""Make a Twilio SendGrid v3 API request with the request body generated by
the Mail object
:param message: The Twilio SendGrid v3 API request body generated by the Mail
object
:type message: Mail
"""
if not isinstance(message, dict):
message = message.get()
return self.client.mail.send.post(request_body=message)
def set_sendgrid_data_residency(self, region):
"""
Client libraries contain setters for specifying region/edge.
This supports global and eu regions only. This set will likely expand in the future.
Global is the default residency (or region)
Global region means the message will be sent through https://api.sendgrid.com
EU region means the message will be sent through https://api.eu.sendgrid.com
:param region: string
:return:
"""
if region in region_host_dict.keys():
self.host = region_host_dict[region]
if self._default_headers is not None:
self.client = python_http_client.Client(
host=self.host,
request_headers=self._default_headers,
version=3)
else:
raise ValueError("region can only be \"eu\" or \"global\"")
|