簡體   English   中英

如何為 PYPI 包持久存儲

[英]How to have persistent storage for a PYPI package

我有一個名為collectiondbf的 pypi 包,它使用用戶輸入的 API 密鑰連接到 API。 它用於在目錄中下載文件,如下所示:

python -m collectiondbf [myargumentshere..]

我知道這應該是基本知識,但我真的被困在這個問題上:

如何以有意義的方式保存用戶給我的密鑰,以便他們不必每次都輸入它們?

我想使用config.json文件使用以下解決方案,但如果我的包將移動目錄,我如何知道此文件的位置?

這是我想如何使用它,但顯然它不會工作,因為工作目錄會改變

import json
if user_inputed_keys:
    with open('config.json', 'w') as f:
        json.dump({'api_key': api_key}, f)

大多數常見的操作系統都有一個應用程序目錄的概念,它屬於在系統上擁有帳戶的每個用戶。 該目錄允許所述用戶創建和讀取例如配置文件和設置。

因此,您需要做的就是列出您想要支持的所有發行版,找出他們喜歡放置用戶應用程序文件的位置,並擁有一個很大的舊if..elif..else鏈來打開相應的目錄。


或者使用appdirs ,它已經做到了:

from pathlib import Path
import json
import appdirs

CONFIG_DIR = Path(appdirs.user_config_dir(appname='collectiondbf'))  # magic
CONFIG_DIR.mkdir(parents=True, exist_ok=True)

config = CONFIG_DIR / 'config.json'
if not config.exists():
  with config.open('w') as f:
    json.dumps(get_key_from_user(), f)
with config.open('r') as f:
  keys = json.load(f)  # now 'keys' can safely be imported from this module

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM