I am using the Google Drive API to create a .csv, and I see it in my "Drive" display but I don't see it in "Sheets." How can I make it show in Sheets? Here is my code:
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('drive', 'v3', http=http)
results = service.files().create(body={"name":"Test7.csv"}, media_body='/tmp/inputfile.csv', keepRevisionForever=None, useContentAsIndexableText=None, supportsTeamDrives=None, ocrLanguage=None, ignoreDefaultVisibility=None).execute()
Looks like you are just adding a CSV file to Drive.
You need to specify the mime type as Google Spreadsheet:
from apiclient.http import MediaFileUpload
file_metadata = {
'name' : 'My Report',
'mimeType' : 'application/vnd.google-apps.spreadsheet'
}
media = MediaFileUpload('test7.csv',
mimetype='text/csv',
resumable=True)
file = drive_service.files().create(body=file_metadata,
media_body=media,
fields='id').execute()
https://developers.google.com/drive/v3/web/manage-uploads#importing_to_google_docs_types_wzxhzdk18wzxhzdk19
Related
I have created a new google sheet using google api. I was able to create it if I have one file for all the below tasks:
Create credential and create an instance of sheets
Create a new sheet with a title
Add permissions to the sheet so that I can access it
Below code runs successfully :
## Define scopes and service account file - these are like ID and password for google api
SCOPES = ['https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive']
SERVICE_ACCOUNT_FILE = 'keys.json'
## Authorizing to connect with google api scopes(these scopes should be enabled in google api)
creds = None
creds = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
spreadsheet_id = Null
spreadsheet = {
'properties': {
'title': 'Test'
}
}
# connecting to google sheets api
service = build('sheets', 'v4', credentials = creds)
# Call the Sheets API
sheet = service.spreadsheets()
# Create spreadsheet with title
create_response = sheet.create(body = spreadsheet, fields='spreadsheetId').execute()
spreadsheet_id = create_response.get('spreadsheetId')
# Add permissions to account/emails
permits = [{'role': 'writer', 'type':'user', 'emailAddress': 'itika.sharma10#gmail.com'}]
# connecting to google drive api
drive = build('drive', 'v3', credentials = creds)
for permit in permits:
res = drive.permissions().create(fileId = spreadsheet_id, body = permit, fields="id").execute()
Now, I wanted to have separate files and functions for all these tasks like below:
Credentials.py - to create sheet instance
Permissions.py - to add permissions
Create.py - to create a new sheet and I am calling the other two files from this file
SCOPES = [['https://www.googleapis.com/auth/spreadsheets'], ['https://www.googleapis.com/auth/drive']]
spreadsheet_id = Null
spreadsheet = {
'properties': {
'title': 'Test'
}
}
def create_sheet(spreadsheet):
# connecting to google sheets api
service = build('sheets', 'v4', credentials = creds)
# Call the Sheets API
sheet = service.spreadsheets()
# Create spreadsheet with title
create_response = sheet.create(body = spreadsheet, fields='spreadsheetId').execute()
spreadsheet_id = create_response.get('spreadsheetId')
return(spreadsheet_id)
if __name__ == '__main__':
creds = credentials.create_creds(SCOPES)
spreadsheet_id = create_sheet(spreadsheet)
permissions.add_permissions(spreadsheet_id, SCOPES)
But I get below error:
Exception has occurred: TypeError
sequence item 0: expected str instance, list found
File "C:\Users\itika\Desktop\Python\web\Untitled Folder\create.py", line 25, in create_sheet
create_response = sheet.create(body = spreadsheet, fields='spreadsheetId').execute()
File "C:\Users\itika\Desktop\Python\web\Untitled Folder\create.py", line 32, in <module>
spreadsheet_id = create_sheet(spreadsheet)
I checked the type of creds, spreadsheet and sheet for both the codes and compared them. They are identical.
Can someone help to resolve this error.
Using this code, I am uploading the files to google drive successfully. But each time when I run this code, it uploads the same files to google drive again. What I want is to stop this repetition of uploading the data and just upload the newly created file.
import os
import httplib2
from googleapiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
http = httplib2.Http()
SCOPES = ['https://www.googleapis.com/auth/drive']
credentials = ServiceAccountCredentials.from_json_keyfile_name('thermal-highway.json', SCOPES)
drive_service = build('drive', 'v3', http=credentials.authorize(http))
def upload_folders(name, folder_id):
file_metadata = {
'name': name,
'mimeType': 'application/vnd.google-apps.folder',
'parents': folder_id
}
file = drive_service.files().create(body=file_metadata, fields='id').execute()
print('Folder ID: %s' % file.get('id'))
def list_files(path):
folderId = ['62bewyZXHy9JfSLG9N96U1e548luuCAWR']
for files in os.listdir(path):
d = os.path.join(path, files)
if os.path.isdir(d):
upload_folders(files, folderId)
path = "/home/bilal/Videos/folder1/"
list_files(path)
Your code uses file.create which creates a new file each time. If you want to update an existing file then you should be using file.update
# File's new content.
media_body = MediaFileUpload(
new_filename, mimetype=new_mime_type, resumable=True)
# Send the request to the API.
updated_file = service.files().update(
fileId=file_id,
body=file,
media_body=media_body).execute()
I was trying to upload a resumable file upload on google api drive as per the documentation from https://developers.google.com/drive/api/v3/manage-uploads#python_1 . A sample code is given below, I am stuck with the current situation.
SCOPES = ['https://www.googleapis.com/auth/drive','https://www.googleapis.com/auth/drive.file','https://www.googleapis.com/auth/drive.appdata']
credentials = ServiceAccountCredentials.from_json_keyfile_name('json-file', SCOPES)
http=Http()
http.redirect_codes = http.redirect_codes - {308}
http_auth = credentials.authorize(http)
drive_service = build('drive', 'v3', http=http_auth,cache_discovery=False)
parent_id="folder-id"
source='/root/test.tar'
target='test.tar'
file_metadata = {'name': target, 'parents': [parent_id], 'mimeType': 'application/vnd.google-apps.file'}
media = MediaFileUpload(source,mimetype='application/vnd.google-apps.file',chunksize=1024*1024,resumable=True)
putfile=drive_service.files().create(body=file_metadata,media_body=media,fields='id').execute()
dest_id=putfile.get('id')
These lines are trowing the following errors. I have no idea about it.
raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://www.googleapis.com/upload/drive/v3/files?fields=id&alt=json&uploadType=resumable returned "Bad Request">
I wonder what is making this issue ?
You are missing chunk size.
parent_id = "folder-id"
source = '/root/test.tar'
target = 'test.tar'
file_metadata = {'name': target, 'parents': [parent_id],
'mimeType': 'application/vnd.google-apps.file'}
media = MediaFileUpload(source, mimetype='application/vnd.google-apps.file',
chunksize=1024*1024, resumable=True)
putfile = drive_service.files().create(body=file_metadata,
media_body=media,fields='id').execute()
dest_id = putfile.get('id')
How I can create a folder inside the google drive and upload files into that folder? (in python)
I have tried with the google tutorials but it is giving me errors
creating a folder, not working giving me errors like 'drive_service not defined'
file_metadata = {
'title': 'Files',
'mimeType': 'application/vnd.google-apps.folder'
}
file = drive_service.files().insert(body=file_metadata,
fields='id').execute()
print 'Folder ID: %s' % file.get('id')
Used this code for uploading a file and it is working, how I can modify it for uploading a file into a folder if that exists, if not create one and upload.
import json
import requests
headers = {"Authorization": "Bearer Token"}
para = {
"name": "index.jpeg",
}
files = {
'data': ('metadata', json.dumps(para), 'application/json; charset=UTF-8'),
'file': open("./index.jpeg", "rb")
}
r = requests.post(
"https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart",
headers=headers,
files=files
)
print(r.text)
Here is an example of what I think you're looking for (its a self-contained example, but I think you can modify it to your own existing code):
from __future__ import print_function
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload
from httplib2 import Http
from oauth2client import file, client, tools
# If modifying these scopes, delete the file token.json.
SCOPES = 'https://www.googleapis.com/auth/drive.file'
def main():
# Access the Drive service
store = file.Storage('token.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('credentials.json', SCOPES)
creds = tools.run_flow(flow, store)
service = build('drive', 'v3', http=creds.authorize(Http()))
# Check if folder exists (simply matching by name)
folder_name = "Photos"
folder_id = None
query = "mimeType='application/vnd.google-apps.folder' and trashed=false and name='" + folder_name + "'"
results = service.files().list(
pageSize=1, q=query, fields="files(id, name)").execute()
folders = results.get('files', [])
if folders:
folder_id = folders[0]['id']
# If folder not found, then create it.
else:
file_metadata = {
'name': folder_name,
'mimeType': 'application/vnd.google-apps.folder'
}
folder_file = service.files().create(body=file_metadata,
fields='id').execute()
folder_id = folder_file.get('id')
# Add file to folder.
file_metadata = {
'name': 'photo.png',
'parents': [folder_id]
}
media = MediaFileUpload('photo.png',
mimetype='image/png',
resumable=True)
image_file = service.files().create(body=file_metadata,
media_body=media,
fields='id').execute()
if __name__ == '__main__':
main()
i tried get method but response is not found file.
when i get other own file.
when i get file info my own file. it is possible.
how to access other own file...
this is my code
file_id value replace [google_id] cause security
SCOPES = ['https://www.googleapis.com/auth/drive.file',
'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/drive.appdata',
'https://www.googleapis.com/auth/drive.scripts',
'https://www.googleapis.com/auth/drive.file',
'https://www.googleapis.com/auth/drive.metadata'
]
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('drive', 'v2', http=http)
file_id = '[google_id]'
file = service.files().get(
fileId=file_id, supportsTeamDrives=True).execute()
new_title = '[bob]'
file['title'] = new_title
new_filename = '[bob].mp4'
new_revision = True
updated_file = service.files().update(
fileId=file_id,
body=file,
newRevision=new_revision,
media_body=('__init__.py'), supportsTeamDrives=True).execute()
print(repr(updated_file))
i solved that i was miss delete credentials file.
so i do not have permission to access that file. thanks.