-
-
Save SanjarbekSaminjonov/6d9b3349c281ecadcc9da438a00335e6 to your computer and use it in GitHub Desktop.
upload files to google drive using python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests, json | |
# Get refresh token from google drive api | |
# Generating a refresh token for DRIVE API calls using the OAuth playground | |
# https://www.youtube.com/watch?v=hfWe1gPCnzc | |
def getToken(): | |
oauth = 'https://www.googleapis.com/oauth2/v4/token' # Google API oauth url | |
headers = {'content-type': 'application/x-www-form-urlencoded'} | |
data = { | |
'grant_type': 'refresh_token', | |
'client_id': '####', | |
'client_secret': '####', | |
'refresh_token': '####', | |
} | |
token = requests.post(oauth, headers=headers, data=data) | |
_key = json.loads(token.text) | |
return _key['access_token'] | |
# Upload files to google drive using access token | |
def upload2Drive(files): | |
TOKEN_KEY = getToken() | |
headers = {"Authorization": "Bearer "+TOKEN_KEY} | |
upload = requests.post( | |
"https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart", | |
headers=headers, | |
files=files | |
) | |
print(upload.text) | |
if __name__ == '__main__': | |
file = "my-upload-test.zip" # change your file name | |
para = { | |
"name": file, #file name to be uploaded | |
"parents": ["####"] # make a folder on drive in which you want to upload files; then open that folder; the last thing in present url will be folder id | |
} | |
files = { | |
'data': ('metadata', json.dumps(para), 'application/json; charset=UTF-8'), | |
'file': ('application/zip',open("./"+file, "rb")) # replace 'application/zip' by 'image/png' for png images; similarly 'image/jpeg' (also replace your file name) | |
} | |
upload2Drive(files) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment