|
import os |
|
import tempfile |
|
from fabric.api import task |
|
|
|
def _serialize_body(fp, metadata, payload, boundary='boundary'): |
|
""" |
|
serialize multi-part body |
|
""" |
|
# Metadata |
|
fp.write('\r\n') |
|
fp.write('--%s\r\n' % boundary) |
|
fp.write('Content-Type: application/json; charset=UTF-8\r\n\r\n') |
|
fp.write('%s\r\n' % (json.dumps(metadata))) |
|
# file data |
|
fp.write('--%s\r\n' % boundary) |
|
fp.write('Content-Type: text/csv;\r\n\r\n') |
|
fp.write('%s\r\n' % (payload)) |
|
fp.write('--%s--\r\n\r\n' % boundary) |
|
|
|
@task |
|
def create_file_mp(input_path, parent_folder=None): |
|
""" |
|
upload a csv or excel file to drive and convert it to spreadsheet format |
|
- by default it will have the persmission of parent folders |
|
""" |
|
|
|
bits = input_path.split('/') |
|
if len(bits): |
|
filename = input_path.split('/')[-1] |
|
else: |
|
filename = input_path |
|
|
|
try: |
|
with open(input_path, 'rU') as f: |
|
print "Uploading %s ..." % (filename) |
|
payload = f.read() |
|
except IOError, e: |
|
print "could not open %s. Reason: %s" % (input_path, e) |
|
|
|
# Check if we have the required credentials |
|
check_credentials() |
|
|
|
# metadata |
|
metadata = { |
|
'title': filename, |
|
} |
|
|
|
# Find given folder defaulting the app_config DRIVE_BASE_FOLDER |
|
if parent_folder: |
|
parent_id = search_folder(parent_folder) |
|
else: |
|
parent_id = app_config.DRIVE_BASE_FOLDER |
|
|
|
if parent_id: |
|
metadata['parents'] = [{'id': parent_id}] |
|
|
|
# boundary |
|
b = 'driveboundary' |
|
with tempfile.NamedTemporaryFile() as fp: |
|
print fp.name |
|
_serialize_body(fp, metadata, payload, b) |
|
fp.seek(0) |
|
content_len = os.path.getsize(fp.name) |
|
# Prepare API request |
|
kwargs = { |
|
'credentials': get_credentials(), |
|
'url': UPLOAD_MULTIPART_URL_TEMPLATE, |
|
'method': 'POST', |
|
'headers': { |
|
'Content-Type': 'multipart/related; boundary=%s' % (b), |
|
'Content-Length': content_len}, |
|
'body': fp.read() |
|
} |
|
print kwargs |
|
resp = app_config.authomatic.access(**kwargs) |
|
|
|
if resp.status == 200: |
|
spreadsheet_key = resp.data['id'] |
|
spreadsheet_url = SPREADSHEET_VIEW_TEMPLATE % spreadsheet_key |
|
print 'New spreadsheet created successfully!' |
|
print 'View it at %s' % spreadsheet_url |
|
return True |
|
print resp.content |
|
print ('Error creating spreadsheet (status code %s) with message %s' % |
|
(resp.status, resp.reason)) |
|
return False |