Skip to content

Commit

Permalink
fix(fields.py): fix File field bug when get an empty value (#301)
Browse files Browse the repository at this point in the history
* fix(fields.py): fix `File` field bug when get an empty value

* perf(fields.py): compatible with `python3.8`

* Update changelog

---------

Co-authored-by: Steven Loria <sloria1@gmail.com>
  • Loading branch information
uncle-lv and sloria committed Mar 18, 2024
1 parent b5b9498 commit 4785db3
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 0 deletions.
8 changes: 8 additions & 0 deletions CHANGELOG.rst
@@ -1,6 +1,14 @@
Changelog
=========

1.2.1 (unreleased)
******************

Bug fixes:

* Fix `File` field when it receives an empty value (:pr:`301`, :issue:`apiflask/apiflask#551`).
Thanks :user:`uncle-lv`.

1.2.0 (2024-02-05)
******************

Expand Down
12 changes: 12 additions & 0 deletions src/flask_marshmallow/fields.py
Expand Up @@ -10,6 +10,7 @@

import re
import typing
from collections.abc import Sequence

from flask import current_app, url_for
from marshmallow import fields, missing
Expand Down Expand Up @@ -225,6 +226,17 @@ def __init__(self, *args, **kwargs):

default_error_messages = {"invalid": "Not a valid file."}

def deserialize(
self,
value: typing.Any,
attr: typing.Optional[str] = None,
data: typing.Optional[typing.Mapping[str, typing.Any]] = None,
**kwargs,
):
if isinstance(value, Sequence) and len(value) == 0:
value = missing
return super().deserialize(value, attr, data, **kwargs)

def _deserialize(self, value, attr, data, **kwargs):
from werkzeug.datastructures import FileStorage

Expand Down
4 changes: 4 additions & 0 deletions tests/test_fields.py
Expand Up @@ -2,6 +2,7 @@

import pytest
from flask import url_for
from marshmallow import missing
from marshmallow.exceptions import ValidationError
from werkzeug.datastructures import FileStorage
from werkzeug.routing import BuildError
Expand Down Expand Up @@ -150,6 +151,9 @@ def test_file_field(ma, mockauthor):
result = field.deserialize(fs, mockauthor)
assert result == fs

result = field.deserialize("", mockauthor)
assert result is missing

with pytest.raises(ValidationError, match="Field may not be null."):
field.deserialize(None, mockauthor)

Expand Down

0 comments on commit 4785db3

Please sign in to comment.