GVKun编程网logo

设置Django以使用MySQL(django 使用mysql)

14

如果您对设置Django以使用MySQL和django使用mysql感兴趣,那么这篇文章一定是您不可错过的。我们将详细讲解设置Django以使用MySQL的各种细节,并对django使用mysql进行

如果您对设置Django以使用MySQLdjango 使用mysql感兴趣,那么这篇文章一定是您不可错过的。我们将详细讲解设置Django以使用MySQL的各种细节,并对django 使用mysql进行深入的分析,此外还有关于114-解决mysqlclient安装失败,及django使用mysql的一个天坑、19 01 17 Django 模型 使用mysql数据库、Django 3.0 中连接mysql 8.0,可以不使用pymysql ,升级Mysqlclient即可、Django db使用MySQL连接池的实用技巧。

本文目录一览:

设置Django以使用MySQL(django 使用mysql)

设置Django以使用MySQL(django 使用mysql)

我想稍微远离PHP,学习Python。为了使用Python进行Web开发,我需要一个框架来帮助模板和其他事情。

我有一台非生产服务器,用于测试所有Web开发内容。这是一个运行MariaDB而不是常见的MySQL服务器软件包的Debian 7.1 LAMP堆栈。

昨天我安装了Django并创建了我的第一个项目firstweb。我尚未更改任何设置。

这是我的第一个大困惑。在教程中,我跟随那个家伙安装了Django,开始了他的第一个项目,重新启动了Apache,从那时起Django就开始工作了。他转到浏览器,然后毫无问题地转到Django默认页面。

但是我,我必须进入我的firstweb文件夹并运行

python manage.py runserver myip:port

而且有效。没问题。但是我想知道它是否应该像这样工作,并且这是否会引起问题?

我的第二个问题是我想对其进行设置,以便它使用我的MySQL数据库。我进入/ firstweb / firstweb下的settings.py,看到了ENGINE和NAME,但不确定在这里放什么。

然后在USER,PASSWORD和HOST区域中,这是我的数据库及其凭据吗?如果我使用本地主机,是否可以将本地主机放在HOST区域中?

答案1

小编典典

MySQL支持很容易添加。在你的DATABASES字典中,你将有一个像这样的条目:

