简体   繁体   English

如何正确设置 json 配置文件,以便它可以用于替换 python 程序中的硬编码值

[英]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.

相关问题 文本文件和 json 文件可以互换使用吗? 如果是这样,我如何在 python 中使用它? - Can a text file and a json file be used interchangeably? And if so how can I use it in python? 如何在python中替换硬编码路径 - how to replace the hardcoded path in python 如何获得python程序以从表/外部文件读取并提供不同的数据值? - How can I get a python program to read and serve up different data values from a table/external file? 如何设置导入,以便 airflow 在任务正常运行时不显示错误 - How can I set up import so that airflow doesn't show errors whereas the tasks are running properly 如何在Python中将list / pyodbc.row转换为字符串,以便可以使用str.replace? - How do you convert a list/pyodbc.row to a string in python so that str.replace can be used? Javascript在我的python代码中实现,这样存放在external.JSON文件中的变量就可以作为全局变量了 - Javascript implementation in my python code, so that variables stored in the external .JSON file can be used as global variables 如何正确地将字典放入 CSV 文件中,以便您可以通过键值搜索 CSV 文件? - How can you properly put a dictionary into a CSV file so you can search the CSV File by key values? 如何通过 python 替换非标准 json 文件中的值 - How to replace values in non-standard json file via python 找不到 AppData 文件以正确设置 Python 设置路径 - Can't find the AppData file in order to set up properly the Python Set Path 如何将 python 中的 json 文件中的值相加? - How do I add up values in a json file in python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM