6
respostas

Não estou conseguindo encontrar o erro no salvar, listar e salvar por id. Poderia me ajudar?

from models import Funcionario, Usuario

SQL_DELETA_FUNCIONARIO = 'delete from funcionario where id = %s'
SQL_FUNCIONARIO_POR_ID = 'SELECT id, nome, cargo, setor from funcionario where id = %s'
SQL_USUARIO_POR_ID = 'SELECT id, nome, senha from usuario where id = %s'
SQL_ATUALIZA_FUNCIONARIO = 'UPDATE funcionario SET nome=%s, cargo=%s, setor=%s where id = %s'
SQL_BUSCA_FUNCIONARIOS = 'SELECT id, nome, cargo, setor from funcionario'
SQL_CRIA_FUNCIONARIO = 'INSERT into funcionario (nome, cargo, setor) values (%s, %s, %s)'


class FuncionarioDao:
    def __init__(self, db):
        self.__db = db

    def salvar(self, funcionario):
        cursor = self.__db.connection.cursor()

        if (funcionario.id):
            cursor.execute(SQL_ATUALIZA_FUNCIONARIO, (funcionario.nome, funcionario.cargo, funcionario.setor, funcionario.id))
        else:
            cursor.execute(SQL_CRIA_FUNCIONARIO, [funcionario.nome, funcionario.cargo, funcionario.setor])
            funcionario.id = cursor.lastrowid
        self.__db.connection.commit()
        return funcionario

   def listar(self):
       cursor = self.__db.connection.cursor()
       cursor.execute(SQL_BUSCA_FUNCIONARIOS)
       funcionarios = traduz_funcionarios(cursor.fetchone())
       return funcionarios

   def busca_por_id(self, id):
        cursor = self.__db.connection.cursor()
        cursor.execute(SQL_FUNCIONARIO_POR_ID, (id,))
        tupla = cursor.fetchone()
        return Funcionario(tupla[1], tupla[2], tupla[3], id=tupla[0])

    def deletar(self, id):
        self.__db.connection.cursor().execute(SQL_DELETA_FUNCIONARIO, (id, ))
        self.__db.connection.commit()


class UsuarioDao:
    def __init__(self, db):
        self.__db = db

    def buscar_por_id(self, id):
        cursor = self.__db.connection.cursor()
        cursor.execute(SQL_USUARIO_POR_ID, (id,))
        dados = cursor.fetchone()
        usuario = traduz_usuario(dados) if dados else None
        return usuario


def traduz_funcionarios(funcionarios):
    def cria_funcionario_com_tupla(tupla):
        return Funcionario(tupla[1], tupla[2], tupla[3], id=tupla[0])
    return list(map(cria_funcionario_com_tupla, funcionarios))


def traduz_usuario(tupla):
    return Usuario(tupla[0], tupla[1], tupla[2])
6 respostas

Fala Leandro, como vai?

Qual erro você está tendo?

Performing system checks...