DATABASES = {    ''default'': {        ''ENGINE'': ''django.db.backends.mysql'',         ''NAME'': ''DB_NAME'',        ''USER'': ''DB_USER'',        ''PASSWORD'': ''DB_PASSWORD'',        ''HOST'': ''localhost'',   # Or an IP Address that your DB is hosted on        ''PORT'': ''3306'',    }}

从Django 1.7开始,你还可以选择使用MySQL 选项文件。你可以这样设置DATABASES数组来完成此操作:

DATABASES = {    ''default'': {        ''ENGINE'': ''django.db.backends.mysql'',        ''OPTIONS'': {            ''read_default_file'': ''/path/to/my.cnf'',        },    }}

你还需要/path/to/my.cnf使用上面的类似设置来创建文件

[client]database = DB_NAMEhost = localhostuser = DB_USERpassword = DB_PASSWORDdefault-character-set = utf8

使用Django 1.7中的这种新连接方法,了解已建立的顺序连接很重要:

1. OPTIONS.2. NAME, USER, PASSWORD, HOST, PORT3. MySQL option files.

换句话说,如果你在OPTIONS中设置数据库的名称,它将优先于NAME,而NAME将覆盖MySQL选项文件中的所有内容。

如果你只是在本地计算机上测试应用程序,则可以使用

python manage.py runserver

添加ip:port参数允许你自己的机器以外的其他机器访问你的开发应用程序。准备好部署应用程序后,建议你阅读djangobook上有关部署Django的章节

MySQL默认字符集通常不是utf-8,因此请确保使用以下sql创建数据库:

CREATE DATABASE mydatabase CHARACTER SET utf8 COLLATE utf8_bin

如果你正在使用Oracle的MySQL的连接器的ENGINE线应该是这样的:

''ENGINE'': ''mysql.connector.django'',

请注意,你首先需要在操作系统上安装mysql。

brew install mysql (MacOS)

此外,mysql客户端软件包已针对python 3进行了更改(MySQL-Client仅适用于python 2)

pip3 install mysqlclient

114-解决mysqlclient安装失败,及django使用mysql的一个天坑

114-解决mysqlclient安装失败,及django使用mysql的一个天坑

安装好MySQL之后,直接用Python进行操作是可以的,假设要在django中使用mysql,还需要安装pymysql,话不多说,直接安装:

pip3 install pymysql --user

 安装完之后,在setting进行如下配置:

 

1、首先在django工程的setting.py里,引入pymysql:

import os
import pymysql
pymysql.install_as_MySQLdb()

 

2、接着,在mysql里创建一个数据库,用来存储django里要存取的表格:

lzh@lzh-pc:~$ mysql -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 9
Server version: 8.0.17 MySQL Community Server - GPL

Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type ''help;'' or ''\h'' for help. Type ''\c'' to clear the current input statement.

mysql> CREATE DATABASE test_app CHARACTER SET utf8;
Query OK, 1 row affected, 1 warning (0.01 sec)

mysql> SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
| test_app           |
+--------------------+
5 rows in set (0.00 sec)

 

3、最后,配置django工程里的setting.py的database部分。其中name是在mysql里定义的某个数据库名:

# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases

DATABASES = {
    ''default'': {
        ''ENGINE'': ''django.db.backends.mysql'',
        ''NAME'': ''test_app'',
        ''USER'': ''root'',
        ''PASSWORD'': ''19830427'',
        ''HOST'': ''localhost'',
        ''PORT'': ''3306'',
    }
}

 

4、高能预警!

此时无论是直接runserver,还是makemigrations,都会报错,大致是:

raise ImproperlyConfigured(''mysqlclient 1.3.13 or newer is required; you have %s.'' % Database.__version__)
django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3.

但是请注意,如果用pip3 list查看,是根本没有mysqlclient这个包的,一定会有人想,如果没有这个包(或者版本太低),装一下不就行了。

 

5、安装mysqlclient,官网上列举了这些前置需求:

sudo apt-get install python3-dev

sudo apt-get install default-libmysqlclient-dev

如果把这两个安装完成后,再安装mysqlclient,仍然会报错,而且会报错一整屏幕红字,非常惊悚,仔细一看,主要是这里的问题:

/usr/bin/ld: 找不到 -lssl 
/usr/bin/ld: 找不到 -lcrypto

 安装其中一个即可:sudo apt-get install libssl-dev

【注意是libssl,少一个l】

到这里,就能正常安装mysqlclient了,使用命令:pip3 install mysqlclient --user

然后再用pip3 list就能查看到:

mysqlclient           1.4.4 

到了这里,你以为问题解决了,然后能愉快地运行runserver或makemigrations?非常遗憾!

仍然会报错:django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3.

这就不是版本的问题了,而是它永远都会出错!!!

File "/home/lzh/.local/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 36, in <module>
    raise ImproperlyConfigured(''mysqlclient 1.3.13 or newer is required; you have %s.'' % Database.__version__)
django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3.

 

 

6、大部分的人(网上看到的各种笔记,blog,经验分享)都是选择直接跳过这个错误,方法是编辑报错文件:gedit /home/yourusername/.local/lib/python3.6/site-packages/django/db/backends/mysql/base.py

将以下两行注释掉:

# if version < (1, 3, 13):
#     raise ImproperlyConfigured(''mysqlclient 1.3.13 or newer is required; you have %s.'' % Database.__version__)

 

尝试运行runserver或makemigrations,仍然出错:

File "/home/lzh/.local/lib/python3.6/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''

 解决这个报错的方法是:gedit /home/lzh/.local/lib/python3.6/site-packages/django/db/backends/mysql/opetions.py

将decode改为encode,代码为:

def last_executed_query(self, cursor, sql, params):
        # With MySQLdb, cursor objects have an (undocumented) "_executed"
        # attribute where the exact query sent to the database is saved.
        # See MySQLdb/cursors.py in the source distribution.
        query = getattr(cursor, ''_executed'', None)
        if query is not None:
            query = query.encode(errors=''replace'')
        return query

 

7、后记

安装了MySQL,然后安装了pymysql,就直接开始使用的,当报错时直接使用《6》的方法解决即可,个人怀疑是检查兼容性的代码有bug;

实际上,在bug没有解决前,费劲心思安装mysqlclient一点用处没有!

 

8、验证django使用mysql

(1)使用python3 manage.py createsuperuser创建超级管理员

(2)进入admin后台,添加一个guest:guest_name=刘振华,guest_title=先生

(3)查看mysql是否有对应内容

lzh@lzh-pc:~$ mysql -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 30
Server version: 8.0.17 MySQL Community Server - GPL

Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type ''help;'' or ''\h'' for help. Type ''\c'' to clear the current input statement.

mysql> USE test_app;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> SHOW TABLES;
+----------------------------+
| Tables_in_test_app         |
+----------------------------+
| auth_group                 |
| auth_group_permissions     |
| auth_permission            |
| auth_user                  |
| auth_user_groups           |
| auth_user_user_permissions |
| django_admin_log           |
| django_content_type        |
| django_migrations          |
| django_session             |
| test_app_cnbcontent        |
| test_app_cnbtitle          |
| test_app_guestmodel        |
+----------------------------+
13 rows in set (0.00 sec)

mysql> select * from test_app_guestmodel;
+----+------------+-------------+
| id | guest_name | guest_title |
+----+------------+-------------+
|  1 | 刘振华     | 先生        |
+----+------------+-------------+
1 row in set (0.00 sec)

 

19 01 17 Django 模型 使用mysql数据库

19 01 17 Django 模型 使用mysql数据库

今天演示使用MySQL数据库,这是Web项目首选的数据库。

进入虚拟环境py_django。

workon py_django

在/home/python/pytest目录下创建项目test2。

django-admin startproject test2

创建项目test2

打开test2/settings.py文件,找到DATABASES项,默认使用SQLite3数据库

数据库配置

修改为使用MySQL数据库,代码如下:

将引擎改为mysql,提供连接的主机HOST、端口PORT、数据库名NAME、用户名USER、密码PASSWORD。

DATABASES = {
    ''default'': {
        ''ENGINE'': ''django.db.backends.mysql'',
        ''NAME'': ''test2'', #数据库名字,
        ''USER'': ''root'', #数据库登录用户名
        ''PASSWORD'': ''mysql'', #数据库登录密码
        ''HOST'': ''localhost'', #数据库所在主机
        ''PORT'': ''3306'', #数据库端口
    }
}

注意:数据库test2 Django框架不会自动生成,需要我们自己进入mysql数据库去创建。

下面是手动创建数据库,打开新终端,在命令行登录mysql,创建数据库test2。

 

注意:设置字符集为utf8

create database test2 charset=utf8;


 

Django 3.0 中连接mysql 8.0,可以不使用pymysql ,升级Mysqlclient即可

Django 3.0 中连接mysql 8.0,可以不使用pymysql ,升级Mysqlclient即可

python 中,连接mysql一般都推荐用pymysql ,而且在django中,网上的教程都是这么连接mysql的.

import pymysql

pymysql.install_as_MySQLdb()

这实际是pymysql模块调用了模块中的一个函数 install_as_MySQLdb(),这个函数的注释是这么说的.

After this function is called, any application that imports MySQLdb or
_mysql will unwittingly actually use pymysql.

大概意思是:

  调用此函数后,任何导入MySQLdb或_mysql的应用程序都会在不经意间实际使用pymysql。

最近在使用Django 3.0 中, 导入 Pymsql的时候报错,提示Mysqlclient版本问题,.既然django 在我们选择使用MYSQL的情景时,实际自动调用的是MySQLdb, Pymysql是可有可无的,我就直接pip install 了最新版的MySQLdb, 版本号是1.4.6, 在没使用Pymysql, 也不用在settings中自己导入MySQLdb的情况下,顺利连接我的MySQL .

我本地的安装的是MySQL8.0 ,用来练习Django中的ORM操作,没有发现问题. 我还没测试过Mysql 5.6 5.7版本.估计也没问题,(注:django不支持Mysql5.6以下的版本)

看来老方法有 OUT 了的可能性.

发布出来供大家参考, 如果有版本兼容性问题,还劳烦在本帖下留言,供大家分享.

补充:

django3.0官方文档说,3.0需要mysqlclient 1.3.13或者更高版本的支持,并且mysqlclient是推荐的数据库驱动程序.

除了mysqlclient, django还可以使用Connector/Python 作为mysql的数据库驱动程序,这个驱动可以在dev.mysql.com下载. 这个驱动是Oracle提供的纯python驱动, 不需要MySQL客户端库或标准库之外的任何Python模块作为支持.

不管mysqlclient还是Connector/Python都支持线程安全和连接池特性。

原文出处:https://www.cnblogs.com/worldinmyeyes/p/12093495.html

Django db使用MySQL连接池

Django db使用MySQL连接池

Django db使用MySQL连接池

Sep 25 2016

Django db模块本身不支持MySQL连接池,只有一个配置CONN_MAX_AGE连接最大存活时间,如果WSGI服务器使用了线程池技术,会达到连接复用的效果。但是如果WSGI服务如果是每个请求都创建新的线程,那么这个配置没有任何效果,因为连接保存在Thread.local()名称空间中,在不同的线程中不能复用。

在上一篇greentor MySQL连接池实现中已经实现了MySQL连接池,只需要重写Django MySQL backend以支持连接池,就能达到连接复用的目的,减少socket 3次握手的开销,提高性能。

https://github.com/zhu327/greentor/blob/master/demo/core/base.py

 

from django.db.backends.mysql.base import (SafeText, SafeBytes, six,
    DatabaseWrapper as BaseDatabaseWrapper)
from greentor.mysql import ConnectionPool

class DatabaseWrapper(BaseDatabaseWrapper):
    u"""
    支持greentor mysql connection pool 的backends
    """
    pools = {} # 类变量用于保存所有不同数据库的连接

    def get_new_connection(self, conn_params):
        # conn = Database.connect(**conn_params)
        if not self.alias in self.pools: # 如果需要的数据库还没有连接池则新建连接池
            self.pools[self.alias] = ConnectionPool(mysql_params=conn_params)
        conn = self.pools[self.alias].get_conn() # 获取新的连接时从连接池中获取
        conn.encoders[SafeText] = conn.encoders[six.text_type]
        conn.encoders[SafeBytes] = conn.encoders[bytes]
        return conn

    def _close(self):
        if self.connection is not None: # 不再直接关闭连接,而是释放连接到连接池中
            self.pools[self.alias].release(self.connection)

  

修改数据库配置引擎

 1 DATABASES = {
 2     ''default'': {
 3         ''NAME'': ''test'',
 4         ''HOST'': ''127.0.0.1'',
 5         # ''ENGINE'': ''django.db.backends.mysql'',
 6         ''ENGINE'': ''core'',
 7         ''USER'': ''root'',
 8         ''PASSWORD'': '''',
 9     }
10 }

 

连接池backend的代码虽然很少,但是在尝试过程中,基本把Django db模块的代码都过了一遍,感觉自己又牛B了一点点,哈哈。

关于设置Django以使用MySQLdjango 使用mysql的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于114-解决mysqlclient安装失败,及django使用mysql的一个天坑、19 01 17 Django 模型 使用mysql数据库、Django 3.0 中连接mysql 8.0,可以不使用pymysql ,升级Mysqlclient即可、Django db使用MySQL连接池的相关知识,请在本站寻找。

本文标签: