[英]How to properly set up a json config file so that it can be used to replace hardcoded values in python program
I am trying to modify my python method so that its reading values from a separate json config file.我正在尝试修改我的 python 方法,以便它从单独的 json 配置文件中读取值。
I have a separate valid json file that looks like this testtok.json
:我有一个单独的有效 json 文件,看起来像这样testtok.json
:
{
"email" : "user@domain.com",
"audience" : "http://someaudience.com",
"jti" : "MYJTI1234",
"name" : "John Smith",
"humid" : "ABC1234"
}
I want to pass in those values to my function here:我想将这些值传递给我的函数:
def tokengen(self, privatekey):
with open('config/testtok.json', 'r') as config:
data = json.load(config)
try:
"""Simulate Token Manager creating a token"""
email = config["email"]
audience = config["audience"]
jti = config["jti"]
name = config["name"]
humid = config["humid"]
#email = "user@domain.com"
#audience = "http://someaudience.com"
#jti = "MYJTI1234"
#name = "John Smith"
#humid = "ABC1234"
"""Time Component"""
timestamp = testdate()
timestamp.now()
issued = int(time.time())
expires_in=2400
expires = issued + expires_in
additional_headers = {
"alg": "RS256",
"typ": "JWT"
}
payload = {
"iss": email,
"sub": email,
"aud": audience,
"iat": issued,
"nbf": issued,
"exp": expires,
"jti": jti,
"name": name,
"humid": humid,
"email": email
}
self.testtoken = jwt.encode(payload, privatekey, algorithm="RS256", headers=additional_headers).decode("utf-8")
valid_response = {'validation' : 'VALID', 'ts' : timestamp.utc_datetime_str, 'test_token' : self.testtoken}
return(valid_response)
except Exception as ex:
invalid_response = {'validation' : 'INVALID', 'ts' : timestamp.utc_datetime_str, 'test_token' : self.testtoken}
return(invalid_response)
I'm seeing this error and unclear how to troubleshoot this.我看到了这个错误,但不清楚如何解决这个问题。
Traceback (most recent call last):
File "testTokClass.py", line 25, in tokengen
config["email"]
TypeError: '_io.TextIOWrapper' object is not subscriptable
Is there a better way to do this?有一个更好的方法吗? Ideally, I would like to have the config file as json.理想情况下,我希望将配置文件设为 json。 Thanks.谢谢。
Th problem is that the config
is a file handle;问题是config
是一个文件句柄; in the line data = json.load(config)
the JSON is read from the file pointed to by config
and into the data
variable.在data = json.load(config)
,JSON 从config
指向的文件中读取到data
变量中。
So, just change:所以,只需改变:
email = config["email"]
to:到:
email = data["email"]
And similarly for the next four lines.接下来的四行也类似。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.