Jes*_*nee 6 python pypi setup.py python-packaging
我有一个名为collectiondbf的 pypi 包,它使用用户输入的 API 密钥连接到 API。它用于在目录中下载文件,如下所示:
python -m collectiondbf [myargumentshere..]
Run Code Online (Sandbox Code Playgroud)
我知道这应该是基本知识,但我真的被困在这个问题上:
如何以有意义的方式保存用户给我的密钥,以便他们不必每次都输入它们?
我想通过config.json文件使用以下解决方案,但如果我的包将移动目录,我如何知道该文件的位置?
这是我想如何使用它,但显然它不会工作,因为工作目录会改变
import json
if user_inputed_keys:
with open('config.json', 'w') as f:
json.dump({'api_key': api_key}, f)
Run Code Online (Sandbox Code Playgroud)
大多数常见的操作系统都有一个应用程序目录的概念,它属于在系统上拥有帐户的每个用户。该目录允许所述用户创建和读取例如配置文件和设置。
所以,你需要做的就是列出你想要支持的所有发行版,找出他们喜欢放置用户应用程序文件的位置,并有一个大的旧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
Run Code Online (Sandbox Code Playgroud)