5

用 Python 通过 api 用 post 上传文件怎么分块?

 1 year ago
source link: https://www.v2ex.com/t/894722
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

V2EX  ›  问与答

用 Python 通过 api 用 post 上传文件怎么分块?

  jlak · 4 小时 0 分钟前 · 364 次点击

很多网站上传东西都有提供 api 可以用 requests 这些库 with open 后发简单的 post 请求就能上传 但是对于小内存机子上传大文件就会爆内存 请问怎么做才能不全部读取到内存再上传

5 条回复    2022-11-12 18:46:54 +08:00

vopin      3 小时 26 分钟前 via iPhone

文件能有多大?大文件一般分段上传吧。

xiangyuecn      2 小时 49 分钟前

此回答多写点,显得不那么菜:

“会爆内存”,明显的 http 请求实现的问题,body 部分并没有哪里约束了必须一次性先生成一个完整的 body 才能发送请求。

稍微聪明那么一点的底层框架代码,都应该读一点发送一点,不存在内存问题(但实现代码会很复杂)。

大文件需要注意的就是失败如何重传的问题,只通过一个请求发送大文件,如果传到 99%的时候失败了,那都得从头再来。

-----

回到问题上,“通过 api 用 post 上传文件怎么分块”,本质上跟 python 不 python 没有一毛钱关系,更多的是需要 api 提供分块上传支持,比如:单次请求可以上传 4MB 的数据块,每次请求发送文件中的指定位置大小的数据块,失败了就重传这 4MB 的数据,最后全部传完了,再调一个 api 通知合并文件。

Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK