设置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区域中?

I want to move away from PHP a little and learn Python. In order to do web development with Python I’ll need a framework to help with templating and other things.

I have a non-production server that I use to test all of web development stuff on. It is a Debian 7.1 LAMP stack that runs MariaDB instead of the common MySQL-server package.

Yesterday I installed Django and created my first project called firstweb. I have not changed any settings yet.

Here is my first big piece of confusion. In the tutorial I followed the guy installed Django, started his first project, restarted Apache, and Django just worked from then on. He went to his browser and went to the Django default page with no problems.

Me however, I have to cd into my firstweb folder and run

python manage.py runserver myip:port

And it works. No problem. But I’m wondering if it is supposed to work like this, and if this will cause problems down the line?

My second question is that I want to set it up so it uses my MySQL database. I go into my settings.py under /firstweb/firstweb and I see ENGINE and NAME but I’m not sure what to put here.

And then in the USER, PASSWORD, and HOST areas is this my database and its credentials? If I am using localhost can I just put localhost in the HOST area?


回答 0

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_NAME
host = localhost
user = DB_USER
password = DB_PASSWORD
default-character-set = utf8

使用Django 1.7中的这种新连接方法,重要的是要知道建立了顺序连接:

1. OPTIONS.
2. NAME, USER, PASSWORD, HOST, PORT
3. 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

MySQL support is simple to add. In your DATABASES dictionary, you will have an entry like this:

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',
    }
}

You also have the option of utilizing MySQL option files, as of Django 1.7. You can accomplish this by setting your DATABASES array like so:

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

You also need to create the /path/to/my.cnf file with similar settings from above

[client]
database = DB_NAME
host = localhost
user = DB_USER
password = DB_PASSWORD
default-character-set = utf8

With this new method of connecting in Django 1.7, it is important to know the order connections are established:

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

In other words, if you set the name of the database in OPTIONS, this will take precedence over NAME, which would override anything in a MySQL option file.


If you are just testing your application on your local machine, you can use

python manage.py runserver

Adding the ip:port argument allows machines other than your own to access your development application. Once you are ready to deploy your application, I recommend taking a look at the chapter on Deploying Django on the djangobook

Mysql default character set is often not utf-8, therefore make sure to create your database using this sql:

CREATE DATABASE mydatabase CHARACTER SET utf8 COLLATE utf8_bin

If you are using Oracle’s MySQL connector your ENGINE line should look like this:

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

Note that you will first need to install mysql on your OS.

brew install mysql (MacOS)

Also, the mysql client package has changed for python 3 (MySQL-Client works only for python 2)

pip3 install mysqlclient

回答 1

首先,请运行以下命令以安装python依赖项,否则python runserver命令将引发错误。

sudo apt-get install libmysqlclient-dev
sudo pip install MySQL-python

然后配置#Andy定义的settings.py文件,并在最后一次执行:

python manage.py runserver

玩得开心..!!

To the very first please run the below commands to install python dependencies otherwise python runserver command will throw error.

sudo apt-get install libmysqlclient-dev
sudo pip install MySQL-python

Then configure the settings.py file as defined by #Andy and at the last execute :

python manage.py runserver

Have fun..!!


回答 2

如果您使用的是python3.x,则运行以下命令

pip install mysqlclient

然后像这样更改setting.py

DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': 'DB',
     'USER': 'username',
    'PASSWORD': 'passwd',
  }
  }

If you are using python3.x then Run below command

pip install mysqlclient

Then change setting.py like

DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': 'DB',
     'USER': 'username',
    'PASSWORD': 'passwd',
  }
  }

回答 3

如上所述,您可以轻松地首先从https://www.apachefriends.org/download.html安装xampp, 然后按照以下说明进行操作:

  1. http://www.unixmen.com/install-xampp-stack-ubuntu-14-04/安装并运行xampp ,然后从GUI启动Apache Web Server和MySQL数据库。
  2. 您可以根据需要配置Web服务器,但默认情况下Web服务器位于http://localhost:80,数据库位于port 3306,而PhpMyadmin位于http://localhost/phpmyadmin/
  3. 从这里您可以看到您的数据库,并使用非常友好的GUI访问它们。
  4. 创建要在Django项目上使用的任何数据库。
  5. settings.py像这样编辑文件:

    DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'DB_NAME',
        'HOST': '127.0.0.1',
        'PORT': '3306',
        'USER': 'root',
        'PASSWORD': '',
    }}
  6. 在virtualenv中安装以下软件包(如果您在virtualenv上使用django,则更可取):

    sudo apt-get安装libmysqlclient-dev

    pip安装MySQL-python

  7. 而已!!您已经以非常简单的方式为MySQL配置了Django。

  8. 现在运行您的Django项目:

    python manage.py迁移

    python manage.py运行服务器

