Skip to content

Commit 31b8bf7

Browse files
add support base64 input
1 parent 128b221 commit 31b8bf7

File tree

1 file changed

+12
-22
lines changed

1 file changed

+12
-22
lines changed

sablon.py

+12-22
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
It expects a multipart/form-data upload containing a .docx document with the
77
name template and a JSON part named context containing variable values.
88
"""
9+
import base64
10+
import json
911
from aiohttp import web
1012
import asyncio
1113
import logging
@@ -22,26 +24,18 @@ async def sablon(request):
2224
form_data = {}
2325
temp_dir = None
2426

25-
if not request.content_type == 'multipart/form-data':
27+
if not request.content_type == 'application/json':
2628
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.',
2830
request.content_type,
2931
)
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.")
3333

34+
data = await request.json()
35+
3436
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"])
4539

4640
if 'context' in form_data and 'template' in form_data:
4741
outfilename = os.path.join(temp_dir, 'output.docx')
@@ -87,13 +81,9 @@ async def sablon(request):
8781

8882

8983
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")))
9787
return filename
9888

9989

0 commit comments

Comments
 (0)