-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.py
70 lines (48 loc) · 1.96 KB
/
api.py
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
from io import BytesIO
from pathlib import PurePath
from typing import Union
from fastapi import FastAPI, File
from fastapi.responses import HTMLResponse
from common import FMS_SUBMISSION_TEMPLATE_PATH
from convertor import MOHSampleManifestConversion
"""
REST API
"""
app = FastAPI()
@app.get('/')
def read_root():
return {"hello": "world"}
@app.get('/items/{item_id}')
def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
@app.post('/convert/')
def convert_template(filename: str = "output", template: bytes = File()):
"""
Convert an MOH template to freezeman and return the resulting file.
The POST request body must include a form, and the MOH upload file must
be specified in the form with the key `template`.
The freezeman template is returned as a file download response.
The log is not returned.
TODO Figure out the best way to return the fms file and the log -
either zip them to create a single response, or return the log,
cache the converted file, and provide a second end-point to get the converted file.
"""
fms_template_file_path = PurePath(FMS_SUBMISSION_TEMPLATE_PATH)
output_file_name = PurePath(filename or 'output').stem + ".fms" + ".xlsx"
output_file = BytesIO()
conversion = MOHSampleManifestConversion(
template, fms_template_file_path, output_file
)
conversion.do_conversion()
# We can't use FastApi's FileResponse because it wants a file path as a parameter and the
# output template is in a byte stream, not on disk. Instead, we have to use
# an HTMLResponse and set the headers with the file name.
return HTMLResponse(
content = output_file.getvalue(),
status_code=200,
headers={
"Content-Type": "application/octet-stream",
"Content-Disposition": f"attachment; filename={output_file_name}"
},
media_type='application/octet-stream',
)