Application with login and access control (Error: TypeError: 'NoneType' object is not subscriptable)

0

I'm putting together a basic application with login and access control, meaning not all users can access the same windows. However I have a problem loading the user information into the window after it has login .

When I try to make a function that loads the information used to log into the system using the function of another class, I get the following error:

usuario_cadastro = str(result[4])

TypeError: 'NoneType' object is not subscriptable

file.py

class MainScreen(Screen):
    label_text = StringProperty()

    def __init__(self, **args):
        super(MainScreen, self).__init__(**args)

    def login(self):

        # pega as informações do TextInput do kivy, na janela de login
        usuario = self.ids.usuario.text
        senha = self.ids.senha.text

        # faz uma busca no banco para retornar ID_USUARIO, NOME, SOBRENOME, PRIORIDADE, LOGIN, SENHA
        result = crud.db_select(usuario, senha)

        # guarda as informações retornadas do banco
        usuario_cadastro = str(result[4])
        senha_cadastro = str(result[5])
        prioridade_cadastro = int(result[3])

        # teste para mostrar as informações carregadas do banco
        print(usuario_cadastro)
        print(senha_cadastro)
        print(prioridade_cadastro)

        # guarda as informações que serão retornadas para serem usadas na proxima tela
        usuario_priori = usuario_cadastro, prioridade_cadastro


        #         
        """
        Comparação dos dados inseridos no text input com os dados que estão no banco

        """
        print('Login efetuado com sucesso')
        # se as informações forem válidas, a tela de login é alterada
        self.parent.current = 'telaInicial'

        # retorna os dados que serão usados na proxima tela 
       return usuario_priori

# classe da tela inicial após efetuar o login
class TelaInicial(Screen):
    def __init__(self, **args):
        super(TelaInicial, self).__init__(**args)

    # função que pega os valores retornados da função login e fazer a comparação com a prioridade do usuário cadastrado com a prioridade que o conteudo tem
    def permissao(self):
        # aqui ja acontece o erro
        result = MainScreen().login()

        # depois os dados seriam comparados dessa forma: (mas essa parte ja nao funcionar)
        prioridade = result[1]

        # pega o nome do botão que seria uma especie de id (ou seja a prioridade do botao)
        # nesse caso o botao teria prioridade = 1, pois o nome dele é '1'
        prioridade_botao = root.self.ids.btnAgrot.name
        if(str(prioridade) == prioridade_botao
            # troca para outra janela caso a prioridade do usuario e do botao sejam iguais
            self.parent.current = 'conteudo'

.kv file

<MainScreen>:
    name: 'main'
        GridLayout:
            cols: 1
            size_hint: .5, .5
            pos_hint: {"center_x": .5, "center_y": .3}
            TextInput:
                id: usuario
            TextInput:
                id: senha
                password: True
            Botao:
                id: btnLogin
                on_release: root.login()
                text: "Login"
<TelaInicial>:
    name: 'telaInicial'
        GridLayout:
            cols: 1
            size_hint: .4, 1.
            pos_hint: {"center_x": .5, "center_y": .5}
            Label:
                size_hint: 1., .3
                text: 'Informações do usuário'
            Botao:
                id: btnAgrot
                name: '1'
                size_hint: 1., .3
                text: "Exemplo"
                on_release: root.permissao()

Error:

renan
123
1
Login efetuado com sucesso
[ERROR  ] [Image       ] Error reading file data/img/kivy-logo.png
[INFO   ] [Base        ] Leaving application in progress...
 Traceback (most recent call last):
   File "C:/dev/APS/arquivo.py", line 439, in <module>
     janela.run()
   File "C:\Users\renan\Anaconda3\envs\devPython36\lib\site-packages\kivy\app.py", line 826, in run
     runTouchApp()
   File "C:\Users\renan\Anaconda3\envs\devPython36\lib\site-packages\kivy\base.py", line 502, in runTouchApp
     EventLoop.window.mainloop()
   File "C:\Users\renan\Anaconda3\envs\devPython36\lib\site-packages\kivy\core\window\window_sdl2.py", line 727, in mainloop
     self._mainloop()
   File "C:\Users\renan\Anaconda3\envs\devPython36\lib\site-packages\kivy\core\window\window_sdl2.py", line 460, in _mainloop
     EventLoop.idle()
   File "C:\Users\renan\Anaconda3\envs\devPython36\lib\site-packages\kivy\base.py", line 340, in idle
     self.dispatch_input()
   File "C:\Users\renan\Anaconda3\envs\devPython36\lib\site-packages\kivy\base.py", line 325, in dispatch_input
     post_dispatch_input(*pop(0))
   File "C:\Users\renan\Anaconda3\envs\devPython36\lib\site-packages\kivy\base.py", line 291, in post_dispatch_input
     wid.dispatch('on_touch_up', me)
   File "kivy\_event.pyx", line 707, in kivy._event.EventDispatcher.dispatch
   File "C:\Users\renan\Anaconda3\envs\devPython36\lib\site-packages\kivy\uix\behaviors\button.py", line 179, in on_touch_up
     self.dispatch('on_release')
   File "kivy\_event.pyx", line 703, in kivy._event.EventDispatcher.dispatch
   File "kivy\_event.pyx", line 1214, in kivy._event.EventObservers.dispatch
   File "kivy\_event.pyx", line 1098, in kivy._event.EventObservers._dispatch
   File "C:\Users\renan\Anaconda3\envs\devPython36\lib\site-packages\kivy\lang\builder.py", line 64, in custom_callback
     exec(__kvlang__.co_value, idmap)
   File "<string>", line 203, in <module>
   File "C:/dev/APS/arquivo.py", line 399, in permissao
     result = MainScreen().login()
   File "C:/dev/APS/arquivo.py", line 89, in login
     usuario_cadastro = str(result[4])
 TypeError: 'NoneType' object is not subscriptable

Process finished with exit code 1

Notice that in the first few lines the printouts defined within the login() function inside the MainScreen() class

**class MainScreen(Screen):**
        label_text = StringProperty()

        def __init__(self, **args):
            super(MainScreen, self).__init__(**args)

        **def login(self):**

            # pega as informações do TextInput do kivy, na janela de login
            usuario = self.ids.usuario.text
            senha = self.ids.senha.text

            # faz uma busca no banco para retornar ID_USUARIO, NOME, SOBRENOME, PRIORIDADE, LOGIN, SENHA
            result = crud.db_select(usuario, senha)

            # guarda as informações retornadas do banco
            usuario_cadastro = str(result[4])
            senha_cadastro = str(result[5])
            prioridade_cadastro = int(result[3])

            # teste para mostrar as informações carregadas do banco
            **print(usuario_cadastro)**
            **print(senha_cadastro)**
            **print(prioridade_cadastro)**

But when I call the function login() , inside the TelaInicial() class, it displays the error

My understanding is that in the TelaInicial window I do not have the same fields as the Login screen, so crud.db_select() can not save the values. But my question arises: the values I'm returning inside login() , are values stored in variables, ie I'm not doing another db_select() , I'm just returning the values that are already saved.

How do I work around this situation in a simpler way?

    
asked by anonymous 21.11.2018 / 09:52

1 answer

0
TypeError: 'NoneType' object is not subscriptable

Let's look at the error message. You are saying that an object of type NoneType is not subscriptable . Well, the only NoneType object that exists is None , so this means that the code is trying to access elements within None . From the line you pointed out, this can only be happening on the object that is in result ;

The problem can be solved simply by using a if :

if result is None:
    print('Usuario nao encontrado ou senha nao confere')
    return False
    
21.11.2018 / 12:28