LoginSignup
0
1

More than 3 years have passed since last update.

Pydriveの認証ファイルを,スクリプトと別ディレクトリに保存する

Last updated at Posted at 2020-10-25

結論

Pydriveの認証ファイルをスクリプトと別ディレクトリに保存したい場合は,以下のように書けばOK.

from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from oauth2client.file import Storage

gauth = GoogleAuth(settings_file=f"{保存したいディレクトリの絶対Path}/settings.yaml")
gauth.credentials = Storage(f"{保存したいディレクトリの絶対Path}/credentials.json").get()
gauth.CommandLineAuth()
drive = GoogleDrive(gauth)

依存環境

python==3.7.6
pydrive==1.3.1

背景

はじめに

Pydriveの基本的な使用方法や設定方法は,以下のサイトが丁寧に解説しているため割愛.

参考サイト:
Python, PyDriveでGoogle Driveのダウンロード、アップロード、削除など - note.nkmk.me

デフォルトだと,認証ファイルを別ディレクトリに保存できない.

Pydriveの認証ファイルは,(デフォルトだと)スクリプトが保存されているディレクトリと同じディレクトリに保存されていないと認証NGとなる.

例えば以下のように,スクリプトmain.pyと同じディレクトリに,認証ファイルclient_secrets.json, credentials.json, settings.yamlを保存することがMust.

/home/hogehoge/
  └ hoge_project/
    └ src/
      ├ client_secrets.json
      ├ credentials.json
      ├ settings.yaml
      └ main.py
main.py
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive

gauth = GoogleAuth()
gauth.CommandLineAuth()
drive = GoogleDrive(gauth)

でも別ディレクトリに保存したい.

でも,srcディレクトリの中にスクリプトと認証ファイルとが混在しているのはなんか気持ちが悪い.
そこでなんとかして,以下のように認証ファイルをcreds/ディレクトリ下に移動させたい.

/home/hogehoge/
  └ hoge_project/
    ├ creds/
    │  ├ client_secrets.json
    │  ├ credentials.json
    │  └ settings.yaml
    │
    └ src/
      └ main.py

引数を指定することで,別ディレクトリの認証ファイルを読み込むことが可能.

以下のように書けば,creds/以下の認証ファイルを,main.pyが認識することが可能となる.

main.py
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from oauth2client.file import Storage

gauth = GoogleAuth(settings_file=f"/home/hogehoge/creds/settings.yaml")
gauth.credentials = Storage(f"/home/hogehoge/creds/credentials.json").get()
gauth.CommandLineAuth()
drive = GoogleDrive(gauth)

参考サイト:pythonのスクレイピングで躓いたところをメモ - Qiita

さいごに

なかなか情報が見つからなくて苦労した.
他に何かあれば教えて下さい.

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1