【发布时间】:2017-11-08 18:26:26
【问题描述】:
我正在开发一个 Python 包来与 API 通信。为了不对用户名和密码进行硬编码,我想从位于“conf”目录中的 JSON 文件中读取凭据。因此,如果没有给出用户名和密码,它会尝试从文件中加载凭据:
def __init__(self, user=None, pswd=None):
""" Illustrate method-level docstring."""
if pswd is None:
try:
with open('conf/credentials.json') as data_file:
data = json.load(data_file)
user = data['user']
pswd = data['password']
print('You will log in with user', user)
except IOError:
print("Could not read file: credentials.json. Please Instantiate object with your username and password")
在同一目录中执行代码时,此解决方案可以正常工作,但是一旦安装了软件包,系统就找不到该文件:
Could not read file: credentials.json. Please Instantiate object with
your username and password
我该如何克服这个问题?可以参考安装路径吗?我不想加密密码,我只想将凭据放在一个单独的文件中,并将该文件添加到 .gitignore 文件中以防止共享此信息。
【问题讨论】:
-
你可以使用 Configparser 之类的东西
-
尝试提供 json 的完整路径
标签: python json python-3.x credentials