2

I have a python-script running on a server and I need to get a json-file from my GoogleDrive. I want to use the GoogleDrive API to get the file, which I know the name, location and ID of but I only could find code-samples which downloads the file to storage. The json-content is supposed to be a dict in my script and the file must not be downloaded to storage. I'm new to Python and the GoogleDrive API, so I don't know how to manage it by myself. This is the website I followed: https://www.thepythoncode.com/article/using-google-drive--api-in-python

I hope you can help me because I really need it. Thanks in advance.

benicamera
  • 750
  • 1
  • 7
  • 24
  • Google drive api isnt going to let you download to cloud storage if thats what your trying to do. you would need to download it locally they upload it to cloud storage yourself they are two different systems. – Linda Lawton - DaImTo Sep 04 '20 at 11:07
  • 1
    I have a file on GoogleDrive which I want to read with the script without downloading it to the pc-storage. – benicamera Sep 04 '20 at 11:24

1 Answers1

3

I believe your goal as follows.

  • You want to directly download the file to the memory without creating the data as a file using python.
    • From I need to get a json-file from my GoogleDrive., the file you want to download is the file except for Google Docs files (Spreadsheet, Document, Slides and so on). In this case, it's a text file.
  • You have already been able to use Drive API with googleapis for python.
  • You are using the script for authorizing from https://www.thepythoncode.com/article/using-google-drive--api-in-python.

In this case, in order to retrieve the file content to the memory, I would like to propose to retrieve it using requests. For this, the access token is retrieved from creds of get_gdrive_service().

In order to retrieve the file content, the method of "Files: get" is used by adding the query parameter of alt=media.

Sample script:

file_id = "###"  # Please set the file ID you want to download.

access_token = creds.token
url = "https://www.googleapis.com/drive/v3/files/" + file_id + "?alt=media"
res = requests.get(url, headers={"Authorization": "Bearer " + access_token})
obj = json.loads(res.text)
print(obj)
  • At above script, creds of creds.token is from get_gdrive_service().
  • From your question, I thought that the file you want to download is the JSON data. So at above script, the downloaded data is parsed as JSON object.
  • In this case, please import json and requests.

Note:

  • When the returned content is JSON data, I think that you can also use res.json() instead of res.text. But when JSONDecodeError occurs, please check the value of res.text.

Reference:

Tanaike
  • 181,128
  • 11
  • 97
  • 165