9
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Python】データベースがいらない!?gspreadが便利!

9
Posted at

概要

つい、先日Twitterにて
「あ〜、Herokuのデータベース無料枠に収まりきらない」
とか、
「わい、クレカ持ってないからHerokuのデータベース使えないのだが」
みたいな投稿を見掛けました。

お、それだったらSpreadSheetで管理すればいいやん。って思ったので
PythonからHerokuでも使えるSpreadSheetの操作方法の解説です。

Gspreadとは何ぞや?

Google社が提供するspreadsheetをPythonから管理できるモジュールのこと

環境

Python 3.9.1

gspread
(インストール)

pip install gspread

oauth2client
(インストール)

pip install --upgrade oauth2client

事前準備

詳しい説明は省きますが、
GDCにアクセスしてプロジェクトを作成し、

  • spreadsheetAPI
  • GoogleDriveAPI

を有効にし、サービスアカウントを作成します。
認証情報キーはJson形式でダウンロードしておいてください。

——
データベースとしたいSpreadsheetを作成します。
そして、そのURLの/d/の後の部分(以下:ワークブックID)をあとあと使うので、記録しておく。

右上の共有というボタンから先程のサービスアカウントメールアドレスを追加し、編集者の権限を与えておく。

何でスプレッドシートが便利なの?

① スプレッドシート上で参照やソートを行えるため、コードを略せる。

②ドライブ上に保存してあるので、スマホからもアクセスできる

③手動更新も簡単にできる。

④デザインや見た目を工夫することで見やすいデータベース代わりになる。

⑤共同編集が楽

実装

認証情報jsonはプロジェクトフォルダに移動させ、名前をkey.jsonなどとわかりやすい名前にしておくことを推奨します。

なお、今回はそれぞれの処理がわかりやすいようにclassにまとめます。

spread.py
import gspread
from oauth2client.service_account import ServiceAccountCredentials 

import json

class SpreadSheet():
  #初期化(認証情報読み込み,ワークブックID指定)
  def __init__(self,ID:str):
    self.id = ID
    #リフレッシュトークンを1時間ごとに生産する必要があるのをを回避
    scope = ['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/drive']
    #認証情報を読み込み
    credentials = ServiceAccountCredentials.from_json_keyfile_name('key.json', scope)
    #APIへログイン
    self.gc = gspread.authorize(credentials)

  #spread sheetへアクセス
  def access(self):
    res = self.gc.open_by_key(self.id)
    return res
  
  #スプレッドシートのワークシートを開く
  def read_sheet(self,sheet:str):
    #アクセス
    book = self.access()
    sheet = book.worksheet(sheet)
    return sheet
  
  #セルを指定してデータを取得
  def get_val(self,cell:str):
    sheet = self.read_sheet('シート1')
    val = sheet.acell('A1').value()
    return val
    
  #セルの値を更新
  def update(self,cell:str,text:str):
    sheet = self.read_sheet('シート1')
    sheet.update_acell(cell,text)

メイン部分の実装をします、
例えばこの場合、水道料金を取得するものを作りましょう
水道の価格帯をスプレッドシートにまとめます。

シート1

行/列 A B
1 1 4810
2 2 4870
3 3 4940
4 4 5010
5 5 5090
...
やけに高い水道ですね。
main.py
from spread import SpreadSheet

s =SpreadSheet('my spreadsheet id')

use = int(input())
fee = s.get_val(f'B{use}')
print(f'{use}㎥の水を使用した場合料金は{fee}円になります。')

spreadsheetの機能としては十分だと思います!
容量も取らないので、

以上です。

9
10
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
9
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?