You wrote an api that accepts files uploaded by the client, and then uploads them to oss, what would you do? Write to the hard disk first, then upload to oss? too stupid!

You wrote a screenshot service, and the screenshots are to be uploaded to oss, what would you do? Write to the hard disk first, then upload to oss? too stupid!

This article teaches you to be a human again!

text type

Use io.StringIO

 import io
from loguru import logger


file_like_obj = io.StringIO("hahaha")


logger.debug(file_like_obj)
logger.debug(type(file_like_obj))
logger.debug(getattr(file_like_obj,'read'))
logger.debug(file_like_obj.read())

The output is as follows:

 2022-07-11 21:23:51.206 | DEBUG    | __main__:<module>:8 - <_io.StringIO object at 0x100323eb0>
2022-07-11 21:23:51.206 | DEBUG    | __main__:<module>:9 - <class '_io.StringIO'>
2022-07-11 21:23:51.206 | DEBUG    | __main__:<module>:10 - <built-in method read of _io.StringIO object at 0x100323eb0>
2022-07-11 21:23:51.206 | DEBUG    | __main__:<module>:11 - hahaha

Another familiar one:

 import io
from loguru import logger


file_like_obj = io.StringIO("hahaha")


with file_like_obj as f:
    logger.debug(f.read())

The output is as follows:

 2022-07-11 21:35:04.620 | DEBUG    | __main__:<module>:9 - hahaha

binary type

Use io.BytesIO

Reference article: How does python use requests to upload strings as files?


universe_king
3.4k 声望680 粉丝