python请求api不发布内存中的压缩文件

时间:2016-02-18 19:30:42

标签: python python-2.7 python-requests zipfile

问题:我怎样才能让它发挥作用

我正在尝试使用python requests api将压缩文件发送到服务器。我在文档中看到了这个方法:

r = requests.post(url, files=open('foo.png', 'rb'))

但我正在做的事情之间的区别在于我所拥有的压缩文件在内存中,只有一个python对象,没有创建文件的物理压缩版本:

我正在使用zipfile api,这就是我创建zip文件的方式:

inMemoryOutputFile = StringIO()
outFile = zipfile.ZipFile(inMemoryOutputFile, "w",
        compression=zipfile.ZIP_DEFLATED)

并尝试以下内容(写入zip文件后):

r = requests.post(url, outFile)

然而它不起作用,看起来该对象未被识别为参数。这是堆栈跟踪

Traceback (most recent call last):   File
"/Users/abdulahmad/Desktop/upload-script-ve/bin/cogs", line 11, in
<module>
    sys.exit(main())   File "/Users/abdulahmad/Desktop/upload-script-ve/lib/python2.7/site-packages/cogs/run.py",
line 396, in main
    return run(sys.argv)   File "/Users/abdulahmad/Desktop/upload-script-ve/lib/python2.7/site-packages/cogs/run.py",
line 384, in run
    return instance()   File "/Users/abdulahmad/Desktop/upload-script-ve//src/ctl.py",
line 53, in __call__
    handler = uploader(self.url, self.file)   File "/Users/abdulahmad/Desktop/upload-script-ve//src/uploader.py",
line 24, in __call__
    response = self.session.post(url, files=payload) 

#this is where I'm adding the file (the payload)

File "/Users/abdulahmad/Desktop/upload-script-ve/lib/python2.7/site-packages/requests/sessions.py",
line 511, in post
    return self.request('POST', url, data=data, json=json, **kwargs)   File
"/Users/abdulahmad/Desktop/upload-script-ve/lib/python2.7/site-packages/requests/sessions.py",
line 454, in request
    prep = self.prepare_request(req)   File "/Users/abdulahmad/Desktop/upload-script-ve/lib/python2.7/site-packages/requests/sessions.py",
line 388, in prepare_request
    hooks=merge_hooks(request.hooks, self.hooks),   File "/Users/abdulahmad/Desktop/upload-script-ve/lib/python2.7/site-packages/requests/models.py",
line 296, in prepare
    self.prepare_body(data, files, json)   File "/Users/abdulahmad/Desktop/upload-script-ve/lib/python2.7/site-packages/requests/models.py",
line 447, in prepare_body
    (body, content_type) = self._encode_files(files, data)   File "/Users/abdulahmad/Desktop/upload-script-ve/lib/python2.7/site-packages/requests/models.py",
line 150, in _encode_files
    fdata = fp.read() TypeError: read() takes at least 2 arguments (1 given)

实际代码:

inMemoryOutputFile = StringIO()

    parentDir, dirToZip = os.path.split(dirPath)
    def trimPath(path):
        archivePath = path.replace(parentDir, "", 1)
        if parentDir:
            archivePath = archivePath.replace(os.path.sep, "", 1)
        if not includeDirInZip:
            archivePath = archivePath.replace(dirToZip + os.path.sep, "", 1)
        return os.path.normcase(archivePath)

    outFile = zipfile.ZipFile(inMemoryOutputFile, "w",
        compression=zipfile.ZIP_DEFLATED)

    for (archiveDirPath, dirNames, fileNames) in os.walk(dirPath):
        for fileName in fileNames:
            filePath = os.path.join(archiveDirPath, fileName)
            outFile.write(filePath, trimPath(filePath))
        if not fileNames and not dirNames:
            zipInfo = zipfile.ZipInfo(trimPath(archiveDirPath) + "/")

            outFile.writestr(zipInfo, "")
    outFile.close()
    return outFile

1 个答案:

答案 0 :(得分:2)

您需要将StringIO缓冲区传递给requests,而不是ZipFileZipFile.read("somefile.txt")从存档中读取未压缩的文件,它不读取压缩的二进制流。 read需要1个参数,这就是您收到奇怪错误消息的原因。在发布之前回滚文件或POST数据为空。

此示例显示了工作流程。

import zipfile
from cStringIO import StringIO
import requests
import logging

logging.basicConfig(level=logging.DEBUG)

buf = StringIO()
with zipfile.ZipFile(buf, "w", compression=zipfile.ZIP_DEFLATED) as zippy:
    zippy.write('somefile.txt')
buf.seek(0)

requests.post('http://localhost:8080', 
    headers = {'content-type': 'application/octet-stream'},
    data=buf)