Skip to content

requests: allow str and bytes for fileobj in files parameter#7728

Merged
AlexWaygood merged 2 commits into
python:masterfrom
milanboers:requests-sessions-fix
Apr 28, 2022
Merged

requests: allow str and bytes for fileobj in files parameter#7728
AlexWaygood merged 2 commits into
python:masterfrom
milanboers:requests-sessions-fix

Conversation

@milanboers
Copy link
Copy Markdown
Contributor

@milanboers milanboers commented Apr 27, 2022

Some people are having issues with this one, see #7724

Documentation says to pass a "file-like-object". Implementation allows for str, bytes, bytearray or anything that implements .read().
Left bytearray out for now because urllib3 documents str and bytes as valid in RequestField in the next major version.

Resolves #7724

Copy link
Copy Markdown
Member

@AlexWaygood AlexWaygood left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The implementation looks like it can be str, bytes, or anything with a .read() method: https://github.com/psf/requests/blob/31a89d9c8463c3394ca00f408f4b86d814421a09/requests/models.py#L160-L161

Rather than using IO[Any], we could make it even more permissive, and just use _typeshed.SupportsRead:

class SupportsRead(Protocol[_T_co]):
def read(self, __length: int = ...) -> _T_co: ...

@milanboers
Copy link
Copy Markdown
Contributor Author

Good one, done! Kept the IO in _Data as-is, because it also needs .tell() there.

@AlexWaygood
Copy link
Copy Markdown
Member

I've confirmed that this annotation will allow objects with a .read() returning bytes, and objects with a .read() returning str: https://mypy-play.net/?mypy=latest&python=3.10&gist=c5afaf626edee4068ca05bc806f33f64

Copy link
Copy Markdown
Member

@AlexWaygood AlexWaygood left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

@AlexWaygood AlexWaygood merged commit df06044 into python:master Apr 28, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

requests: Allow files={"example": ("filename", bytes)}

2 participants