编程语言
首页 > 编程语言> > Python:通过海报发布stringIO内的数据?

Python:通过海报发布stringIO内的数据?

作者:互联网

params = {'file': open("test.txt", "rb"), 'name': 'upload test'}
datagen, headers = poster.encode.multipart_encode(params)
request = urllib2.Request(upload_url, datagen, headers)
result = urllib2.urlopen(request)

我使用海报库来发布HTTP.它运作良好.我对此感到满意.

但是我想尝试一些.如上所示,要发送文件数据,我必须打开一个文件.但是有没有办法不制作一个真实的文件呢?我们可以使用STREAM(例如StringIO)来处理文件之类的数据,对吗?但是,我对海报不太了解.因此,我想知道在海报上使用STREAM的方法.

添加

实际上,我尝试过发布图像数据.我写在下面

from PyQt4 import QtCore, QtGui
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers
import urllib2, os

register_openers()
app = QtGui.QApplication(sys.argv)
pixmap = QtGui.QPixmap("c:/test_img.png")
byte_array = QtCore.QByteArray()
buffer = QtCore.QBuffer(byte_array)
buffer.open(QtCore.QIODevice.WriteOnly)
pixmap.save(buffer, "PNG")
from cStringIO import StringIO
datagen, headers = multipart_encode({"image": StringIO(str(byte_array.toBase64()))})
request = urllib2.Request(upload_url, datagen, headers)
_rnt = urllib2.urlopen(request)

但是,我收到此错误:

Traceback (most recent call last):
  File "<pyshell#25>", line 1, in <module>
    _rnt = urllib2.urlopen(request)
  File "C:\Python26\lib\urllib2.py", line 126, in urlopen
    return _opener.open(url, data, timeout)
  File "C:\Python26\lib\urllib2.py", line 397, in open
    response = meth(req, response)
  File "C:\Python26\lib\urllib2.py", line 510, in http_response
    'http', request, response, code, msg, hdrs)
  File "C:\Python26\lib\urllib2.py", line 435, in error
    return self._call_chain(*args)
  File "C:\Python26\lib\urllib2.py", line 369, in _call_chain
    result = func(*args)
  File "C:\Python26\lib\urllib2.py", line 518, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
HTTPError: HTTP Error 500: Internal Server Error

解决方法:

文件参数是您传递文件对象的位置.那么,如果传递一个类似文件的对象怎么办?

>>> params = {'file': cStringIO.StringIO('upload test data'), 'name': 'upload test'}
>>> datagen, headers = poster.encode.multipart_encode(params)
>>> headers
{'Content-Length': '317', 'Content-Type': 'multipart/form-data; boundary=0c56082b1e134424a918b2b083391467'}

看起来很有效.

the documentation说什么?

Values are either strings parameter values, or file-like objects to use as the parameter value. The file-like objects must support .read() and either .fileno() or both .seek() and .tell().

因此,您可以使用StringIO对象,因为它们支持seek()和tell().

但是您不必.您应该能够只使用原始字符串.让我们尝试一下,看看:

>>> params = {'file': 'upload test data', 'name': 'upload test'}
>>> datagen, headers = poster.encode.multipart_encode(params)
>>> headers
{'Content-Length': '317', 'Content-Type': 'multipart/form-data; boundary=0c56082b1e134424a918b2b083391467'}

看看,文档是正确的.

标签:post,stringio,python
来源: https://codeday.me/bug/20191031/1977380.html