將我的第一個 Python 套件發布到 PyPI

一般公司和家庭用家都會透過 router 連接互聯網,他們電腦和手機平板甚至 Server 和 NAS 都是連接 router 的單位內的私人 WIFI 或 LAN,不輕易得知公司或家中在互聯網上的真正 IP 地址。

我擁有一個易記的域名 router.hk 已經多年。之前我開發了一個 IP 地址查詢工具,幫助 Linux 和網絡管理員以及一般用家取得互聯網上的 IP 地址。上星期,我開發了一個更新版本的 API,可以通過簡單的 curl 命令得到 IP 地址。

這星期,我嘗試為它開發一個 Python 套件並上傳到 PyPI(Python Package Index)。開發 Python 套件需要更好的文件結構和附加文件。

PyPI: https://pypi.org/project/routerhk/
GitHub: https://github.com/routerhk/routerhk

文件結構

routerhk/
├── routerhk/
│ ├── init.py
│ └── routerhk.py
├── tests/
│ └── test_routerhk.py
├── setup.py
├── README.md
├── requirements.txt
└── LICENSE

  1. 我的套件具有上述結構。
  2. 在 routerhk.py 中開發一個 RouterHk Class,並從 routerhk/init.py 中調用它,手動測試該Class 及其 Functions。
  3. 編寫 test_routerhk.py,我使用 unittest。
    1. python -m unittest tests/test_routerhk.py
    2. 我可能會稍後改回 pytest。
  4. 參考其他 Python 套件來創建 setup.py,以便讓 PyPI 設立套件資料。
    1. pip install setuptools wheel
    2. python setup.py sdist bdist_wheel
    3. pip install .
    4. 從其他目錄測試安裝的本地 Python 套件。
  5. 上傳到 PyPI
    1. pip install twine
    2. twine upload dist/*
    3. 輸入 API Token 並將套件上傳到 PyPI。

我的 PyPI 帳戶於 2016 年創建。我在 pypi.org 上創建了一個 API token,並用它上傳套件。

使用 routerhk 的示例代碼:

from routerhk import RouterHk
r = RouterHk()
r.get_ip()
r.ip_address

參考資料:

About Sammy Fung

從事國際資訊科技工作超過20年,推動開放源碼和開放數據發展,多次接受媒體訪問科技議題。

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

*