System check identified no issues (0 silenced).
May 05, 2020 - 20:54:57
Django version 3.0.6, using settings 'receita.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
[05/May/2020 20:55:01] "GET / HTTP/1.1" 200 9454
[05/May/2020 20:55:01] "GET /static/img/core-img/pizza.png HTTP/1.1" 404 1692
[05/May/2020 20:55:01] "GET /static/js/jquery/jquery-2.2.4.min.js HTTP/1.1" 404 1713
[05/May/2020 20:55:01] "GET /static/js/bootstrap/popper.min.js HTTP/1.1" 404 1704
[05/May/2020 20:55:01] "GET /static/js/bootstrap/bootstrap.min.js HTTP/1.1" 404 1713
[05/May/2020 20:55:01] "GET /static/js/plugins/plugins.js HTTP/1.1" 404 1689
[05/May/2020 20:55:01] "GET /static/img/core-img/logo.png HTTP/1.1" 404 1689
[05/May/2020 20:55:01] "GET /static/js/active.js HTTP/1.1" 404 1662
[05/May/2020 20:55:01] "GET /static/img/bg-img/foto_receita.png HTTP/1.1" 404 1707
[05/May/2020 20:55:08] "GET /receita HTTP/1.1" 200 9468
Not Found: /site.css
[05/May/2020 20:55:08] "GET /site.css HTTP/1.1" 404 2295
Not Found: /js/jquery/jquery-2.2.4.min.js
[05/May/2020 20:55:08] "GET /js/jquery/jquery-2.2.4.min.js HTTP/1.1" 404 2358
Not Found: /js/bootstrap/popper.min.js
[05/May/2020 20:55:08] "GET /js/bootstrap/popper.min.js HTTP/1.1" 404 2349
Not Found: /js/plugins/plugins.js
Not Found: /js/bootstrap/bootstrap.min.js
[05/May/2020 20:55:08] "GET /js/plugins/plugins.js HTTP/1.1" 404 2334
[05/May/2020 20:55:08] "GET /js/bootstrap/bootstrap.min.js HTTP/1.1" 404 2358
Not Found: /img/bg-img/tomate_banner.jpg
Not Found: /img/core-img/hamburger.png
[05/May/2020 20:55:09] "GET /img/bg-img/tomate_banner.jpg HTTP/1.1" 404 2355
[05/May/2020 20:55:09] "GET /img/core-img/hamburger.png HTTP/1.1" 404 2349
Not Found: /js/active.js
Not Found: /img/core-img/logo.png
[05/May/2020 20:55:09] "GET /js/active.js HTTP/1.1" 404 2307
[05/May/2020 20:55:09] "GET /img/core-img/logo.png HTTP/1.1" 404 2334
Not Found: /js/plugins/plugins.js
[05/May/2020 20:55:09] "GET /js/plugins/plugins.js HTTP/1.1" 404 2334
Not Found: /js/active.js
[05/May/2020 20:55:09] "GET /js/active.js HTTP/1.1" 404 2307
[05/May/2020 20:56:02] "GET / HTTP/1.1" 200 9454
[05/May/2020 20:56:02] "GET /static/img/core-img/pizza.png HTTP/1.1" 404 1692
[05/May/2020 20:56:02] "GET /static/js/jquery/jquery-2.2.4.min.js HTTP/1.1" 404 1713
[05/May/2020 20:56:02] "GET /static/js/bootstrap/popper.min.js HTTP/1.1" 404 1704
[05/May/2020 20:56:02] "GET /static/js/bootstrap/bootstrap.min.js HTTP/1.1" 404 1713
[05/May/2020 20:56:02] "GET /static/js/plugins/plugins.js HTTP/1.1" 404 1689
[05/May/2020 20:56:02] "GET /static/img/core-img/logo.png HTTP/1.1" 404 1689
[05/May/2020 20:56:02] "GET /static/img/bg-img/foto_receita.png HTTP/1.1" 404 1707
[05/May/2020 20:56:02] "GET /static/js/active.js HTTP/1.1" 404 1662
[05/May/2020 20:56:10] "GET /receita HTTP/1.1" 200 9468
Not Found: /site.css
[05/May/2020 20:56:10] "GET /site.css HTTP/1.1" 404 2295
Not Found: /js/jquery/jquery-2.2.4.min.js
[05/May/2020 20:56:10] "GET /js/jquery/jquery-2.2.4.min.js HTTP/1.1" 404 2358
Not Found: /js/bootstrap/popper.min.js
[05/May/2020 20:56:10] "GET /js/bootstrap/popper.min.js HTTP/1.1" 404 2349
Not Found: /js/bootstrap/bootstrap.min.js
[05/May/2020 20:56:10] "GET /js/bootstrap/bootstrap.min.js HTTP/1.1" 404 2358
Not Found: /img/core-img/logo.png
Not Found: /img/bg-img/tomate_banner.jpg
[05/May/2020 20:56:10] "GET /img/bg-img/tomate_banner.jpg HTTP/1.1" 404 2355
[05/May/2020 20:56:10] "GET /img/core-img/logo.png HTTP/1.1" 404 2334
Not Found: /js/plugins/plugins.js
Not Found: /js/active.js
[05/May/2020 20:56:10] "GET /js/plugins/plugins.js HTTP/1.1" 404 2334
Not Found: /img/core-img/hamburger.png
[05/May/2020 20:56:10] "GET /js/active.js HTTP/1.1" 404 2307
[05/May/2020 20:56:10] "GET /img/core-img/hamburger.png HTTP/1.1" 404 2349
Not Found: /js/active.js
[05/May/2020 20:56:10] "GET /js/active.js HTTP/1.1" 404 2307

Favor não considerar a resposta anterior!

\Python\PycharmProjects\app_cadastro\venv\Scripts\python.exe D:/Python/PycharmProjects/Jogo_teca/jogoteca.py
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 302-717-369
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [05/May/2020 22:07:32] "GET / HTTP/1.1" 500 -
Traceback (most recent call last):
  File "D:\Python\PycharmProjects\app_cadastro\venv\Lib\site-packages\flask\app.py", line 1997, in __call__
    return self.wsgi_app(environ, start_response)
  File "D:\Python\PycharmProjects\app_cadastro\venv\Lib\site-packages\flask\app.py", line 1985, in wsgi_app
    response = self.handle_exception(e)
  File "D:\Python\PycharmProjects\app_cadastro\venv\Lib\site-packages\flask\app.py", line 1540, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "D:\Python\PycharmProjects\app_cadastro\venv\Lib\site-packages\flask\_compat.py", line 33, in reraise
    raise value
  File "D:\Python\PycharmProjects\app_cadastro\venv\Lib\site-packages\flask\app.py", line 1982, in wsgi_app
    response = self.full_dispatch_request()
  File "D:\Python\PycharmProjects\app_cadastro\venv\Lib\site-packages\flask\app.py", line 1614, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "D:\Python\PycharmProjects\app_cadastro\venv\Lib\site-packages\flask\app.py", line 1517, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "D:\Python\PycharmProjects\app_cadastro\venv\Lib\site-packages\flask\_compat.py", line 33, in reraise
    raise value
  File "D:\Python\PycharmProjects\app_cadastro\venv\Lib\site-packages\flask\app.py", line 1612, in full_dispatch_request
    rv = self.dispatch_request()
  File "D:\Python\PycharmProjects\app_cadastro\venv\Lib\site-packages\flask\app.py", line 1598, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "D:\Python\PycharmProjects\Jogo_teca\jogoteca.py", line 25, in index
    lista = jogo_dao.listar()
  File "D:\Python\PycharmProjects\Jogo_teca\dao.py", line 27, in listar
    cursor = self.__db.connection.cursor()
  File "D:\Python\PycharmProjects\app_cadastro\venv\Lib\site-packages\flask_mysqldb\__init__.py", line 94, in connection
    ctx.mysql_db = self.connect
  File "D:\Python\PycharmProjects\app_cadastro\venv\Lib\site-packages\flask_mysqldb\__init__.py", line 81, in connect
    return MySQLdb.connect(**kwargs)
  File "D:\Python\PycharmProjects\app_cadastro\venv\Lib\site-packages\MySQLdb\__init__.py", line 84, in Connect
    return Connection(*args, **kwargs)
  File "D:\Python\PycharmProjects\app_cadastro\venv\Lib\site-packages\MySQLdb\connections.py", line 179, in __init__
    super(Connection, self).__init__(*args, **kwargs2)
MySQLdb._exceptions.OperationalError: (1045, "Access denied for user 'root'@'localhost' (using password: YES)")
127.0.0.1 - - [05/May/2020 22:07:33] "GET /?__debugger__=yes&cmd=resource&f=style.css HTTP/1.1" 200 -
127.0.0.1 - - [05/May/2020 22:07:33] "GET /?__debugger__=yes&cmd=resource&f=jquery.js HTTP/1.1" 200 -
127.0.0.1 - - [05/May/2020 22:07:33] "GET /?__debugger__=yes&cmd=resource&f=debugger.js HTTP/1.1" 200 -
127.0.0.1 - - [05/May/2020 22:07:33] "GET /?__debugger__=yes&cmd=resource&f=ubuntu.ttf HTTP/1.1" 200 -
127.0.0.1 - - [05/May/2020 22:07:33] "GET /?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200 -

insira seu código aqui

