Skip to content

Commit aa7dd39

Browse files
authored
Merge pull request #32 from yanokwa/zip-detect
If file is zipped, assume xlsx
2 parents 9b18f12 + 26b9469 commit aa7dd39

File tree

4 files changed

+25
-3
lines changed

4 files changed

+25
-3
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
11
__pycache__/
2+
.DS_Store

README.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,3 +53,8 @@ A form that converts successfully (with percent encoded id)
5353
```
5454
curl --request POST --header "X-XlsForm-FormId-Fallback: example%40example.org" --data-binary @test/pyxform-clean.xlsx http://127.0.0.1:5001/api/v1/convert
5555
```
56+
57+
A form that converts successfully (with no id, in XLS format)
58+
```
59+
curl --request POST --data-binary @test/pyxform-clean.xls http://127.0.0.1:5001/api/v1/convert
60+
```

app/main.py

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,14 +29,19 @@ def post():
2929
else:
3030
xlsform_formid_fallback = str(uuid())
3131

32+
request_data = request.get_data()
33+
34+
file_ext = ".xlsx" if has_zip_magic_number(request_data) else ".xls"
35+
3236
with TemporaryDirectory() as temp_dir_name:
3337
try:
3438
with open(
3539
os.path.join(temp_dir_name, xlsform_formid_fallback + ".xml"), "w+"
3640
) as xform, open(
37-
os.path.join(temp_dir_name, xlsform_formid_fallback + ".xlsx"), "wb"
41+
os.path.join(temp_dir_name, xlsform_formid_fallback + file_ext),
42+
"wb",
3843
) as xlsform:
39-
xlsform.write(request.get_data())
44+
xlsform.write(request_data)
4045
convert_status = xls2xform.xls2xform_convert(
4146
xlsform_path=str(xlsform.name),
4247
xform_path=str(xform.name),
@@ -75,6 +80,17 @@ def post():
7580
return app
7681

7782

83+
def has_zip_magic_number(buffer):
84+
# https://github.com/h2non/filetype.py/blob/master/filetype/types/archive.py#L54
85+
return (
86+
len(buffer) > 3
87+
and buffer[0] == 0x50
88+
and buffer[1] == 0x4B
89+
and (buffer[2] == 0x3 or buffer[2] == 0x5 or buffer[2] == 0x7)
90+
and (buffer[3] == 0x4 or buffer[3] == 0x6 or buffer[3] == 0x8)
91+
)
92+
93+
7894
def sanitize(string):
7995
return os.path.basename(escape(unquote(string)))
8096

@@ -86,7 +102,7 @@ def response(status=400, result=None, itemsets=None, warnings=None, error=None):
86102
result=result,
87103
itemsets=itemsets,
88104
warnings=warnings,
89-
error=error
105+
error=error,
90106
),
91107
status,
92108
)

test/pyxform-clean.xls

25.5 KB
Binary file not shown.

0 commit comments

Comments
 (0)