Home > front end >  Configparser python giving error while trying to access any value [Python]
Configparser python giving error while trying to access any value [Python]

Time:11-05

I am using configparser to store username and password for a project I am developing. The file Info.ini has the following:

[Username]
user1 = Admin

[Password]
user1 = 


[Other]
firsttimeopen = True

The idea here is that, if firsttimeopen = True, then the password the user has inputted is stored instead of validated. Otherwise, the value of ['Password']['User1'] is compared with user input, and user is given access to the rest of the application.

To do this, I tried the following:

configs = configparser.ConfigParser()

with open('Info.ini', 'r') as configfile:
    configs.read(configfile)


class verifyLogin():
    def __init__(self, user, passw):
        self.username = user
        self.password = passw

        
        if configs['Other']['firsttimeopen'] == "True":
            self.CreatePassword()
        
        else:
            self.verifyLoginFunc()

    def verifyLoginFunc(self):
        if self.password == configs['Password']['User1']:
            print("ENTER")  

        else:
            print("NO")

    def CreatePassword(self):
        
        configs.set('Password', 'User1', self.password)
        configs.set('Other', 'firsttimeopen', 'False')  
        

        with open('info.ini', 'w') as configfile:
             configs.write(configfile)

However, this throws the following error:

`

Traceback (most recent call last):
  File "c:\Users\?\Documents\Programming\Python\IA\LoginGUI.py", line 81, in clicked
    verifyLogin(username, password)
  File "c:\Users\?\Documents\Programming\Python\IA\LoginGUI.py", line 17, in __init__
    if configs['Password']['firsttimeopen'] == "True":
  File "C:\Users\?\AppData\Local\Programs\Python\Python310\lib\configparser.py", line 964, in __getitem__
    raise KeyError(key)
KeyError: 'Password'

PS: Idk if this is important or not, but to remake/delete the .ini file for testing I have another file test.py:

config = configparser.ConfigParser()
config['Username'] = {'User1': 'Admin'}
config['Password'] = {'User1': ''}
config['Other'] = {'firsttimeopen': "True"}

with open('info.ini', 'w') as configfile:
    config.write(configfile)

CodePudding user response:

Main error

Use configs.read('Info.ini') instead configs.write(...) to read config file.
See example 1 on this tutorial

From my test

I used the exactly same Init.ini file, but scripted python3 on its terminal

┌────(レナトの将軍)-[stackoverflow]
└─ $ python3
Python 3.10.8 (main, Oct 13 2022, 21:13:48) [GCC 12.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import configparser
>>> configs = configparser.ConfigParser()
>>> configs.read(open('Info.ini', 'r'))
[]
>>> configs.read('Info.ini')
['Info.ini']
>>> configs.items
<bound method RawConfigParser.items of <configparser.ConfigParser object at 0x7f15ed167d00>>
>>> configs['Other']
<Section: Other>
>>> configs['Other']['firsttimeopen']
'True'
>>> 

You can see configs.read(open('Info.ini', 'r')) returns empty list.

How you can you do it in a pro-level

Store login and passwords in a structured database

You can do it using configparser, but its not made for this. Try using a structured database like SQLite3.

Never store real password

Save the sha512 (or something like) hash of new passwords. On a login attempt, you have to hash the input password and then compare with the storaged hash. Its recommended to use salt also.

  • Related