-
Notifications
You must be signed in to change notification settings - Fork 114
Expand file tree
/
Copy pathrender_server.py
More file actions
73 lines (56 loc) · 2.2 KB
/
render_server.py
File metadata and controls
73 lines (56 loc) · 2.2 KB
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
import json
import hashlib
import requests
from optional_django.serializers import JSONEncoder
from .exceptions import ReactRenderingError
from . import conf
from .exceptions import RenderServerError
class RenderedComponent(object):
def __init__(self, markup, props):
self.markup = markup
self.props = props
def __str__(self):
return self.markup
def __unicode__(self):
return unicode(self.markup)
class RenderServer(object):
def render(self, path, props=None, to_static_markup=False):
if props is not None:
serialized_props = json.dumps(props, cls=JSONEncoder)
else:
serialized_props = None
if not conf.settings.RENDER:
return RenderedComponent('', serialized_props)
options = {
'path': path,
'serializedProps': serialized_props,
'toStaticMarkup': to_static_markup
}
serialized_options = json.dumps(options)
options_hash = hashlib.sha1(serialized_options.encode('utf-8')).hexdigest()
try:
res = requests.post(
conf.settings.RENDER_URL,
data=serialized_options,
headers={'content-type': 'application/json'},
params={'hash': options_hash}
)
except requests.ConnectionError:
raise RenderServerError('Could not connect to render server at {}'.format(self.url))
if res.status_code != 200:
raise RenderServerError(
'Unexpected response from render server at {} - {}: {}'.format(self.url, res.status_code, res.text)
)
obj = res.json()
markup = obj.get('markup', None)
err = obj.get('error', None)
if err:
if 'message' in err and 'stack' in err:
raise ReactRenderingError(
'Message: {}\n\nStack trace: {}'.format(err['message'], err['stack'])
)
raise ReactRenderingError(err)
if markup is None:
raise ReactRenderingError('Render server failed to return markup. Returned: {}'.format(obj))
return RenderedComponent(markup, serialized_props)
render_server = RenderServer()