Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Drive API V2 , Python — create new file without uploading new file and without using Google Drive UI

All the documentation I have found related to creating a new file and putting the new file in a user's Google Drive folder is achieved with the user uploading a file and having the python script use MediaFileUpload to gather the file and put it in Drive.

I want to create a new file in my GAE code, and put that. For example my code renders a new XML string after hitting database, and I would like to take that string, make it a file and put in Google Drive.

Anyone working with something like this?

like image 466
user1501783 Avatar asked Jul 04 '12 14:07

user1501783


People also ask

How do I automatically add files to Google Drive?

Google offers Backup and Sync, an application you can install on your computer in order to back up any folder on your computer over to Google Drive automatically. Simply install Backup and Sync and you can add any folder on your computer to automatically upload all files to Google Drive.

How do I create a Google Drive folder in Google Drive API?

To create a folder, use the files. create method with the application/vnd. google-apps. folder MIME type and a title.


2 Answers

You should use a MediaInMemoryUpload instead, which is designed for this exact purpose. You can pass a string and a MIME type.

media = MediaInMemoryUpload('some data', 'text/plain')
like image 69
Ali Afshar Avatar answered Sep 28 '22 05:09

Ali Afshar


Use following code, content is the string you're going to put. You don't have to use MediaFileUpload and python client library.

def update(content, file_id):
    url = 'https://www.googleapis.com/upload/drive/v2/files/%s?uploadType=media' % file_id
    headers = {
        'Content-Type': 'text/plain',
        'Content-Length': str(len(content)),
        'Authorization': 'Bearer <oauth2 token>'
        }
    response = urlfetch.fetch(url, payload=content, method='PUT', headers=headers)
    assert response.status_code == 200
    return response.content
like image 27
Takahiro Avatar answered Sep 28 '22 05:09

Takahiro