【问题标题】:Converting str data to file object in Python在 Python 中将 str 数据转换为文件对象
【发布时间】:2016-07-26 10:43:31
【问题描述】:

我将视频发布到 Google Cloud Buckets,并且签名的 PUT 网址可以解决问题。但是,如果文件大小大于 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

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

class GetData(webapp2.RequestHandler):
def post(self):
    data = self.request.get('file')

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

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

【问题讨论】:

    标签: python json file object typeconverter


    【解决方案1】:

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

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

    两个类都将类文件对象的数据作为第一个参数,所以你只需这样做:

    f = io.BytesIO(b'test data')
    

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

    【讨论】:

    • 谢谢,这就是解决方案。现在我只需要弄清楚为什么我会收到 400 响应。但是谢谢,这就是我想要的。
    【解决方案2】:

    使用StringIO:

    data= StringIO(data)
    read_in_chunks(data)
    

    【讨论】:

    • 此方案在 Python 3 下无法使用,您需要改用 io 模块。有关详细信息,请参阅我的答案。
    • @Underyx...OP 似乎正在使用 Python2!
    • @IronFist 是的,很遗憾。无论哪种方式,Python 2 用户都可能不会专门找到这个问题,因此请务必注意,其中一个答案与两个版本兼容,而另一个则不兼容。
    猜你喜欢
    • 2015-11-14
    • 2019-11-01
    • 2017-04-29
    • 1970-01-01
    • 2021-12-05
    • 2018-12-26
    • 1970-01-01
    • 2020-10-06
    • 2021-01-03
    相关资源
    最近更新 更多