我正在将视频发布到 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
我上传视频的方式是传递 json 格式的数据。
class GetData(webapp2.RequestHandler):
def post(self):
data = self.request.get('file')
然后我所做的就是一个 request.put(url, data=data)。这工作顺利。
如何将 Python 识别为 str 的数据转换为类似文件的对象?