Python实现不写硬盘上传文件

2022-10-07,,,

引言

你写了一个 api,接受 client 上传的文件,然后在上传到 oss,你会怎么做?先写硬盘,然后在上传到 oss?太笨了!

你写了一个截图服务,截到的图要上传到 oss,你会怎么做?先写硬盘,在上传到 oss?太笨了!

这篇文章教你重新做人!

文本类型

使用 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())

输出结果如下:

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

再看一个熟悉的:

import io
from loguru import logger
file_like_obj = io.stringio("hahaha")
with file_like_obj as f:
    logger.debug(f.read())

输出结果如下:

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

二进制类型

使用 io.bytesio

使用 requests 把字符串按照文件上传

下面的代码是标准的上传文件的代码:

import requests
import io
response = requests.post('http://localhost:5000/', files={
    'file': open('纵观人类文明史.txt', 'r', encoding='utf-8')
})
print(response.text)

但是我想把 open('纵观人类文明史.txt', 'r', encoding='utf-8') 替换为字符串。为此我想到的办法是把字符串先写到硬盘上,在按照上面的代码上传,可是这太低效率(硬盘太低效率),平白无故多了两次硬盘读写操作,我想直接把内存中的字符串按照文件上传有什么办法吗?

 参考文档

https://docs.python.org/zh-cn/3/library/io.html#io.stringio

以上就是python实现不写硬盘上传文件的详细内容,更多关于python不写硬盘上传文件的资料请关注其它相关文章!

《Python实现不写硬盘上传文件.doc》

下载本文的Word格式文档,以方便收藏与打印。