bigfile_client_example.py 2.32 KB
Newer Older
Romain Courteaud's avatar
Romain Courteaud committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
input_file = open('input_file.webm', 'r')

import httplib
connection =  httplib.HTTPConnection('192.168.242.68:12001')

import base64
base64string = base64.encodestring('zope:insecure')[:-1]

n = 1 << 20


######################################
# Create new document
######################################

headers = {
    'Authorization': 'Basic %s' % base64string,
    }
connection.request('POST', "/erp5/portal_contributions/newContent?" \
                           "portal_type=Video&filename=input_file.webm&container_path=video_module&data=", "", headers)
result = connection.getresponse()
path = result.getheader("X-Document-Location")
result.close()
path = '/%s' % '/'.join(path.split('/')[3:])
print path

######################################
# Upload chunks
######################################

input_file.seek(0, 2)
end = input_file.tell()

input_file.seek(0)
pos = input_file.tell()

first = True

while pos < end:                                                                
  next_pos = pos + n
  if next_pos > end:
    next_pos = end                                                                  

  body_content = input_file.read(next_pos-pos)
  if first:
    headers = {
        'Authorization': 'Basic %s' % base64string,
        }
  else:
    headers = {
        'Authorization': 'Basic %s' % base64string,
        'Content-Range': 'bytes %i-%i/%i' % (pos, next_pos-1, next_pos),
        }
  connection.request('PUT', path, body_content, headers)
  result = connection.getresponse()

  pos = input_file.tell()
  first = False

######################################
# Download chunks
######################################

output_file = open('output_file.webm', 'wb')
output_file.seek(0)

headers = {
  'Authorization': 'Basic %s' % base64string,
  'Content-Range': 'bytes */*',
}
connection.request('PUT', path, '', headers)
result = connection.getresponse()
filerange = result.getheader('Range')
size = int(filerange.split('-')[1])

pos = 0
while pos < size:

  next_pos = pos + n
  if next_pos > size:
    next_pos = size

  headers = {
    'Authorization': 'Basic %s' % base64string,
    'Range': 'bytes=%s-%s' % (pos, next_pos),
  }
  connection.request('GET', path, '', headers)
  result = connection.getresponse()
  output_file.write(result.read())                                           
  result.close()

  pos = output_file.tell()