As all said above, you can easily install xampp first from https://www.apachefriends.org/download.html Then follow the instructions as:

  1. Install and run xampp from http://www.unixmen.com/install-xampp-stack-ubuntu-14-04/, then start Apache Web Server and MySQL Database from the GUI.
  2. You can configure your web server as you want but by default web server is at http://localhost:80 and database at port 3306, and PhpMyadmin at http://localhost/phpmyadmin/
  3. From here you can see your databases and access them using very friendly GUI.
  4. Create any database which you want to use on your Django Project.
  5. Edit your settings.py file like:

    DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'DB_NAME',
        'HOST': '127.0.0.1',
        'PORT': '3306',
        'USER': 'root',
        'PASSWORD': '',
    }}
    
  6. Install the following packages in the virtualenv (if you’re using django on virtualenv, which is more preferred):

    sudo apt-get install libmysqlclient-dev

    pip install MySQL-python

  7. That’s it!! you have configured Django with MySQL in a very easy way.

  8. Now run your Django project:

    python manage.py migrate

    python manage.py runserver


回答 4

实际上,不同的环境,python版本等等存在很多问题。您可能还需要安装python dev文件,因此要“强行安装”,我将运行所有这些文件:

sudo apt-get install python-dev python3-dev
sudo apt-get install libmysqlclient-dev
pip install MySQL-python
pip install pymysql
pip install mysqlclient

您应该接受公认的答案。如果对您很重要,可以删除不需要的软件包。

Actually, there are many issues with different environments, python versions, so on. You might also need to install python dev files, so to ‘brute-force’ the installation I would run all of these:

sudo apt-get install python-dev python3-dev
sudo apt-get install libmysqlclient-dev
pip install MySQL-python
pip install pymysql
pip install mysqlclient

You should be good to go with the accepted answer. And can remove the unnecessary packages if that’s important to you.


回答 5

运行这些命令

sudo apt-get install python-dev python3-dev
sudo apt-get install libmysqlclient-dev
pip install MySQL-python 
pip install pymysql
pip install mysqlclient

然后像这样配置settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'django_db',
        'HOST': '127.0.0.1',
        'PORT': '3306',
        'USER': 'root',
        'PASSWORD': '123456',
    }
}

享受mysql连接

Run these commands

sudo apt-get install python-dev python3-dev
sudo apt-get install libmysqlclient-dev
pip install MySQL-python 
pip install pymysql
pip install mysqlclient

Then configure settings.py like

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'django_db',
        'HOST': '127.0.0.1',
        'PORT': '3306',
        'USER': 'root',
        'PASSWORD': '123456',
    }
}

Enjoy mysql connection


回答 6

安迪的答案很有帮助,但是如果您担心要在django设置中公开数据库密码,我建议在mysql连接上遵循django官方配置:https : //docs.djangoproject.com/en/1.7/ref/databases/

在这里引用为:

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


# my.cnf
[client]
database = NAME
user = USER
password = PASSWORD
default-character-set = utf8

要在设置中替换“ HOST”:“ 127.0.0.1”,只需将其添加到my.cnf中:

# my.cnf
[client]
database = NAME
host = HOST NAME or IP
user = USER
password = PASSWORD
default-character-set = utf8

另一个有用的选项是为django设置存储引擎,您可能需要在setting.py中使用它:

'OPTIONS': {
   'init_command': 'SET storage_engine=INNODB',
}

Andy’s answer helps but if you have concern on exposing your database password in your django setting, I suggest to follow django official configuration on mysql connection: https://docs.djangoproject.com/en/1.7/ref/databases/

Quoted here as:

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


# my.cnf
[client]
database = NAME
user = USER
password = PASSWORD
default-character-set = utf8

To replace ‘HOST’: ‘127.0.0.1’ in setting, simply add it in my.cnf:

# my.cnf
[client]
database = NAME
host = HOST NAME or IP
user = USER
password = PASSWORD
default-character-set = utf8

Another OPTION that is useful, is to set your storage engine for django, you might want it in your setting.py:

'OPTIONS': {
   'init_command': 'SET storage_engine=INNODB',
}

回答 7

settings.py

DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': 'django',
    'USER': 'root',
    'PASSWORD': '*****',
    'HOST': '***.***.***.***',
    'PORT': '3306',
    'OPTIONS': {
        'autocommit': True,
    },
}

}

然后:

python manage.py migrate

如果成功将生成这些表:

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

您将可以使用mysql。

这是一个展示示例,请在Django 1.11.5版上进行测试: Django-pool-showcase

settings.py

DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': 'django',
    'USER': 'root',
    'PASSWORD': '*****',
    'HOST': '***.***.***.***',
    'PORT': '3306',
    'OPTIONS': {
        'autocommit': True,
    },
}

}

