我正在向Google Cloud存儲桶發佈視頻,並且有一個簽名的PUT url會訣竅。但是,如果文件大小大於10MB,它將無法工作,所以我找到了一個開放源代碼,可以讓我做到這一點,但它使用像對象一樣的文件。將str數據轉換爲Python中的文件對象
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)。這工作無縫。
如何將這些數據轉換爲像對象那樣的文件作爲str的數據?
謝謝,這是解決方案。現在我只需要弄清楚爲什麼我得到了400的迴應。但是,謝謝你,這是我正在尋找的。 –