Python 设置 Django 以使用 MySQL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19189813/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:05:43  来源:igfitidea点击:

Setting Django up to use MySQL

pythonmysqldjangodebian

提问by gregor

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.

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

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.

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

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

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

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.

这是我的第一个大困惑。在教程中,我跟着那家伙安装了 Django,开始了他的第一个项目,重新启动了 Apache,然后 Django 就开始工作了。他转到他的浏览器并转到 Django 默认页面,没有任何问题。

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

然而,我必须进入我的 firstweb 文件夹并运行

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 questionis 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.

我的第二个问题是我想设置它以便它使用我的 MySQL 数据库。我进入 /firstweb/firstweb 下的 settings.py,我看到了 ENGINE 和 NAME,但我不知道该放什么。

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

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

采纳答案by Andy

MySQL supportis simple to add. In your DATABASESdictionary, you will have an entry like this:

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

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

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

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

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

您还需要/path/to/my.cnf从上面创建具有类似设置的文件

[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:

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

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.

换句话说,如果您在 OPTIONS 中设置数据库的名称,这将优先于 NAME,后者将覆盖 MySQL 选项文件中的任何内容。



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

如果您只是在本地机器上测试您的应用程序,您可以使用

python manage.py runserver

Adding the ip:portargument 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 Djangoon the djangobook

添加ip:port参数允许您自己以外的机器访问您的开发应用程序。一旦你准备好部署应用程序,我建议采取一看一章部署的Djangodjangobook

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

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

CREATE DATABASE mydatabase CHARACTER SET utf8 COLLATE utf8_bin

If you are using Oracle's MySQL connectoryour ENGINEline should look like this:

如果您使用Oracle 的 MySQL 连接器,您的ENGINE行应如下所示:

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


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

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

brew install mysql (MacOS)

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

此外,python 3 的 mysql 客户端包已更改(MySQL-Client仅适用于 python 2)

pip3 install mysqlclient

回答by Ritesh

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

首先请运行以下命令来安装 python 依赖项,否则 python runserver 命令会抛出错误。

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 :

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

python manage.py runserver

Have fun..!!

玩得开心..!!

回答by root

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

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

  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:80and 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.pyfile 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

  1. http://www.unixmen.com/install-xampp-stack-ubuntu-14-04/安装并运行 xampp ,然后从 GUI 启动 Apache Web 服务器和 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,这是更可取的):

    须藤 apt-get 安装 libmysqlclient-dev

    pip 安装 MySQL-python

  7. 就是这样!!您已经以非常简单的方式使用 MySQL 配置了 Django。

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

    python manage.py 迁移

    python manage.py runserver

回答by mimoralea

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:

其实,不同的环境,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

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

您应该很乐意接受已接受的答案。如果这对您很重要,可以删除不必要的包。

回答by Jiawei Dai

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/

安迪的回答有帮助,但如果您担心在 django 设置中暴露您的数据库密码,我建议在 mysql 连接上遵循 django 官方配置: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:

要在设置中替换 '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

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

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

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

回答by Sibi M

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

您必须先创建一个 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',
 }
}

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

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

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

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

回答by Deepak Kumar

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

然后配置 settings.py 之类的

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

Enjoy mysql connection

享受mysql连接

回答by Manoj Jadhav

If you are using python3.x then Run below command

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

pip install mysqlclient

Then change setting.py like

然后更改 setting.py 之类的

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

回答by LuciferHyman

settings.py

设置.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.

你将可以使用 mysql。

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

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

回答by Shubham Gupta

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

按照给定的步骤将其设置为使用 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, 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