
一般公司和家庭用家都會透過 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
- 我的套件具有上述結構。
- 在 routerhk.py 中開發一個 RouterHk Class,並從 routerhk/init.py 中調用它,手動測試該Class 及其 Functions。
- 編寫 test_routerhk.py,我使用 unittest。
python -m unittest tests/test_routerhk.py
- 我可能會稍後改回 pytest。
- 參考其他 Python 套件來創建 setup.py,以便讓 PyPI 設立套件資料。
pip install setuptools wheel
python setup.py sdist bdist_wheel
pip install .
- 從其他目錄測試安裝的本地 Python 套件。
- 上傳到 PyPI
pip install twine
twine upload dist/*
- 輸入 API Token 並將套件上傳到 PyPI。
我的 PyPI 帳戶於 2016 年創建。我在 pypi.org 上創建了一個 API token,並用它上傳套件。
使用 routerhk 的示例代碼:
from routerhk import RouterHk
r = RouterHk()
r.get_ip()
r.ip_address
參考資料:
- unittest 基礎示例: https://docs.python.org/3/library/unittest.html#basic-example
- Python Packaging User Guide: https://packaging.python.org/en/latest/
- The Packaging Flow: https://packaging.python.org/en/latest/flow/