Aula 08 – Curso de Django
Criando uma primeira aplicação com Django e mysql no windows
Configurando o Django para trabalhar com o mysql
https://docs.djangoproject.com/pt-br/1.11/intro/tutorial02/
Página Principal
Todas as Aulas da App Polls
AULA 07 AULA 09
Primeira coisa, adicionar o caminho da pasta bin do mysql server ao Path do windows
Vá em painel de controle, sistemas, configurações avançadas do sistema, variáveis de ambiente, aí então você vai criar as variáveis de ambientes, MYSQL_HOME, com o caminho de onde seu mysql está instalado, é a pasta do m, normalmente o caminho é:
C:\Program Files\MySQL\MySQL Server 5.7\bin
Mas, é preciso identificar se no seu sistema também é esse o caminho.
Agora você precisa adicionar essa variável de ambiente na variável Path do seu sistema.
A variável Path do seu sistema tem o caminho de todos os programas que você tem no seu computador.
Você vai até o final da lista que Path guarda, a lista é separada por ponto e vírgula, você vai acrescentar um ponto e vírgula no final se não tiver, e em seguida adicionar a variável MYSQL_HOME.
Vamos dizer que no final da variável Path tenha:
…….;C:\Ruby24-x64\bin; C:\Users\toti.cavalcanti\AppData\Roaming\npm;
Você vai acrescentar no final, a variável MYSQL_HOME, ficando assim:
C:\Ruby24-x64\bin; C:\Users\toti.cavalcanti\AppData\Roaming\npm;%MYSQL_HOME%;
Vamos criar o banco de dados da app, para isso vamos entrar no console do mysql como usuário root, para isso, digite:
OBS: Feche o cmd se tiver aberto e abra outro e digite:
mysql -u root -p
-u root pra entrar como usuário root do mysql e o -p pra pedir a password, você vai digitar a password definida quando você instalou o mysql no windows e dá enter.
O prompt muda para o prompt do mysql.
Agora crie um usuário chamado django, com privilégio de acesso root.
CREATE USER 'django'@'localhost' IDENTIFIED BY 'sua_senha';
Dê a permissão para o usuário django:
GRANT ALL PRIVILEGES ON *.* TO 'django'@'localhost' IDENTIFIED BY 'sua_senha';
Agora vamos criar o banco de dados da app no mysql:
CREATE DATABASE db_mysite;
Para selecionar o banco use:
USE db_mysite;
Saia do shell do mysql com:
exit
Depois de criar uma app, é preciso registrá-la no arquivo de configuração do projeto, o settings.py:
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls',
]
INSTALLED_APPS possui os nomes de todas as aplicações Django ativas para essa instância do Django.
Aplicações podem ser usadas em múltiplos projetos, e você pode empacotá-las e distribuí-las para uso em outros projetos. Pode parecer difícil, mas por trás de todo profissional existe muita experiência no papertyper.net, e é preciso prática para adquiri-la. Então pratique, repita e aprenda e você terá sucesso.
As aplicações que já estão lá por padrão, são incluídas como uma conveniência já que são comuns em vários projetos.
Ainda no settings.py vamos mudar o TIME_ZONE e o LANGUAGE_CODE :
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
Para:
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'pt-br'
TIME_ZONE = 'America/Sao_Paulo'
USE_I18N = True
USE_L10N = True
USE_TZ = True
Continuando no settings.py vamos mudar a configuração do DATABASE:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'db_mysite',
'USER': 'django',
'PASSWORD': 'sua_senha',
'HOST': 'localhost', # Or an IP Address that your DB is hosted on
'PORT': '3306',
}
}
Caso dê erro informando que não encontrou mysqlclient, tente o comando:
pip install mysqlclient
Depois execute novamente o migrate com:
python manage.py migrate
O comando migrate verifica a configuração em INSTALLED_APPS e cria a(s) tabela(s) do banco de dados necessária(s) de acordo com as configurações do banco de dados no seu arquivo mysite/settings.py e as migrações que venham com a app.
É mostrado uma mensagem para cada migração aplicada.
Parceiro, não consegui instalar o mysqlclient. Aparece esse erro:
—————————————-
Failed building wheel for mysqlclient
Running setup.py clean for mysqlclient
Failed to build mysqlclient
Installing collected packages: mysqlclient
Running setup.py install for mysqlclient … error
Complete output from command r:\django\tenv\scripts\python.exe -u -c “import setuptools, tokenize;__file__=’c:\\users\\rapha\\appdata\\local\\temp\\pip-install-co1vxs\\mysqlclient\\setup.py’;f=getattr(tokenize, ‘open’, open)(__file__);code=f.read().replace(‘\r\n’, ‘\n’);f.close();exec(compile(code, __file__, ‘exec’))” install –record c:\users\rapha\appdata\local\temp\pip-record-xxw8x9\install-record.txt –single-version-externally-managed –compile –install-headers r:\django\tenv\include\site\python2.7\mysqlclient:
running install
running build
running build_py
creating build
creating build\lib.win-amd64-2.7
copying _mysql_exceptions.py -> build\lib.win-amd64-2.7
creating build\lib.win-amd64-2.7\MySQLdb
copying MySQLdb\__init__.py -> build\lib.win-amd64-2.7\MySQLdb
copying MySQLdb\compat.py -> build\lib.win-amd64-2.7\MySQLdb
copying MySQLdb\connections.py -> build\lib.win-amd64-2.7\MySQLdb
copying MySQLdb\converters.py -> build\lib.win-amd64-2.7\MySQLdb
copying MySQLdb\cursors.py -> build\lib.win-amd64-2.7\MySQLdb
copying MySQLdb\release.py -> build\lib.win-amd64-2.7\MySQLdb
copying MySQLdb\times.py -> build\lib.win-amd64-2.7\MySQLdb
creating build\lib.win-amd64-2.7\MySQLdb\constants
copying MySQLdb\constants\__init__.py -> build\lib.win-amd64-2.7\MySQLdb\constants
copying MySQLdb\constants\CLIENT.py -> build\lib.win-amd64-2.7\MySQLdb\constants
copying MySQLdb\constants\CR.py -> build\lib.win-amd64-2.7\MySQLdb\constants
copying MySQLdb\constants\ER.py -> build\lib.win-amd64-2.7\MySQLdb\constants
copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win-amd64-2.7\MySQLdb\constants
copying MySQLdb\constants\FLAG.py -> build\lib.win-amd64-2.7\MySQLdb\constants
copying MySQLdb\constants\REFRESH.py -> build\lib.win-amd64-2.7\MySQLdb\constants
running build_ext
building ‘_mysql’ extension
creating build\temp.win-amd64-2.7
creating build\temp.win-amd64-2.7\Release
C:\Users\Rapha\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\Bin\amd64\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -Dversion_info=(1,3,12,’final’,0) -D__version__=1.3.12 “-IC:\Program Files (x86)\MySQL\MySQL Connector C 6.1\include” -IC:\Python27\include -Ir:\django\tenv\PC /Tc_mysql.c /Fobuild\temp.win-amd64-2.7\Release\_mysql.obj /Zl
_mysql.c
_mysql.c(29) : fatal error C1083: Cannot open include file: ‘mysql.h’: No such file or directory
error: command ‘C:\\Users\\Rapha\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++ for Python\\9.0\\VC\\Bin\\amd64\\cl.exe’ failed with exit status 2
—————————————-
Command “r:\django\tenv\scripts\python.exe -u -c “import setuptools, tokenize;__file__=’c:\\users\\rapha\\appdata\\local\\temp\\pip-install-co1vxs\\mysqlclient\\setup.py’;f=getattr(tokenize, ‘open’, open)(__file__);code=f.read().replace(‘\r\n’, ‘\n’);f.close();exec(compile(code, __file__, ‘exec’))” install –record c:\users\rapha\appdata\local\temp\pip-record-xxw8x9\install-record.txt –single-version-externally-managed –compile –install-headers r:\django\tenv\include\site\python2.7\mysqlclient” failed with error code 1 in c:\users\rapha\appdata\local\temp\pip-install-co1vxs\mysqlclient\
poderia me ajudar?
Olá Raphael, o erro diz que não consegue abrir o arquivo de include mysql.h (fatal error C1083: Cannot open include file: ‘mysql.h’), tenta desinstalar o mysql, reinicia a máquina e reinstala ele.
Outra coisa a fazer é verificar se a variável de ambiente do mysql (MYSQL_HOME), tá apontando pro diretório do mysql, que no meu caso é:
C:\Program Files\MySQL\MySQL Server 5.7\bin\
Sugiro que você refaça toda parte de criar a variável (MYSQL_HOME) e colocar no PATH do windows.
Outra parte do erro diz:
Failed building wheel for mysqlclient
Running setup.py clean for mysqlclient
Failed to build mysqlclient
Installing collected packages: mysqlclient
Running setup.py install for mysqlclient … error
Dá uma verificada se o PIP está instalado:
pip -V
ou
which pip
Se não estiver instalado, instale ele:
Baixa o get-pip.py em:
https://bootstrap.pypa.io/get-pip.py
Coloca ele na pasta de scripts do python, no meu caso:
C:\Users\toti.cavalcanti\AppData\Local\Programs\Python\Python36\Scripts\
Pelo cmd, entre na pasta onde você colocou e roda ele com:
python get-pip.py
Se o PIP tiver instalado e continuar com o problema, tenta rodar:
pip install -U wheel
Qualquer coisa, entra em contato de novo.
Abs,
Toti
Olá Raphael, acho que a sua instalação do mysql não tá legal, veja que o erro fala Cannot open include file: ‘mysql.h’: No such file or directory
error, o arquivo mysql.h não tá sendo localizado. Desinstala o mysql, apaga a pasta dele, reinicia a máquina e reinstala.
Depois roda o comando.
pip install wheel
Baixa o arquivo para seu sistema no link:
http://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python
Para o python 3.x:
pip install mysqlclient-1.3.8-cp36-cp36m-win_amd64.whl
Para o python 2.7:
pip install mysqlclient-1.3.8-cp27-cp27m-win_amd64.whl
Vê se resolve.
Abs,
Toti
solução usando esse comnado: pip install mysqlclient==1.3.4
Tive o mesmo problema. Tentei aplicar a mesma solução mas nao consegui resolver.
Não consigo aplicar o migrate. Faço diz:
Running migrations:
No migrations to apply.
(virtual_01) C:\Users\rlpro\mysite>pip install mysqlclient
Collecting mysqlclient
Using cached https://files.pythonhosted.org/packages/6f/86/bad31f1c1bb0cc99e88ca2adb7cb5c71f7a6540c1bb001480513de76a931/mysqlclient-1.3.12.tar.gz
Building wheels for collected packages: mysqlclient
Running setup.py bdist_wheel for mysqlclient … error
Complete output from command c:\users\rlpro\ambientes_virtuais\virtual_01\scripts\python.exe -u -c “import setuptools, tokenize;__file__=’C:\\Users\\rlpro\\AppData\\Local\\Temp\\pip-install-7h3m70ff\\mysqlclient\\setup.py’;f=getattr(tokenize, ‘open’, open)(__file__);code=f.read().replace(‘\r\n’, ‘\n’);f.close();exec(compile(code, __file__, ‘exec’))” bdist_wheel -d C:\Users\rlpro\AppData\Local\Temp\pip-wheel-puvfdo9y –python-tag cp37:
running bdist_wheel
running build
running build_py
creating build
creating build\lib.win-amd64-3.7
copying _mysql_exceptions.py -> build\lib.win-amd64-3.7
creating build\lib.win-amd64-3.7\MySQLdb
copying MySQLdb\__init__.py -> build\lib.win-amd64-3.7\MySQLdb
copying MySQLdb\compat.py -> build\lib.win-amd64-3.7\MySQLdb
copying MySQLdb\connections.py -> build\lib.win-amd64-3.7\MySQLdb
copying MySQLdb\converters.py -> build\lib.win-amd64-3.7\MySQLdb
copying MySQLdb\cursors.py -> build\lib.win-amd64-3.7\MySQLdb
copying MySQLdb\release.py -> build\lib.win-amd64-3.7\MySQLdb
copying MySQLdb\times.py -> build\lib.win-amd64-3.7\MySQLdb
creating build\lib.win-amd64-3.7\MySQLdb\constants
copying MySQLdb\constants\__init__.py -> build\lib.win-amd64-3.7\MySQLdb\constants
copying MySQLdb\constants\CLIENT.py -> build\lib.win-amd64-3.7\MySQLdb\constants
copying MySQLdb\constants\CR.py -> build\lib.win-amd64-3.7\MySQLdb\constants
copying MySQLdb\constants\ER.py -> build\lib.win-amd64-3.7\MySQLdb\constants
copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win-amd64-3.7\MySQLdb\constants
copying MySQLdb\constants\FLAG.py -> build\lib.win-amd64-3.7\MySQLdb\constants
copying MySQLdb\constants\REFRESH.py -> build\lib.win-amd64-3.7\MySQLdb\constants
running build_ext
building ‘_mysql’ extension
creating build\temp.win-amd64-3.7
creating build\temp.win-amd64-3.7\Release
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Dversion_info=(1,3,12,’final’,0) -D__version__=1.3.12 “-IC:\Program Files (x86)\MySQL\MySQL Connector C 6.1\include” -Ic:\users\rlpro\appdata\local\programs\python\python37\include -Ic:\users\rlpro\appdata\local\programs\python\python37\include “-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\INCLUDE” “-IC:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt” “-IC:\Program Files (x86)\Windows Kits\8.1\include\shared” “-IC:\Program Files (x86)\Windows Kits\8.1\include\um” “-IC:\Program Files (x86)\Windows Kits\8.1\include\winrt” /Tc_mysql.c /Fobuild\temp.win-amd64-3.7\Release\_mysql.obj /Zl
_mysql.c
_mysql.c(29): fatal error C1083: Cannot open include file: ‘mysql.h’: No such file or directory
error: command ‘C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\cl.exe’ failed with exit status 2
—————————————-
Failed building wheel for mysqlclient
Running setup.py clean for mysqlclient
Failed to build mysqlclient
Installing collected packages: mysqlclient
Running setup.py install for mysqlclient … error
Complete output from command c:\users\rlpro\ambientes_virtuais\virtual_01\scripts\python.exe -u -c “import setuptools, tokenize;__file__=’C:\\Users\\rlpro\\AppData\\Local\\Temp\\pip-install-7h3m70ff\\mysqlclient\\setup.py’;f=getattr(tokenize, ‘open’, open)(__file__);code=f.read().replace(‘\r\n’, ‘\n’);f.close();exec(compile(code, __file__, ‘exec’))” install –record C:\Users\rlpro\AppData\Local\Temp\pip-record-d6v6btby\install-record.txt –single-version-externally-managed –compile –install-headers c:\users\rlpro\ambientes_virtuais\virtual_01\include\site\python3.7\mysqlclient:
running install
running build
running build_py
creating build
creating build\lib.win-amd64-3.7
copying _mysql_exceptions.py -> build\lib.win-amd64-3.7
creating build\lib.win-amd64-3.7\MySQLdb
copying MySQLdb\__init__.py -> build\lib.win-amd64-3.7\MySQLdb
copying MySQLdb\compat.py -> build\lib.win-amd64-3.7\MySQLdb
copying MySQLdb\connections.py -> build\lib.win-amd64-3.7\MySQLdb
copying MySQLdb\converters.py -> build\lib.win-amd64-3.7\MySQLdb
copying MySQLdb\cursors.py -> build\lib.win-amd64-3.7\MySQLdb
copying MySQLdb\release.py -> build\lib.win-amd64-3.7\MySQLdb
copying MySQLdb\times.py -> build\lib.win-amd64-3.7\MySQLdb
creating build\lib.win-amd64-3.7\MySQLdb\constants
copying MySQLdb\constants\__init__.py -> build\lib.win-amd64-3.7\MySQLdb\constants
copying MySQLdb\constants\CLIENT.py -> build\lib.win-amd64-3.7\MySQLdb\constants
copying MySQLdb\constants\CR.py -> build\lib.win-amd64-3.7\MySQLdb\constants
copying MySQLdb\constants\ER.py -> build\lib.win-amd64-3.7\MySQLdb\constants
copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win-amd64-3.7\MySQLdb\constants
copying MySQLdb\constants\FLAG.py -> build\lib.win-amd64-3.7\MySQLdb\constants
copying MySQLdb\constants\REFRESH.py -> build\lib.win-amd64-3.7\MySQLdb\constants
running build_ext
building ‘_mysql’ extension
creating build\temp.win-amd64-3.7
creating build\temp.win-amd64-3.7\Release
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Dversion_info=(1,3,12,’final’,0) -D__version__=1.3.12 “-IC:\Program Files (x86)\MySQL\MySQL Connector C 6.1\include” -Ic:\users\rlpro\appdata\local\programs\python\python37\include -Ic:\users\rlpro\appdata\local\programs\python\python37\include “-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\INCLUDE” “-IC:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt” “-IC:\Program Files (x86)\Windows Kits\8.1\include\shared” “-IC:\Program Files (x86)\Windows Kits\8.1\include\um” “-IC:\Program Files (x86)\Windows Kits\8.1\include\winrt” /Tc_mysql.c /Fobuild\temp.win-amd64-3.7\Release\_mysql.obj /Zl
_mysql.c
_mysql.c(29): fatal error C1083: Cannot open include file: ‘mysql.h’: No such file or directory
error: command ‘C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\cl.exe’ failed with exit status 2
—————————————-
Command “c:\users\rlpro\ambientes_virtuais\virtual_01\scripts\python.exe -u -c “import setuptools, tokenize;__file__=’C:\\Users\\rlpro\\AppData\\Local\\Temp\\pip-install-7h3m70ff\\mysqlclient\\setup.py’;f=getattr(tokenize, ‘open’, open)(__file__);code=f.read().replace(‘\r\n’, ‘\n’);f.close();exec(compile(code, __file__, ‘exec’))” install –record C:\Users\rlpro\AppData\Local\Temp\pip-record-d6v6btby\install-record.txt –single-version-externally-managed –compile –install-headers c:\users\rlpro\ambientes_virtuais\virtual_01\include\site\python3.7\mysqlclient” failed with error code 1 in C:\Users\rlpro\AppData\Local\Temp\pip-install-7h3m70ff\mysqlclient\
Criei o banco… consigo consultar.
Oi Ricardo, descupe a demora pra responder, desinstala o mysql e reinstala novamente. Dá uma olhada nessa mensagem no final do log de erro:
mysql.c
_mysql.c(29): fatal error C1083: Cannot open include file: ‘mysql.h’: No such file or directory
error: command ‘C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\cl.exe’ failed with exit status 2
Não tá localizando o ‘mysql.h’, No such file or directory.
Na resposta ao comentário do Raphel Felipe eu mostrei mais ou menos como fazer isso.
pip install wheel
Baixa o arquivo para seu sistema no link:
http://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python
Para o python 3.x:
pip install mysqlclient-1.3.8-cp36-cp36m-win_amd64.whl
Para o python 2.7:
pip install mysqlclient-1.3.8-cp27-cp27m-win_amd64.whl
Só não sei se essa é a versão mais atual, dá uma verificada antes e troca a versão se for o caso.
Abraço
Toti
bom dia Toti!
Cara, isso significa que eu já rodei o migrate ou não?
C:\Users\rlpro\mysite>python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
No migrations to apply.
Como consulto isso no BD?
Como verifico esse comando.
Abraço,
Oi Ricardo, Tenta fazer o seguinte
Deleta o banco e cria novamente.
Apaga todos os arquivos de migração na pasta de migrations.
tenta rodar:
python manage.py makemigrations
e também:
python manage.py migrate
Vê se resolve.
Qualquer coisa me dá um toque, posso demorar um pouquinho pra responder, mas respondo.
Abraço.
Toti
Fala Toti.
Cara, a saga por aqui continua.
refiz toda a instalação. Mas estou tendo muito problemas com versão. como sou novato isso tem me custado um tempo.
agora to com o seguinte problema:
C:\Users\rlpro\mysite>python manage.py runserver
Traceback (most recent call last):
File “manage.py”, line 15, in
execute_from_command_line(sys.argv)
File “C:\Users\rlpro\appData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py”, line 371, in execute_from_command_line
utility.execute()
File “C:\Users\rlpro\appData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py”, line 317, in execute
settings.INSTALLED_APPS
File “C:\Users\rlpro\appData\Local\Programs\Python\Python37\lib\site-packages\django\conf\__init__.py”, line 56, in __getattr__
self._setup(name)
File “C:\Users\rlpro\appData\Local\Programs\Python\Python37\lib\site-packages\django\conf\__init__.py”, line 43, in _setup
self._wrapped = Settings(settings_module)
File “C:\Users\rlpro\appData\Local\Programs\Python\Python37\lib\site-packages\django\conf\__init__.py”, line 106, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File “C:\Users\rlpro\appData\Local\Programs\Python\Python37\lib\importlib\__init__.py”, line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File “”, line 1006, in _gcd_import
File “”, line 983, in _find_and_load
File “”, line 967, in _find_and_load_unlocked
File “”, line 677, in _load_unlocked
File “”, line 724, in exec_module
File “”, line 860, in get_code
File “”, line 791, in source_to_code
File “”, line 219, in _call_with_frames_removed
File “C:\Users\rlpro\mysite\mysite\settings.py”, line 81
‘USER’: ‘root’,
^
SyntaxError: invalid syntax
O python 3.7 roda com mysql 8.0???
Fala Ricardo,
Tá com erro de sintaxe no seu C:\Users\rlpro\mysite\mysite\settings.py na linha 81, as aspas que você usou estão erradas, você usou (‘ ’) em ‘USER’: ‘root’, note que elas são ligeiramente curvadas, na verdade você deve usar aspas (‘ ‘), ou seja, ‘USER’: ‘root’ e não ‘USER’: ‘root’. Aqui no post acho que não dá pra notar a diferença, mas as aspas que você usou são aspas simples, mas elas são ligeiramente curvadas.
Tenta aí e vê se resolve,
Abs,
Toti
Quando digito o pip install mysqlclient aparece o erro:
Collecting mysqlclient
Using cached https://files.pythonhosted.org/packages/f4/f1/3bb6f64ca7a429729413e6556b7ba5976df06019a5245a43d36032f1061e/mysqlclient-1.4.2.post1.tar.gz
Building wheels for collected packages: mysqlclient
Building wheel for mysqlclient (setup.py) … error
ERROR: Complete output from command ‘c:\users\anderson\ambientes_virtuais\ambientes_virtuais\virtual_01\scripts\python.exe’ -u -c ‘import setuptools, tokenize;__file__='”‘”‘C:\\Users\\Anderson\\AppData\\Local\\Temp\\pip-install-hob4ml5t\\mysqlclient\\setup.py'”‘”‘;f=getattr(tokenize, ‘”‘”‘open'”‘”‘, open)(__file__);code=f.read().replace(‘”‘”‘\r\n'”‘”‘, ‘”‘”‘\n'”‘”‘);f.close();exec(compile(code, __file__, ‘”‘”‘exec'”‘”‘))’ bdist_wheel -d ‘C:\Users\Anderson\AppData\Local\Temp\pip-wheel-y9rfnv_b’ –python-tag cp37:
ERROR: running bdist_wheel
running build
running build_py
creating build
creating build\lib.win32-3.7
creating build\lib.win32-3.7\MySQLdb
copying MySQLdb\__init__.py -> build\lib.win32-3.7\MySQLdb
copying MySQLdb\_exceptions.py -> build\lib.win32-3.7\MySQLdb
copying MySQLdb\compat.py -> build\lib.win32-3.7\MySQLdb
copying MySQLdb\connections.py -> build\lib.win32-3.7\MySQLdb
copying MySQLdb\converters.py -> build\lib.win32-3.7\MySQLdb
copying MySQLdb\cursors.py -> build\lib.win32-3.7\MySQLdb
copying MySQLdb\release.py -> build\lib.win32-3.7\MySQLdb
copying MySQLdb\times.py -> build\lib.win32-3.7\MySQLdb
creating build\lib.win32-3.7\MySQLdb\constants
copying MySQLdb\constants\__init__.py -> build\lib.win32-3.7\MySQLdb\constants
copying MySQLdb\constants\CLIENT.py -> build\lib.win32-3.7\MySQLdb\constants
copying MySQLdb\constants\CR.py -> build\lib.win32-3.7\MySQLdb\constants
copying MySQLdb\constants\ER.py -> build\lib.win32-3.7\MySQLdb\constants
copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win32-3.7\MySQLdb\constants
copying MySQLdb\constants\FLAG.py -> build\lib.win32-3.7\MySQLdb\constants
running build_ext
building ‘MySQLdb._mysql’ extension
creating build\temp.win32-3.7
creating build\temp.win32-3.7\Release
creating build\temp.win32-3.7\Release\MySQLdb
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Dversion_info=(1,4,2,’post’,1) -D__version__=1.4.2.post1 “-IC:\Program Files (x86)\MySQL\MySQL Connector C 6.1\include\mariadb” “-Ic:\program files (x86)\python37-32\include” “-Ic:\program files (x86)\python37-32\include” /TcMySQLdb/_mysql.c /Fobuild\temp.win32-3.7\Release\MySQLdb/_mysql.obj /Zl /D_CRT_SECURE_NO_WARNINGS
_mysql.c
MySQLdb/_mysql.c(29): fatal error C1083: Cannot open include file: ‘mysql.h’: No such file or directory
error: command ‘C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\bin\\cl.exe’ failed with exit status 2
—————————————-
ERROR: Failed building wheel for mysqlclient
Running setup.py clean for mysqlclient
Failed to build mysqlclient
Installing collected packages: mysqlclient
Running setup.py install for mysqlclient … error
ERROR: Complete output from command ‘c:\users\anderson\ambientes_virtuais\ambientes_virtuais\virtual_01\scripts\python.exe’ -u -c ‘import setuptools, tokenize;__file__='”‘”‘C:\\Users\\Anderson\\AppData\\Local\\Temp\\pip-install-hob4ml5t\\mysqlclient\\setup.py'”‘”‘;f=getattr(tokenize, ‘”‘”‘open'”‘”‘, open)(__file__);code=f.read().replace(‘”‘”‘\r\n'”‘”‘, ‘”‘”‘\n'”‘”‘);f.close();exec(compile(code, __file__, ‘”‘”‘exec'”‘”‘))’ install –record ‘C:\Users\Anderson\AppData\Local\Temp\pip-record-9zoo_o0e\install-record.txt’ –single-version-externally-managed –compile –install-headers ‘c:\users\anderson\ambientes_virtuais\ambientes_virtuais\virtual_01\include\site\python3.7\mysqlclient’:
ERROR: running install
running build
running build_py
creating build
creating build\lib.win32-3.7
creating build\lib.win32-3.7\MySQLdb
copying MySQLdb\__init__.py -> build\lib.win32-3.7\MySQLdb
copying MySQLdb\_exceptions.py -> build\lib.win32-3.7\MySQLdb
copying MySQLdb\compat.py -> build\lib.win32-3.7\MySQLdb
copying MySQLdb\connections.py -> build\lib.win32-3.7\MySQLdb
copying MySQLdb\converters.py -> build\lib.win32-3.7\MySQLdb
copying MySQLdb\cursors.py -> build\lib.win32-3.7\MySQLdb
copying MySQLdb\release.py -> build\lib.win32-3.7\MySQLdb
copying MySQLdb\times.py -> build\lib.win32-3.7\MySQLdb
creating build\lib.win32-3.7\MySQLdb\constants
copying MySQLdb\constants\__init__.py -> build\lib.win32-3.7\MySQLdb\constants
copying MySQLdb\constants\CLIENT.py -> build\lib.win32-3.7\MySQLdb\constants
copying MySQLdb\constants\CR.py -> build\lib.win32-3.7\MySQLdb\constants
copying MySQLdb\constants\ER.py -> build\lib.win32-3.7\MySQLdb\constants
copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win32-3.7\MySQLdb\constants
copying MySQLdb\constants\FLAG.py -> build\lib.win32-3.7\MySQLdb\constants
running build_ext
building ‘MySQLdb._mysql’ extension
creating build\temp.win32-3.7
creating build\temp.win32-3.7\Release
creating build\temp.win32-3.7\Release\MySQLdb
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Dversion_info=(1,4,2,’post’,1) -D__version__=1.4.2.post1 “-IC:\Program Files (x86)\MySQL\MySQL Connector C 6.1\include\mariadb” “-Ic:\program files (x86)\python37-32\include” “-Ic:\program files (x86)\python37-32\include” /TcMySQLdb/_mysql.c /Fobuild\temp.win32-3.7\Release\MySQLdb/_mysql.obj /Zl /D_CRT_SECURE_NO_WARNINGS
_mysql.c
MySQLdb/_mysql.c(29): fatal error C1083: Cannot open include file: ‘mysql.h’: No such file or directory
error: command ‘C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\bin\\cl.exe’ failed with exit status 2
—————————————-
ERROR: Command “‘c:\users\anderson\ambientes_virtuais\ambientes_virtuais\virtual_01\scripts\python.exe’ -u -c ‘import setuptools, tokenize;__file__='”‘”‘C:\\Users\\Anderson\\AppData\\Local\\Temp\\pip-install-hob4ml5t\\mysqlclient\\setup.py'”‘”‘;f=getattr(tokenize, ‘”‘”‘open'”‘”‘, open)(__file__);code=f.read().replace(‘”‘”‘\r\n'”‘”‘, ‘”‘”‘\n'”‘”‘);f.close();exec(compile(code, __file__, ‘”‘”‘exec'”‘”‘))’ install –record ‘C:\Users\Anderson\AppData\Local\Temp\pip-record-9zoo_o0e\install-record.txt’ –single-version-externally-managed –compile –install-headers ‘c:\users\anderson\ambientes_virtuais\ambientes_virtuais\virtual_01\include\site\python3.7\mysqlclient'” failed with error code 1 in C:\Users\Anderson\AppData\Local\Temp\pip-install-hob4ml5t\mysqlclient\
Olá Anderson,
Talvez seja problema de compatibilidade de versão do driver com a versão do python.
Vou deixar várias opções para você tentar:
Opção 1 – Tenta executar este comando no terminal (ou prompt de comando):
python3 -m pip install mysqlclient
Opção 2 – Tenta também baixar no https://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python o mysqlclient-1.4.2:
http://qpypi.qpython.org/repository/106911/mysqlclient-1.4.2.post1-cp37-cp37m-win_amd64.whl#8ce5525d5f90fb916b8d9ea2c42508d5
2.1 – Depois instalar:
pip install mysqlclient-1.4.2.post1-cp37-cp37m-win_amd64.whl
Opção 3 – pip install mysqlclient==1.4.24
3.1 – Se o comando acima não funcionar, tente:
pip install –only-binary :all: mysqlclient
Qualquer coisa me dá um retorno.
Abs. 😉
Que erro é esse?
(virtual_01) C:\Users\Genka\ambientes_virtuais\mysite>python manage.py migrate
Traceback (most recent call last):
File “C:\Users\Genka\ambientes_virtuais\virtual_01\lib\site-packages\django\db
\backends\base\base.py”, line 217, in ensure_connection
self.connect()
File “C:\Users\Genka\ambientes_virtuais\virtual_01\lib\site-packages\django\db
\backends\base\base.py”, line 195, in connect
self.connection = self.get_new_connection(conn_params)
File “C:\Users\Genka\ambientes_virtuais\virtual_01\lib\site-packages\django\db
\backends\mysql\base.py”, line 227, in get_new_connection
return Database.connect(**conn_params)
File “C:\Users\Genka\ambientes_virtuais\virtual_01\lib\site-packages\MySQLdb\_
_init__.py”, line 84, in Connect
return Connection(*args, **kwargs)
File “C:\Users\Genka\ambientes_virtuais\virtual_01\lib\site-packages\MySQLdb\c
onnections.py”, line 164, in __init__
super(Connection, self).__init__(*args, **kwargs2)
MySQLdb._exceptions.OperationalError: (2059, )
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File “manage.py”, line 21, in
main()
File “manage.py”, line 17, in main
execute_from_command_line(sys.argv)
File “C:\Users\Genka\ambientes_virtuais\virtual_01\lib\site-packages\django\co
re\management\__init__.py”, line 381, in execute_from_command_line
utility.execute()
File “C:\Users\Genka\ambientes_virtuais\virtual_01\lib\site-packages\django\co
re\management\__init__.py”, line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File “C:\Users\Genka\ambientes_virtuais\virtual_01\lib\site-packages\django\co
re\management\base.py”, line 323, in run_from_argv
self.execute(*args, **cmd_options)
File “C:\Users\Genka\ambientes_virtuais\virtual_01\lib\site-packages\django\co
re\management\base.py”, line 361, in execute
self.check()
File “C:\Users\Genka\ambientes_virtuais\virtual_01\lib\site-packages\django\co
re\management\base.py”, line 390, in check
include_deployment_checks=include_deployment_checks,
File “C:\Users\Genka\ambientes_virtuais\virtual_01\lib\site-packages\django\co
re\management\commands\migrate.py”, line 64, in _run_checks
issues = run_checks(tags=[Tags.database])
File “C:\Users\Genka\ambientes_virtuais\virtual_01\lib\site-packages\django\co
re\checks\registry.py”, line 72, in run_checks
new_errors = check(app_configs=app_configs)
File “C:\Users\Genka\ambientes_virtuais\virtual_01\lib\site-packages\django\co
re\checks\database.py”, line 10, in check_database_backends
issues.extend(conn.validation.check(**kwargs))
File “C:\Users\Genka\ambientes_virtuais\virtual_01\lib\site-packages\django\db
\backends\mysql\validation.py”, line 9, in check
issues.extend(self._check_sql_mode(**kwargs))
File “C:\Users\Genka\ambientes_virtuais\virtual_01\lib\site-packages\django\db
\backends\mysql\validation.py”, line 13, in _check_sql_mode
with self.connection.cursor() as cursor:
File “C:\Users\Genka\ambientes_virtuais\virtual_01\lib\site-packages\django\db
\backends\base\base.py”, line 256, in cursor
return self._cursor()
File “C:\Users\Genka\ambientes_virtuais\virtual_01\lib\site-packages\django\db
\backends\base\base.py”, line 233, in _cursor
self.ensure_connection()
File “C:\Users\Genka\ambientes_virtuais\virtual_01\lib\site-packages\django\db
\backends\base\base.py”, line 217, in ensure_connection
self.connect()
File “C:\Users\Genka\ambientes_virtuais\virtual_01\lib\site-packages\django\db
\utils.py”, line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File “C:\Users\Genka\ambientes_virtuais\virtual_01\lib\site-packages\django\db
\backends\base\base.py”, line 217, in ensure_connection
self.connect()
File “C:\Users\Genka\ambientes_virtuais\virtual_01\lib\site-packages\django\db
\backends\base\base.py”, line 195, in connect
self.connection = self.get_new_connection(conn_params)
File “C:\Users\Genka\ambientes_virtuais\virtual_01\lib\site-packages\django\db
\backends\mysql\base.py”, line 227, in get_new_connection
return Database.connect(**conn_params)
File “C:\Users\Genka\ambientes_virtuais\virtual_01\lib\site-packages\MySQLdb\_
_init__.py”, line 84, in Connect
return Connection(*args, **kwargs)
File “C:\Users\Genka\ambientes_virtuais\virtual_01\lib\site-packages\MySQLdb\c
onnections.py”, line 164, in __init__
super(Connection, self).__init__(*args, **kwargs2)
django.db.utils.OperationalError: (2059, )
Olá Andreia, desculpe a demora.
Seguinte, a parte principal da mensagem de erro diz: super(Connection, self).__init__(*args, **kwargs2)
MySQLdb._exceptions.OperationalError: (2059, )
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File “manage.py”, line 21, in
main()
File “manage.py”, line 17, in main
execute_from_command_line(sys.argv)
Acho que o problema é com o mysql.
Você conseguiu criar o banco do projeto dentro do console do mysql?
Me dá um retorno com mais detalhes para eu tentar te ajudar.
\o/ 😉
Olá caríssimos esse problema do windows e do mysql, julgo que é por causa de terem instalado a versão 32bits do python. Experimentem desinstalar essa versão e instalar a 64bits https://www.python.org/ftp/python/3.8.3/python-3.8.3-amd64.exe
Abraço,
Dinis
\o/ Dinis. Valeu pela dica.