6
6
It expects a multipart/form-data upload containing a .docx document with the
7
7
name template and a JSON part named context containing variable values.
8
8
"""
9
+ import base64
10
+ import json
9
11
from aiohttp import web
10
12
import asyncio
11
13
import logging
@@ -22,26 +24,18 @@ async def sablon(request):
22
24
form_data = {}
23
25
temp_dir = None
24
26
25
- if not request .content_type == 'multipart/form-data ' :
27
+ if not request .content_type == 'application/json ' :
26
28
logger .info (
27
- 'Bad request. Received content type %s instead of multipart/form-data .' ,
29
+ 'Bad request. Received content type %s instead of application/json .' ,
28
30
request .content_type ,
29
31
)
30
- return web .Response (status = 400 , text = "Multipart request required." )
31
-
32
- reader = await request .multipart ()
32
+ return web .Response (status = 400 , text = "application/json request required." )
33
33
34
+ data = await request .json ()
35
+
34
36
with tempfile .TemporaryDirectory () as temp_dir :
35
- while True :
36
- part = await reader .next ()
37
-
38
- if part is None :
39
- break
40
-
41
- if part .name == 'template' :
42
- form_data ['template' ] = await save_part_to_file (part , temp_dir )
43
- elif part .name == 'context' :
44
- form_data ['context' ] = await part .text ()
37
+ form_data ['template' ] = await save_part_to_file (data ["template_base64" ], temp_dir )
38
+ form_data ['context' ] = json .dumps (data ["context" ])
45
39
46
40
if 'context' in form_data and 'template' in form_data :
47
41
outfilename = os .path .join (temp_dir , 'output.docx' )
@@ -87,13 +81,9 @@ async def sablon(request):
87
81
88
82
89
83
async def save_part_to_file (part , directory ):
90
- filename = os .path .join (directory , part .filename )
91
- with open (os .path .join (directory , filename ), 'wb' ) as file_ :
92
- while True :
93
- chunk = await part .read_chunk (CHUNK_SIZE )
94
- if not chunk :
95
- break
96
- file_ .write (chunk )
84
+ filename = os .path .join (directory , "template.docx" )
85
+ with open (filename , "wb" ) as fh :
86
+ fh .write (base64 .decodebytes (bytes (part , "utf-8" )))
97
87
return filename
98
88
99
89
0 commit comments