stages/prompt: try to base64 decode file, fallback to keeping value as-is

Signed-off-by: Jens Langhammer <jens.langhammer@beryju.org>
This commit is contained in:
Jens Langhammer 2022-07-08 22:45:31 +02:00
parent ff500b44a6
commit 47434cd62d
2 changed files with 10 additions and 1 deletions

View File

@ -1,5 +1,6 @@
"""prompt models""" """prompt models"""
from base64 import b64decode from base64 import b64decode
from binascii import Error
from typing import Any, Optional from typing import Any, Optional
from urllib.parse import urlparse from urllib.parse import urlparse
from uuid import uuid4 from uuid import uuid4
@ -90,7 +91,11 @@ class InlineFileField(CharField):
_mime, _, enc = header.partition(";") _mime, _, enc = header.partition(";")
if enc != "base64": if enc != "base64":
raise ValidationError("Invalid encoding") raise ValidationError("Invalid encoding")
try:
data = b64decode(encoded.encode()).decode() data = b64decode(encoded.encode()).decode()
except (UnicodeDecodeError, UnicodeEncodeError, ValueError, Error):
LOGGER.info("failed to decode base64 of file field, keeping base64")
data = encoded
return super().to_internal_value(data) return super().to_internal_value(data)

View File

@ -120,6 +120,10 @@ class TestPromptStage(FlowTestCase):
InlineFileField().to_internal_value("data:mine/type;base64,Zm9v"), InlineFileField().to_internal_value("data:mine/type;base64,Zm9v"),
"foo", "foo",
) )
self.assertEqual(
InlineFileField().to_internal_value("data:mine/type;base64,Zm9vqwer"),
"Zm9vqwer",
)
def test_render(self): def test_render(self):
"""Test render of form, check if all prompts are rendered correctly""" """Test render of form, check if all prompts are rendered correctly"""