then:

python manage.py migrate

if success will generate theses tables:

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

and u will can use mysql.

this is a showcase example ,test on Django version 1.11.5: Django-pool-showcase


回答 8

  1. 安装 mysqlclient

sudo pip3 install mysqlclient

如果出现错误:

命令“ python setup.py egg_info”在/ tmp / pip-install-dbljg4tx / mysqlclient /中失败,错误代码为1

然后:

 1. sudo apt install libmysqlclient-dev python-mysqldb

 2. sudo pip3 install mysqlclient

  1. 修改settings.py

    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': 'website',
            'USER': 'root',
            'PASSWORD': '',
            'HOST': '127.0.0.1',
            'PORT': '3306',
            'OPTION': {'init_command':"SET sql_mode='STRICT_TRANS_TABLE',"},
        }
    }
  1. Install mysqlclient

sudo pip3 install mysqlclient

if you get error:

Command “python setup.py egg_info” failed with error code 1 in /tmp/pip-install-dbljg4tx/mysqlclient/

then:

 1. sudo apt install libmysqlclient-dev python-mysqldb

 2. sudo pip3 install mysqlclient

  1. Modify settings.py

    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': 'website',
            'USER': 'root',
            'PASSWORD': '',
            'HOST': '127.0.0.1',
            'PORT': '3306',
            'OPTION': {'init_command':"SET sql_mode='STRICT_TRANS_TABLE',"},
        }
    }
    

回答 9

请按照给定的步骤进行设置以使用MySQL数据库:

1) Install MySQL Database Connector :

    sudo apt-get install libmysqlclient-dev

2) Install the mysqlclient library :

    pip install mysqlclient

3) Install MySQL server, with the following command :

    sudo apt-get install mysql-server

4) Create the Database :

    i) Verify that the MySQL service is running:

        systemctl status mysql.service

    ii) Log in with your MySQL credentials using the following command where -u is the flag for declaring your username and -p is the flag that tells MySQL that this user requires a password :  

        mysql -u db_user -p


    iii) CREATE DATABASE db_name;

    iv) Exit MySQL server, press CTRL + D.

5) Add the MySQL Database Connection to your Application:

    i) Navigate to the settings.py file and replace the current DATABASES lines with the following:

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

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

    ii) Next, lets edit the config file so that it has your MySQL credentials. Use vi as sudo to edit the file and add the following information:

        sudo vi /etc/mysql/my.cnf

        database = db_name
        user = db_user
        password = db_password
        default-character-set = utf8

6) Once the file has been edited, we need to restart MySQL for the changes to take effect :

    systemctl daemon-reload

    systemctl restart mysql

7) Test MySQL Connection to Application:

    python manage.py runserver your-server-ip:8000

Follow the given steps in order to setup it up to use MySQL database:

1) Install MySQL Database Connector :

    sudo apt-get install libmysqlclient-dev

2) Install the mysqlclient library :

    pip install mysqlclient

3) Install MySQL server, with the following command :

    sudo apt-get install mysql-server

4) Create the Database :

    i) Verify that the MySQL service is running:

        systemctl status mysql.service

    ii) Log in with your MySQL credentials using the following command where -u is the flag for declaring your username and -p is the flag that tells MySQL that this user requires a password :  

        mysql -u db_user -p


    iii) CREATE DATABASE db_name;

    iv) Exit MySQL server, press CTRL + D.

5) Add the MySQL Database Connection to your Application:

    i) Navigate to the settings.py file and replace the current DATABASES lines with the following:

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

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

    ii) Next, let’s edit the config file so that it has your MySQL credentials. Use vi as sudo to edit the file and add the following information:

        sudo vi /etc/mysql/my.cnf

        database = db_name
        user = db_user
        password = db_password
        default-character-set = utf8

6) Once the file has been edited, we need to restart MySQL for the changes to take effect :

    systemctl daemon-reload

    systemctl restart mysql

7) Test MySQL Connection to Application:

    python manage.py runserver your-server-ip:8000

回答 10

您必须首先创建一个MySQL数据库。然后转到settings.py文件并'DATABASES'使用您的MySQL凭据编辑字典:

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

这是用于将Django设置为在virtualenv上使用MySQL的完整安装指南:

http://codex.themedelta.com/how-to-install-django-with-mysql-in-a-virtualenv-on-linux/

You must create a MySQL database first. Then go to settings.py file and edit the 'DATABASES' dictionary with your MySQL credentials:

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

Here is a complete installation guide for setting up Django to use MySQL on a virtualenv:

http://codex.themedelta.com/how-to-install-django-with-mysql-in-a-virtualenv-on-linux/