Application with login and access control (Error: Typeerror: 'Nonetype' Object is not subscriptable)

Asked

Viewed 469 times

-1

I’m putting together a basic application with login and access control, that is, not all users can access the same windows. However I have a problem to load user information into the window after it does the login.

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

usuario_cadastro = str(result[4])

TypeError: 'NoneType' object is not subscriptable

py file.

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'

archive.K

<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

Note that print defined within the function is printed on the first lines login() that is within the class MainScreen()

**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 job login(), within the class TelaInicial(), shows the error

My understanding is that in the window TelaInicial I don’t have the same fields as on the screen Login, therefore the crud.db_select() cannot store values. But my doubt arises: the values I am returning within login(), are values stored in variables, or I am not doing another db_select(), I’m just returning the values that are already saved.

How do I get around this situation more simply?

  • 1

    Its variable result is the return of crud.db_select and seems to be None. Make sure the function db_select is returning something before using it.

  • @Andersoncarloswoss When I print a variable result within the function login(), it and returns the data correctly, but when I call the same function login() only that within the other class, the same variables return to me None. I thought of a way to record the variables in a place that is global, but anywhere I call the function login() out of class MainScreen() she returns to me None

1 answer

0

TypeError: 'NoneType' object is not subscriptable

Let’s analyze the error message. You’re saying an object of the type NoneType is not subscriptable. Well, the only object NoneType that exists is the None, so that means the code is trying to access elements within None. By the line you pointed out, this can only be happening in the object that is on 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
  • When I give a print(result) within the function login() I can get the data, but when I call the function login() outside the scope of the class MainScreen() she returns to me None.

  • @Renanf. Legal sap if you put the complete error, with traceback, for us to see right and no doubt, where is the error. You can edit the question and add? The line you put that is giving error is within the function, so there is no way it is returning None if the error is inside her!

  • I added the traceback along with some more information

Browser other questions tagged

You are not signed in. Login or sign up in order to post.