Opa Leandro, parece que suas credenciais pra acessar o banco de dados estão incorretas. Verifica se o usuário e senha que você inseriu estão corretos.

Abs.

O projeto está igual ao da alura.

D:\Python\PycharmProjects\app_cadastro\venv\Scripts\python.exe D:/Python/PycharmProjects/app_cadastro/cadastro.py
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 302-717-369
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [06/May/2020 23:31:58] "GET / HTTP/1.1" 500 -
Traceback (most recent call last):
  File "D:\Python\PycharmProjects\app_cadastro\venv\Lib\site-packages\flask\app.py", line 1997, in __call__
    return self.wsgi_app(environ, start_response)
  File "D:\Python\PycharmProjects\app_cadastro\venv\Lib\site-packages\flask\app.py", line 1985, in wsgi_app
    response = self.handle_exception(e)
  File "D:\Python\PycharmProjects\app_cadastro\venv\Lib\site-packages\flask\app.py", line 1540, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "D:\Python\PycharmProjects\app_cadastro\venv\Lib\site-packages\flask\_compat.py", line 33, in reraise
    raise value
  File "D:\Python\PycharmProjects\app_cadastro\venv\Lib\site-packages\flask\app.py", line 1982, in wsgi_app
    response = self.full_dispatch_request()
  File "D:\Python\PycharmProjects\app_cadastro\venv\Lib\site-packages\flask\app.py", line 1614, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "D:\Python\PycharmProjects\app_cadastro\venv\Lib\site-packages\flask\app.py", line 1517, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "D:\Python\PycharmProjects\app_cadastro\venv\Lib\site-packages\flask\_compat.py", line 33, in reraise
    raise value
  File "D:\Python\PycharmProjects\app_cadastro\venv\Lib\site-packages\flask\app.py", line 1612, in full_dispatch_request
    rv = self.dispatch_request()
  File "D:\Python\PycharmProjects\app_cadastro\venv\Lib\site-packages\flask\app.py", line 1598, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "D:\Python\PycharmProjects\app_cadastro\views.py", line 13, in index
    lista = funcionario_dao.listar()
  File "D:\Python\PycharmProjects\app_cadastro\dao.py", line 29, in listar
    funcionarios = traduz_funcionarios(cursor.fetchone())
  File "D:\Python\PycharmProjects\app_cadastro\dao.py", line 58, in traduz_funcionarios
    return list(map(cria_funcionario_com_tupla, funcionarios))
  File "D:\Python\PycharmProjects\app_cadastro\dao.py", line 57, in cria_funcionario_com_tupla
    return Funcionario(tupla[1], tupla[2], tupla[3], id=tupla[0])
TypeError: 'int' object is not subscriptable
127.0.0.1 - - [06/May/2020 23:31:58] "GET /?__debugger__=yes&cmd=resource&f=style.css HTTP/1.1" 200 -
127.0.0.1 - - [06/May/2020 23:31:58] "GET /?__debugger__=yes&cmd=resource&f=jquery.js HTTP/1.1" 200 -
127.0.0.1 - - [06/May/2020 23:31:59] "GET /?__debugger__=yes&cmd=resource&f=debugger.js HTTP/1.1" 200 -
127.0.0.1 - - [06/May/2020 23:31:59] "GET /?__debugger__=yes&cmd=resource&f=ubuntu.ttf HTTP/1.1" 200 -
127.0.0.1 - - [06/May/2020 23:31:59] "GET /?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200 -

Oi Leandro, como vai?

Aparentemente o erro está na função traduz_funcionarios. Percebi que na linha que utiliza esta função, você utiliza o método fetchone trazendo o resultado de apenas um único registro do banco, sugiro que mude para fetchall() e tente executar o projeto novamente:

Onde está:

funcionarios = traduz_funcionarios(cursor.fetchone())

Muda para:

funcionarios = traduz_funcionarios(cursor.fetchall())

O fetchall irá retornar todos os registros do seu banco, fazendo com que seja possível iterar sobre eles.

Caso isto não resolva seu problema, peço por gentileza que compartilhe todo o seu código conosco através de algum link no drive, para que possamos analisá-lo e sermos assertivos quanto ao erro.

Fico no aguardo.