在Python中将str数据转换为文件对象

Adr*_*rey 1 python json file object typeconverter

我正在将视频发布到Google Cloud Buckets,并且签名的PUT url可以解决问题。但是,如果文件大小大于10MB,它将无法正常工作,因此我找到了一个开放源代码,可以使用该文件,例如对象。

def read_in_chunks(file_object, chunk_size=65536):
while True:
    data = file_object.read(chunk_size)
    if not data:
        break
    yield data

def main(file, url):
content_name = str(file)
content_path = os.path.abspath(file)
content_size = os.stat(content_path).st_size

print content_name, content_path, content_size

f = open(content_path)

index = 0
offset = 0
headers = {}

for chunk in read_in_chunks(f):
    offset = index + len(chunk)
    headers['Content-Type'] = 'application/octet-stream'
    headers['Content-length'] = content_size
    headers['Content-Range'] = 'bytes %s-%s/%s' % (index, offset, content_size)
    index = offset
    try:
        r = requests.put(url, data=chunk, headers=headers)
        print "r: %s, Content-Range: %s" % (r, headers['Content-Range'])
    except Exception, e:
        print e
Run Code Online (Sandbox Code Playgroud)

我上传视频的方式是传递json格式的数据。

class GetData(webapp2.RequestHandler):
def post(self):
    data = self.request.get('file')
Run Code Online (Sandbox Code Playgroud)

然后,我所做的只是一个request.put(url,data = data)。这无缝地工作。

如何将Python识别为str的数据转换为类似object的文件?

Und*_*ryx 7

在大多数情况下,所谓的“类似文件”的对象只是实现Python缓冲区接口的对象。也就是说,有类似的方法readwriteseek,等等。

缓冲区接口工具的标准库模块称为io。您正在寻找io.StringIOio.BytesIO,具体取决于您拥有的数据类型-如果它是unicode编码的字符串,则应该使用io.StringIO,但是您可能正在使用原始字节流(例如图像文件中),例如而不是文字,io.BytesIO您想要的也是。使用文件时,这open(path, 'r')open(path, 'rb')处理unicode文件和原始处理字节的区别相同。

这两个类都将文件状对象的数据作为第一个参数,因此您只需执行以下操作:

f = io.BytesIO(b'test data')
Run Code Online (Sandbox Code Playgroud)

此后,f将是一个与文件一样工作的对象,除了它的数据保存在内存中而不是磁盘上。