Python3-Mac OS-django配置MySQL数据库

     用django框架开发项目,肯定要用到数据库做存储。今天做个笔记,怎么配置MySQL数据库,在Mac OS上做配置还遇到了一个小麻烦,一并记录下来吧!

1、进入到提前准备好的django_test虚拟环境(要提前安装虚拟环境哦)。

workon django_test #进入django_test虚拟环境

2、pip3安装mysqlclient

pip3 install mysqlclient #安装mysqlclient

就这一步不顺利(ps:我的Mac 之前用dmg包安装过mysql)。报错了,一屏幕的红色啊,吓死宝宝了!主要的错误就是最后写的mysql_config not found。然后就查呗。

终于在参考:【1】的stackOver中找到了并解决了问题。

 解决问题的办法就是在Terminal中输入一行命令,问题解决了。继续喽。下面再项目框架的settings.py中做配置

export PATH=$PATH:/usr/local/mysql/bin

 

 3、配置settings.py

#数据库配置
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'django_test',
        'HOST': '127.0.0.1',
        'USER': 'root',
        'PASSWORD': 'root',
        'PORT': 3306
    }
}

 4、在settings.py中把数据库配置好之后,我们就要紧接着配置modles.py了。我们新建一个类,是User类

from django.db import models

class User(models.Model):
    #db_column 表中的字段名
    uid = models.AutoField(primary_key=True, db_column='uid')
    username = models.CharField(max_length=30, unique=True)
    password = models.CharField(max_length=128)
    create_time = models.DateTimeField(auto_now_add=True)
    #元数据,模型本身信息
    class Meta:
        db_table = 'user' #表名
        ordering = 'username' #排序 

5、上一步模型创建好啦.....接下来我们通过两个命令在数据库中生成对应的表。ps(数据迁移的问题可以再看一下这里)

python manage.py makemigrations (应用名,选写) 
python manage.py migrate (应用名,选写)

吃着火锅唱着歌,等待着顺利的结果。但是又报错了。

(django_test) look@lookdeMacBook-Pro django_test_project % python3 manage.py makemigrations
Traceback (most recent call last):
  File "/Users/look/Documents/pysource/django_test_project/manage.py", line 21, in <module>
    main()
  File "/Users/look/Documents/pysource/django_test_project/manage.py", line 17, in main
    execute_from_command_line(sys.argv)
  .....
  .....
  .....
  File "/Users/look/Documents/.envs/django_test/lib/python3.9/site-packages/django/db/backends/mysql/features.py", line 82, in is_sql_auto_is_null_enabled
    cursor.execute('SELECT @@SQL_AUTO_IS_NULL')
  File "/Users/look/Documents/.envs/django_test/lib/python3.9/site-packages/django/db/backends/utils.py", line 103, in execute
    sql = self.db.ops.last_executed_query(self.cursor, sql, params)
  File "/Users/look/Documents/.envs/django_test/lib/python3.9/site-packages/django/db/backends/mysql/operations.py", line 146, in last_executed_query
    query = query.decode(errors='replace')
AttributeError: 'str' object has no attribute 'decode' 

叮了咣啷的一顿查阅,说是要改operations.py这个文件(参考:【2】)那就改呗。主要就是把query.decode()改成query.encode()

改好了,我们再来一发试试看。 

 开始生成表

 

再去看看你的数据库,惊不惊喜,意不意外,有了。我们继续

 6、我们在应用中的路由文件urls.py中写个路由:

from django.contrib import admin
from django.urls import path

from App import views2

app_name = "App" #应用名空间
urlpatterns = [

    #CRUD的操作
    path('add_user/', views2.addUser, name='add_user')

]

7、新建一个veiws2.py文件。里面写保存数据库的数据

from django.http import HttpResponse

from App.models import User

def addUser(request):
    user = User(username='zs', password='123')
    user.save()
    return HttpResponse('添加用户成功')

8、好期待,离成功就差一步啦。用命令:python3 manager.py runserver 启动项目。震惊了,又报错了。

(django_test) look@lookdeMacBook-Pro django_test_project % python3 manage.py runserver
Watching for file changes with StatReloader
Exception in thread Thread-1:
Traceback (most recent call last):
  File "/usr/local/Cellar/python@3.9/3.9.1_4/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 954, in _bootstrap_inner
    self.run()
....
....
 File "/Users/look/Documents/.envs/django_test/lib/python3.9/site-packages/django/db/backends/mysql/base.py", line 15, in <module>
    import MySQLdb as Database
  File "/Users/look/Documents/.envs/django_test/lib/python3.9/site-packages/MySQLdb/__init__.py", line 24, in <module>
    version_info, _mysql.version_info, _mysql.__file__
NameError: name '_mysql' is not defined

 哎!!!这就是码农的生活啊。继续解决报错呗。找来找去说是要在项目的__init__.py文件中添加一段。来试试看。

import pymysql
pymysql.version_info = (1, 4, 13, "final", 0)
pymysql.install_as_MySQLdb()

添加好了,在来启动项目。不知道你的行不行。我是终于启动了。好心酸。不容易啊。好嘞!浏览器访问: http://127.0.0.1/add_user 走起。没报错,嘿嘿!那应该是没问题了。数据库看一把。数据进去了。完成!

其他的查,改,删就不写了。主要是第一步成功迈出去,第二步,第三步,就应该没啥大问题了。 

参考:

  【1】https://stackoverflow.com/questions/25459386/mac-os-x-environmenterror-mysql-config-not-found

  【2】CSDN, https://blog.csdn.net/tianxinyiru/article/details/107670638

  【3】简书,https://www.jianshu.com/p/1f0c8e3c438b

原文地址:https://www.cnblogs.com/happyflyingpig/p/14337953.html