8000 Script that uploads a file to Google Drive works, but when I try to run that script within another I get an HTTPerror · Issue #983 · googleapis/google-api-python-client · GitHub
[go: up one dir, main page]

Skip to content
Script that uploads a file to Google Drive works, but when I try to run that script within another I get an HTTPerror #983
Closed
@filifunk

Description

@filifunk

I'm somewhat of a beginner.

I have a script (morning3.py) that I run that writes and saves a text file and at the end of the script it's supposed to upload that file into google through the api by calling upon another python script called auth.py.

the morning.py file writes the new file but when it tries to upload the file I get this error:

Traceback (most recent call last):
  File "morning3.py", line 108, in <module>
    auth.uploadfile('test{}.txt'.format(datetime.date.today()), 'test{}.txt'.format(datetime.date.today()), 'txt/csv')
  File "/home/pete/google/auth.py", line 78, in uploadfile
    file = service.files().create(body=file_metadata,media_body=media,fields='id').execute()
  File "/home/pete/.local/lib/python3.8/site-packages/googleapiclient/_helpers.py", line 134, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/home/pete/.local/lib/python3.8/site-packages/googleapiclient/http.py", line 871, in execute
    _, body = self.next_chunk(http=http, num_retries=num_retries)
  File "/home/pete/.local/lib/python3.8/site-packages/googleapiclient/_helpers.py", line 134, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/home/pete/.local/lib/python3.8/site-packages/googleapiclient/http.py", line 1054, in next_chunk
    return self._process_response(resp, content)
  File "/home/pete/.local/lib/python3.8/site-packages/googleapiclient/http.py", line 1085, in _process_response
    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">

The weird thing is that I don't try to upload the file by importing auth.py and using the function that uploads the file...and run auth.py separately...it works fine!

This is auth.py, looking at this now I know there is probably ugly code here...but here it is:

from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.http import MediaFileUpload
import datetime

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/drive']

def main():
    """Shows basic usage of the Drive v3 API.
    Prints the names and ids of the first 10 files the user has access to.
    """
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('drive', 'v3', credentials=creds)

    # Call the Drive v3 API
    results = service.files().list(
        pageSize=10, fields="nextPageToken, files(id, name)").execute()
    items = results.get('files', [])

    if not items:
        print('No files found.')
    else:
        print('Files:')
        for item in items:
            print(u'{0} ({1})'.format(item['name'], item['id']))

def uploadfile(filename,filepath,mimetype):
    creds = None

    
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('drive', 'v3', credentials=creds)


    file_metadata = {'name': filename,}
    media = MediaFileUpload(filepath,
                        mimetype=mimetype,
                        resumable=True)
    #import pdb
    #pdb.set_trace()
    file = service.files().create(body=file_metadata,media_body=media,fields='id').execute()
    print ('File ID: %s' % file.get('id'))


if __name__ == '__main__':
    main()
    uploadfile('test{}.txt'.format(datetime.date.today()), 'test{}.txt'.format(datetime.date.today()), 'txt/csv')

in morning3.py, I import auth up top and then at the bottom I have this:

auth.uploadfile('test{}.txt'.format(datetime.date.today()), 'test{}.txt'.format(datetime.date.today()), 'txt/csv')

Metadata

Metadata

Assignees

Labels

type: questionRequest for information or clarification. Not an issue.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions

    0