LoginSignup
1
2

More than 1 year has passed since last update.

[デジタル開発]NotionのAPIを使ってPythonからデータベースの値を取得する。

Last updated at Posted at 2021-12-31

Pythonコード

Notionのデータベース上の値を取得するPythonコードです。
下記の[Secret Token]と[Database ID]を適宜自分の環境に合わせて変えるだけです。

▶︎ 下記のPythonライブラリを用いています。
https://github.com/ramnes/notion-sdk-py

▶︎ NotionのAPI導入、Secret Token取得については下記のサイトを参照してください。
https://dev.classmethod.jp/articles/try-notion-api-with-postman/

▶︎ NotionのDatabase ID取得については下記のサイトを参照してください。
https://zenn.dev/5t111111/articles/785fec8d21d82b

▶︎ Notionのデータベースはこちら↓
https://opaque-pixie-26c.notion.site/Main-Page-Sample-68e2f924703f471ab0ac4b8b1a0bdf32

66703A5C-08D0-4AF2-BE31-EADE52703874.jpeg

▶︎ その結果をNASA CEAの入力として使えば設計作業を全てデジタル化できます。
NASA CEAは実際のロケットエンジン開発現場でも使われている性能解析ソフトウェアです。
最近、Pythonから簡単に呼び出せるWrapperが出たので、全てがPython上で完結して超便利。
https://github.com/bluedack-space/OnlineRocketDesigner/blob/main/RocketEnginePeformance.ipynb

NotionApiGetValueFromDatabase.py
import os
from notion_client import Client
token: str = os.environ.get("NOTION_TOKEN", "[Secret Token]")
notion = Client(auth=token)

dic ={
        "database_id": "[Database ID]",
        "filter": {
            "property": "Design Parameter",
            "text": {
                "contains": "[KEY]",
            },
        },
    }

import json
def json_ReplaceKey(dic,strTarget,strReplace):
    buff = json.dumps(dic)
    buff = buff.replace(strTarget,strReplace)
    dicRet = json.loads(buff)
    return dicRet

def getValue(notion,dic,Key=None):
    dicNew = json_ReplaceKey(dic,strTarget='[KEY]',strReplace=Key)
    result = notion.databases.query(**dicNew)
    value  = result['results'][0]['properties']['Design Value']['rich_text'][0]['plain_text']
    return value

value  = getValue(notion,dic,Key='Chamber Pressure')
Pc     = float(value)
print("Chamber Pressure[MPa]:"+str(Pc))

FuelName = getValue(notion,dic,Key='Fuel')
print("Fuel[-]:"+str(FuelName))

OxName   = getValue(notion,dic,Key='Oxidizer')
print("Oxidizer[-]:"+str(OxName))

出力結果は下記のとおりです。

Chamber Pressure[MPa]:11.0
Fuel[-]:LH2
Oxidizer[-]:LOX
1
2
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
1
2