環境變數 #
在開發 python 專案的時候,常常會面對到程式碼必須與其他人一起分享(通常透過git
),但是你又不希望分享一些比較敏感的資訊,譬如:API_KEY
, SECRET_TOKEN
, …等等。這個時候你可以把這些資訊透過寫到你的 .bashrc
裡面,
export API_KEY="my_api_key"
然後在python中讀取:
import os
api_key = os.getenv("API_KEY") # or os.environ["API_KEY"]
print(f"My API key is: {api_key}")
不過,這樣一來同事還需要手動設定 .bashrc
,而且在 README 說明還得額外加上環境變數的設定指示,對專案維護比較麻煩。更理想的做法是把這些環境變數集中放到一個 .env
檔案裡,然後透過 python-dotenv
這個套件來載入。
安裝 python-dotenv
#
pip install python-dotenv
建立 .env
檔案
#
在專案根目錄建立一個 .env
檔案,寫入需要的環境變數,例如:
API_KEY=your_api_key_here
LINE_TOKEN=your_token
在 Python 中使用 #
from dotenv import load_dotenv
import os
# 載入 .env 檔案
load_dotenv()
# 取得環境變數
api_key = os.getenv("API_KEY")
token = os.getenv("LINE_TOKEN")
print("API_KEY:", api_key)
print("LINE_TOKEN:", token)
小技巧 #
.env
檔案建議不要 commit 到 git(在.gitignore
裡加上.env
)- 在開發時可以把
.env.example
當範例,供同事複製後填入自己的參數。 - 如果要在GitHub Action 使用,可以把環境變數寫入:Settings -> Secrets and variables -> Actions -> New repository secret 。
- 加入後可在
.github/workflows/ci.yml
加入... env: API_KEY: ${{ secrets.API_KEY }} LINE_TOKEN: ${{ secrets.LINE_TOKEN }} ...
這樣就能讓環境變數管理更安全、更有彈性,同時保護專案的敏感資料!