Skip to main content
 首页 » 编程设计

python之使用 file.write 接口(interface)上传文件

2025年05月04日10lonelyxmas

我从未在 Python 中看到过这一点,我很感兴趣是否有任何东西可以让您使用写入接口(interface)发送文件(例如 HTTP PUT 或 POST)?我只见过一个读取接口(interface),您可以在其中传递文件名或 file 对象(urllib、请求等)

当然,我可能出于充分的理由从未见过这个,我也很想知道。

请您参考如下方法:

虽然它在较高层次上看起来很有意义,但让我们尝试将文件接口(interface)映射到 HTTP 动词:

file interface   http 
------------------------ 
read             GET 
                 HEAD 
------------------------ 
write            POST 
                 PUT 
                 PATCH 
------------------------ 
?                DELETE 
                 OPTIONS 

如您所见,文件接口(interface)与任何 RESTful 接口(interface)所需的 HTTP 动词集之间没有明确的映射。当然,您可能会破解一个仅使用 GET(读取)和 POST(写入)的实现,但这会中断您需要扩展它以支持的时间任何其他 HTTP 动词。

根据评论编辑:

我自己没试过,但似乎在深处(http/client.py),如果数据实现read,它会这样读取:

        while 1: 
            datablock = data.read(blocksize) 
            if not datablock: 
                break 
            if encode: 
                datablock = datablock.encode("iso-8859-1") 
            self.sock.sendall(datablock) 

不过请注意这样做可能会影响性能:

# If msg and message_body are sent in a single send() call, 
# it will avoid performance problems caused by the interaction 
# between delayed ack and the Nagle algorithm. However, 
# there is no performance gain if the message is larger 
# than MSS (and there is a memory penalty for the message 
# copy). 

所以是的,您应该能够将文件对象作为 data 参数传递。