Abstract away treating a file as a stream

Makes upload_file cleaner (context manager instead of try-finally)
and helps keep the logic "we may own this stream and need to close
it or not" separated.

It can be overengineered to allow nesting the same instance in
context managers and also provide implementations for synchronous
context managers but it adds quite a bit of unnecessary complexity
for the time being. YAGNI.
This commit is contained in:
Lonami Exo
2020-09-14 16:20:44 +02:00
parent 9ec5707c32
commit 219b4ecb77
3 changed files with 147 additions and 80 deletions

View File

@@ -611,7 +611,9 @@ def _get_metadata(file):
# The parser may fail and we don't want to crash if
# the extraction process fails.
try:
# Note: aiofiles are intentionally left out for simplicity
# Note: aiofiles are intentionally left out for simplicity.
# `helpers._FileStream` is async only for simplicity too, so can't
# reuse it here.
if isinstance(file, str):
stream = open(file, 'rb')
elif isinstance(file, bytes):