Newer
Older
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import logging
import time
import requests
from odoo.exceptions import ValidationError
try:
from urllib.parse import urljoin
except ImportError:
from urlparse import urljoin
logger = logging.getLogger(__name__)
class Redner(object):
def __init__(self, api_key, server_url, account):
"""Initialize the API client
Args:
api_key(str): provide your Redner API key.
server_url(str): Redner server URL.
"""
self.session = requests.session()
self.account = account
self.server_url = server_url
self.api_key = api_key
self.templates = Templates(self)
def call(self, path, http_verb="post", **params):
"""Call redner with the specified paramters.
Delegate to ``call_impl``; this is a wrapper to have some retries
before giving up as redner sometimes mistakenly rejects our queries.
"""
MAX_REDNERD_TRIES = 3
for retry_counter in range(MAX_REDNERD_TRIES):
try:
return self.call_impl(path, http_verb=http_verb, **params)
except Exception as error:
if retry_counter == MAX_REDNERD_TRIES - 1:
raise error
def call_impl(self, path, http_verb="post", **params):
"""Actually make the API call with the given params -
this should only be called by the namespace methods
Args:
path(str): URL path to query, eg. '/template/'
http_verb(str): http verb to use, default: 'post'
params(dict): json payload
"""
if not self.server_url:
raise ValidationError(
"Cannot find redner config url. "
"Please add it in odoo.conf or in ir.config_parameter"
)
endpoint = urljoin(self.server_url, path)
_http_verb = http_verb.upper()
logger.info("%s to %s: %s" % (_http_verb, endpoint, params))
start = time.time()
r = getattr(self.session, http_verb, "post")(
endpoint, json=params, headers={"Rednerd-API-Key": self.api_key}
)
complete_time = time.time() - start
logger.info(
"Received %s in %.2fms: %s"
% (r.status_code, complete_time * 1000, r.text)
)
try:
response = r.json()
except Exception:
# If we cannot decode JSON then it's an API error
# having response as text could help debuggin with sentry
response = r.text
if not str(r.status_code).startswith("2"):
logger.error("Bad response from Redner: %s" % response)
raise ValidationError("Unexpected redner error: %r" % response)
return r.json()
def ping(self):
"""Try to establish a connection to server"""
conn = self.session.get(self.server_url)
if conn.status_code != requests.codes.ok:
raise ValidationError("Cannot Establish a connection to server")
return conn
def __repr__(self):
return "<Redner %s>" % self.api_key
class Templates(object):
def __init__(self, master):
self.master = master
def render(
self,
template_id,
data,
accept="text/html",
body_format="base64",
metadata=None,
):
"""Inject content and optionally merge fields into a template,
returning the HTML that results.
Args:
template_id(str): Redner template ID.
data(dict): Template variables.
accept: format of a request or response body data.
body_format (string): The body attribute format.
Can be 'text' or 'base64'. Default 'base64',
metadata (dict):
Returns:
Array of dictionaries: API response
"""
if isinstance(data, dict):
data = [data]
params = {
"accept": accept,
"data": data,
"template": {"account": self.master.account, "name": template_id},
"body-format": body_format,
"metadata": metadata or {},
}
return self.master.call("v1/render", http_verb="post", **params)
def account_template_add(
self,
language,
body,
locale="fr_FR",
version="N/A",
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
):
"""Store template in Redner
Args:
name(string): Name of your template. This is to help the user find
its templates in a list.
language(string): Language your template is written with.
Can be mustache or handlebar
body(string): Content you want to create.
produces(string): Can be text/html or
body_format (string): The body attribute format. Can be 'text' or
'base64'. Default 'base64'
locale(string):
version(string):
Returns:
name(string): Redner template Name.
"""
params = {
"name": name,
"language": language,
"body": body,
"produces": produces,
"body-format": body_format,
"locale": locale,
"version": version,
}
res = self.master.call(
"v1/template/%s" % self.master.account, http_verb="post", **params
)
return res["name"]
def account_template_update(
self,
produces="text/html",
body_format="text",
locale="fr",
template_id(string): Name of your template.
This is to help the user find its templates in a list.
name(string): The new template name (optional)
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
language(string): Language your template is written with.
Can be mustache or handlebar
body(string): Content you want to create.
produces(string): Can be text/html or
body_format (string): The body attribute format. Can be 'text' or
'base64'. Default 'base64'
locale(string):
version(string):
Returns:
name(string): Redner template Name.
"""
params = {
"name": name,
"language": language,
"body": body,
"produces": produces,
"body-format": body_format,
"locale": locale,
"version": version,
}
res = self.master.call(
"v1/template/%s/%s" % (self.master.account, template_id),
http_verb="put",
**params
)
return res["name"]
def account_template_delete(self, name):
"""Delete a given template name
Args:
name(string): Redner template Name.
Returns:
dict: API response.
"""
return self.master.call(
"v1/template/%s/%s" % (self.master.account, name),
http_verb="delete",
)