2017-04-23 4 views

答えて

1

私はGoogleチュートリアルで苦労しました。ファイルのパスを使用してファイルを送信したり、ファイルをrik clikingで送信するために必要なコード(および説明)は次のとおりです(Windows 7の場合はPython 36で作業します)

## windows7 python36: send to gdrive using righ click context menu 

import logging 
import httplib2 
import os #to get files 
from os.path import basename #get file name 
import sys #to get path 
import ctypes # alert box (inbuilt) 
import time #date for filename 
import oauth2client 
from oauth2client import client, tools 

# google apli drive 
from oauth2client.service_account import ServiceAccountCredentials 
from apiclient.discovery import build 
from apiclient.http import MediaFileUpload 

#needed for gmail service 
from apiclient import discovery 

import mimetypes #to guess the mime types of the file to upload 

import HtmlClipboard #custom modul which recognized html and copy it in html_clipboard 


## About credentials 
# There are 2 types of "credentials": 
#  the one created and downloaded from https://console.developers.google.com/apis/ (let's call it the client_id) 
#  the one that will be created from the downloaded client_id (let's call it credentials, it will be store in C:\Users\user\.credentials) 


     #Getting the CLIENT_ID 
      # 1) enable the api you need on https://console.developers.google.com/apis/ 
      # 2) download the .json file (this is the CLIENT_ID) 
      # 3) save the CLIENT_ID in same folder as your script.py 
      # 4) update the CLIENT_SECRET_FILE (in the code below) with the CLIENT_ID filename 


     #Optional 
     # If you don't change the permission ("scope"): 
      #the CLIENT_ID could be deleted after creating the credential (after the first run) 

     # If you need to change the scope: 
      # you will need the CLIENT_ID each time to create a new credential that contains the new scope. 
      # Set a new credentials_path for the new credential (because it's another file) 

## get the credential or create it if doesn't exist 

def get_credentials(): 
    # If needed create folder for credential 
    home_dir = os.path.expanduser('~') #>> C:\Users\Me 
    credential_dir = os.path.join(home_dir, '.credentials') # >>C:\Users\Me\.credentials (it's a folder) 
    if not os.path.exists(credential_dir): 
     os.makedirs(credential_dir) #create folder if doesnt exist 
    credential_path = os.path.join(credential_dir, 'name_of_your_json_file.json') 

    #Store the credential 
    store = oauth2client.file.Storage(credential_path) 
    credentials = store.get() 

    if not credentials or credentials.invalid: 
     CLIENT_SECRET_FILE = 'client_id to send Gmail.json' 
     APPLICATION_NAME = 'Gmail API Python Send Email' 
     #The scope URL for read/write access to a user's calendar data 

     SCOPES = 'https://www.googleapis.com/auth/gmail.send' 

     # Create a flow object. (it assists with OAuth 2.0 steps to get user authorization + credentials) 
     flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) 
     flow.user_agent = APPLICATION_NAME 

     credentials = tools.run_flow(flow, store) 

    return credentials 



## Send a file by providing it's path (for debug) 
def upload_myFile_to_Gdrive(): #needed for testing 

    credentials = get_credentials() 
    http = credentials.authorize(httplib2.Http()) 
    drive_service = discovery.build('drive', 'v3', http=http) 

    path_file_to_upload=r'C:\Users\Me\Desktop\myFile.docx' 

    #extract file name from the path 
    myFile_name=os.path.basename(path_file_to_upload) 

    #upload in the right folder: 
    # (to get the id: open the folder on gdrive and look in the browser URL)  
    folder_id="0B5qsCtRh5yNoTnVbR3hJUHlKZVU" 

    #send it 
    file_metadata = { 'name' : myFile_name, 'parents': [folder_id] } 
    media = MediaFileUpload(path_file_to_upload, 
          mimetype='application/vnd.openxmlformats-officedocument.wordprocessingml.document' 
          )#find the right mime type: http://stackoverflow.com/questions/4212861/what-is-a-correct-mime-type-for-docx-pptx-etc 
    file = drive_service.files().create(body=file_metadata, media_body=media, fields='id').execute() 

    #Print result: 
    print(f"file ID uploaded: {file.get('id')}") 
    input("close?") 


## Send file selected using the "send to" context menu 

def upload_right_clicked_files_to_Gdrive(): 

    credentials = get_credentials() 
    http = credentials.authorize(httplib2.Http()) 
    drive_service = discovery.build('drive', 'v3', http=http) 

    ## launch the script through the context menu "SendTo" 
    # (in windows7) Type "shell:SendTo" in the URL of an explorer windows. Create a .cmd file containing (remove the first # before each line): 
    # #@echo off 
    # cls 
    # python "The\\path\\of\\your_script.py" "%1" 

    ## the path of the file right-clicked will be stored in "sys.argv[1:]" 
    #print(sys.argv) 
    #['C:\\Users\\my_script.py', 'C:\\Desktop\\my', 'photo.jpg'] #(the path will cut if the filename contain space) 

    ##get the right-clicked file path 
    #join all till the end (because of the space) 
    path_file_to_upload= ' '.join(sys.argv[1:]) #>> C:\Desktop\my photo.jpg  
    file_name=os.path.basename(path_file_to_upload) 

    ##guess the content type of the file 
    #-----About MimeTypes: 
    # It tells gdrive which application it should use to read the file (it acts like an extension for windows). If you dont provide it, you wont be able to read the file on gdrive (it won't recognized it as text, image...). You'll have to download it to read it (it will be recognized then with it's extension). 

    file_mime_type, encoding = mimetypes.guess_type(path_file_to_upload) 
    #file_mime_type: ex image/jpeg or text/plain (or None if extension isn't recognized) 
    # if your file isn't recognized you can add it here: C:\Users\Me\AppData\Local\Programs\Python\Python36\Lib\mimetypes.py 


    if file_mime_type is None or encoding is not None: 
     file_mime_type = 'application/octet-stream' #this mine type will be set for unrecognized extension (so it won't return None). 

    ##upload in the right folder: 
    # (to get the id: open the folder on gdrive and look in the browser URL)   
    folder_id="0B5f6Tv7nVYv77BPbVU" 

    ## send file + it's metadata 
    file_metadata = { 'name' : file_name, 'parents': [folder_id] } 
    media = MediaFileUpload(path_file_to_upload, mimetype= file_mime_type) 
    the_file = drive_service.files().create(body=file_metadata, media_body=media, fields='id').execute() 

    ##print the uploaded file ID 
    uploaded_file_id = the_file.get('id') 
    print(f"file ID: {uploaded_file_id}") 
    input("close?") 




if __name__ == '__main__': 
    # upload_right_clicked_files_to_Gdrive() 
    upload_myFile_to_Gdrive() # needed to debug 
関連する問題