Python django mysql linux

Setting Django up to use MySQL

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?

Note: as od 01/2016 there is no MySQL driver for python 3.5.x. See stackoverflow.com/questions/34456770/… So use only up to Python 3.4. You can still use Django 1.9 (latest stable release as of 01/2016).

There is a workaround using PyMySQL as outlined here. You basically install and import pymysql and add pymysql.version_info = (1, 4, 2, «final», 0) and pymysql.install_as_MySQLdb() right after you specify the DATABASES dictionary in settings.py . @TomasTintera

13 Answers 13

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

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:

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

Читайте также:  Форматировать linux флешка ubuntu

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.

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

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 

If you are using python3.x then Run below command

Then change setting.py like

I am using virtualenv with python 3.6. This saves my life. Thank you. Also, remember to create DB in mysql first

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:

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.

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

Enjoy mysql connection

sudo pip3 install mysqlclient

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

 1. sudo apt install libmysqlclient-dev python-mysqldb 2. sudo pip3 install mysqlclient 

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/

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

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 

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

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 

Источник

Развертывание Django проекта на сервере NGINX в Linux Ubuntu

Обновлено

Обновлено: 30.05.2021 Опубликовано: 26.05.2021

Рассмотрим эти процессы по шагам.

Python, Django и UWSGI

Устанавливаем необходимые пакеты:

apt-get install nginx uwsgi python3 uwsgi-plugin-python3 python3-pip python3-dev build-essential libssl-dev libffi-dev python3-setuptools

Устанавливаем пакеты для Python:

pip3 install virtualenv uwsgi django

Создаем директорию для хранения стачичных файлов (css, js, img):

mkdir -p /var/www/my_app/static /var/www/my_app/media

chown www-data.www-data /var/www/my_app/media

chown www-data.www-data /var/www/my_app/static

Копируем наше приложение в папку /var/www/my_app, структура должна получиться примерно такой:

Вносим изменения в конфигурационный файл нашего проекта:

from .base import *
.
ALLOWED_HOSTS = [ ‘www.example.com’ ]
.
DATABASES = < 'default': < . >>
.
STATIC_ROOT = ‘/var/www/my_app/static’
MEDIA_ROOT = ‘/var/www/my_app/media’

  • ALLOWED_HOSTS — разрешенные доменные имена, на которых должен открываться наш сайт.
  • DATABASES — данные для подключения к базе данных. Подробнее, данная настройка описана ниже.

Запускаем команду для сбора всех статических файлов в нашем проекте (из корня проекта):

[uwsgi]
chdir = var/www/my_app
env = DJANGO_SETTINGS_MODULE=project.settings.production
wsgi-file = my_app/wsgi.py
workers = 1max-requests=5000
plugins=python3
processes = 5
threads = 2
master = true
die-on-term = true
socket = sedova.sock
chmod-socket = 660
vacuum = true
uid = www-data
gui = www-data

  • chdir — указываем директорию нашего проекта.
  • env — конфигурационный файл нашего приложения.
  • wsgi-file — относительный путь до файла wsgi.py нашего приложения.

Перезапускаем сервис uwsgi:

Настройка Nginx

Создаем файл конфигурации для нашего приложения

Содержимое файла должно быть примерно следующим:

server listen 80;
server_tokens off;
server_name my_app my_app.domain.local;

location / include uwsgi_params;
uwsgi_pass unix:///run/uwsgi/app/sedova/socket;
>

location /static/ alias /var/www/my_app/static/;
>

location /media/ alias /var/www/my_app/media/;
>
>

Подключение к базе данных

Рассмотрим пример настройки подключения к СУБД MariaDB/MySQL. Нам необходимо будет настроить как сам сервер баз данных, так и фреймворк. В инструкции опишем полный процесс, начиная от установки СУБД.

MariaDB

Выполним установку и настройку сервера баз данных. Начнем с установки:

apt-get install mariadb-server

Разрешаем автозапуск СУБД:

Зададим пароль для учетной записи mysql-root:

mysqladmin -u root password

Установка и запуск завершены. Перейдем к настройке.

Для Django важно, чтобы кодировка была UTF-8. Откроем конфигурационный файл клиента:

[mysql]
.
default-character-set = utf8

Аналогичную настройку выполняем в следующем файле:

[mysql]
.
default-character-set = utf8

Редактируем файл для настройки сервера:

Задаем значения для опций:

character-set-server = utf8
collation_server = utf8_unicode_ci

Для применения настроек перезапускаем сервис:

systemctl restart mariadb

Подготовка базы данных

Предполагается, что у нас есть база данных, которую мы либо создадим на сервере, либо восстановим из резервной копии.

Не забываем также настроить права доступа на базу.

Установка модуля для Python

Для возможности подключения к базе, мы должны установить клиента mysql на сервер. Для этого выполняем две команды:

apt-get install libmysqlclient-dev

Первая команда установит библиотеки, необходимые для установки mysqlclient через менеджер пакетов Python. Вторая, собственно, и установит клиента.

Настройка подключения

Откроем конфигурационный файл нашего приложения:

DATABASES = ‘default’: ‘ENGINE’: ‘django.db.backends.sqlite3’,
‘NAME’: BASE_DIR / ‘db.sqlite3’,
>
>

Данная настройка прописывается, как правило, по умолчанию и позволяет использовать базу sqlite3. Поменяем ее:

DATABASES = ‘default’: ‘ENGINE’: ‘django.db.backends.mysql’,
‘NAME’: ‘database_name’,
‘HOST’: ‘localhost’,
‘USER’: ‘db_user’,
‘PASSWORD’: ‘db_password’,
>
>

  • NAME — имя базы данных, к которой мы подключимся.
  • HOST — сервер баз данных.
  • USER — пользователь с привилегиями работы с базой данных.
  • PASSWORD — пароль для пользователя.

Делаем выборку

Для проверки настройки создадим select-запрос с нашей базе. Предположим, к таблице users. Пример кода будет таким:

  1. from django.db import connection
  2. cursor = connection.cursor()
  3. cursor.execute(«SELECT * FROM users»)
  4. print(cursor.fetchall())

В данном примере мы извлечем все содержимое таблицы users и выведем это на экран.

Источник

Оцените статью
Adblock
detector