- Documentation
- Quick install guide¶
- Install Python¶
- Set up a database¶
- Install Django¶
- Verifying¶
- Documentation
- How to install Django¶
- Install Python¶
- Install Apache and mod_wsgi ¶
- Get your database running¶
- Install the Django code¶
- Installing an official release with pip ¶
- Installing a distribution-specific package¶
- Installing the development version¶
- Развертывание Django проекта на сервере NGINX в Linux Ubuntu
- Python, Django и UWSGI
- Настройка Nginx
- Подключение к базе данных
- MariaDB
- Подготовка базы данных
- Установка модуля для Python
- Настройка подключения
- Делаем выборку
Documentation
Quick install guide¶
Before you can use Django, you’ll need to get it installed. We have a complete installation guide that covers all the possibilities; this guide will guide you to a minimal installation that’ll work while you walk through the introduction.
Install Python¶
Being a Python Web framework, Django requires Python. See What Python version can I use with Django? for details. Python includes a lightweight database called SQLite so you won’t need to set up a database just yet.
Get the latest version of Python at https://www.python.org/downloads/ or with your operating system’s package manager.
You can verify that Python is installed by typing python from your shell; you should see something like:
Set up a database¶
This step is only necessary if you’d like to work with a “large” database engine like PostgreSQL, MariaDB, MySQL, or Oracle. To install such a database, consult the database installation information .
Install Django¶
You’ve got three options to install Django:
- Install an official release . This is the best approach for most users.
- Install a version of Django provided by your operating system distribution .
- Install the latest development version . This option is for enthusiasts who want the latest-and-greatest features and aren’t afraid of running brand new code. You might encounter new bugs in the development version, but reporting them helps the development of Django. Also, releases of third-party packages are less likely to be compatible with the development version than with the latest stable release.
Always refer to the documentation that corresponds to the version of Django you’re using!
If you do either of the first two steps, keep an eye out for parts of the documentation marked new in development version. That phrase flags features that are only available in development versions of Django, and they likely won’t work with an official release.
Verifying¶
To verify that Django can be seen by Python, type python from your shell. Then at the Python prompt, try to import Django:
You may have another version of Django installed.
Источник
Documentation
How to install Django¶
This document will get you up and running with Django.
Install Python¶
Django is a Python Web framework. See What Python version can I use with Django? for details.
Get the latest version of Python at https://www.python.org/downloads/ or with your operating system’s package manager.
Python on Windows
If you are just starting with Django and using Windows, you may find How to install Django on Windows useful.
Install Apache and mod_wsgi ¶
If you just want to experiment with Django, skip ahead to the next section; Django includes a lightweight web server you can use for testing, so you won’t need to set up Apache until you’re ready to deploy Django in production.
If you want to use Django on a production site, use Apache with mod_wsgi. mod_wsgi operates in one of two modes: embedded mode or daemon mode. In embedded mode, mod_wsgi is similar to mod_perl – it embeds Python within Apache and loads Python code into memory when the server starts. Code stays in memory throughout the life of an Apache process, which leads to significant performance gains over other server arrangements. In daemon mode, mod_wsgi spawns an independent daemon process that handles requests. The daemon process can run as a different user than the Web server, possibly leading to improved security. The daemon process can be restarted without restarting the entire Apache Web server, possibly making refreshing your codebase more seamless. Consult the mod_wsgi documentation to determine which mode is right for your setup. Make sure you have Apache installed with the mod_wsgi module activated. Django will work with any version of Apache that supports mod_wsgi.
See How to use Django with mod_wsgi for information on how to configure mod_wsgi once you have it installed.
If you can’t use mod_wsgi for some reason, fear not: Django supports many other deployment options. One is uWSGI ; it works very well with nginx. Additionally, Django follows the WSGI spec ( PEP 3333), which allows it to run on a variety of server platforms.
Get your database running¶
If you plan to use Django’s database API functionality, you’ll need to make sure a database server is running. Django supports many different database servers and is officially supported with PostgreSQL, MariaDB, MySQL, Oracle and SQLite.
If you are developing a small project or something you don’t plan to deploy in a production environment, SQLite is generally the best option as it doesn’t require running a separate server. However, SQLite has many differences from other databases, so if you are working on something substantial, it’s recommended to develop with the same database that you plan on using in production.
In addition to the officially supported databases, there are backends provided by 3rd parties that allow you to use other databases with Django.
In addition to a database backend, you’ll need to make sure your Python database bindings are installed.
- If you’re using PostgreSQL, you’ll need the psycopg2 package. Refer to the PostgreSQL notes for further details.
- If you’re using MySQL or MariaDB, you’ll need a DB API driver like mysqlclient . See notes for the MySQL backend for details.
- If you’re using SQLite you might want to read the SQLite backend notes .
- If you’re using Oracle, you’ll need a copy of cx_Oracle, but please read the notes for the Oracle backend for details regarding supported versions of both Oracle and cx_Oracle .
- If you’re using an unofficial 3rd party backend, please consult the documentation provided for any additional requirements.
If you plan to use Django’s manage.py migrate command to automatically create database tables for your models (after first installing Django and creating a project), you’ll need to ensure that Django has permission to create and alter tables in the database you’re using; if you plan to manually create the tables, you can grant Django SELECT , INSERT , UPDATE and DELETE permissions. After creating a database user with these permissions, you’ll specify the details in your project’s settings file, see DATABASES for details.
If you’re using Django’s testing framework to test database queries, Django will need permission to create a test database.
Install the Django code¶
Installation instructions are slightly different depending on whether you’re installing a distribution-specific package, downloading the latest official release, or fetching the latest development version.
Installing an official release with pip ¶
This is the recommended way to install Django.
Install pip. The easiest is to use the standalone pip installer. If your distribution already has pip installed, you might need to update it if it’s outdated. If it’s outdated, you’ll know because installation won’t work.
Take a look at venv . This tool provides isolated Python environments, which are more practical than installing packages systemwide. It also allows installing packages without administrator privileges. The contributing tutorial walks through how to create a virtual environment.
After you’ve created and activated a virtual environment, enter the command:
Installing a distribution-specific package¶
Check the distribution specific notes to see if your platform/distribution provides official Django packages/installers. Distribution-provided packages will typically allow for automatic installation of dependencies and supported upgrade paths; however, these packages will rarely contain the latest release of Django.
Installing the development version¶
Tracking Django development
If you decide to use the latest development version of Django, you’ll want to pay close attention to the development timeline, and you’ll want to keep an eye on the release notes for the upcoming release . This will help you stay on top of any new features you might want to use, as well as any changes you’ll need to make to your code when updating your copy of Django. (For stable releases, any necessary changes are documented in the release notes.)
If you’d like to be able to update your Django code occasionally with the latest bug fixes and improvements, follow these instructions:
Make sure that you have Git installed and that you can run its commands from a shell. (Enter git help at a shell prompt to test this.)
Check out Django’s main development branch like so:
This will create a directory django in your current directory.
Make sure that the Python interpreter can load Django’s code. The most convenient way to do this is to use a virtual environment and pip. The contributing tutorial walks through how to create a virtual environment.
After setting up and activating the virtual environment, run the following command:
This will make Django’s code importable, and will also make the django-admin utility command available. In other words, you’re all set!
When you want to update your copy of the Django source code, run the command git pull from within the django directory. When you do this, Git will download any changes.
Источник
Развертывание Django проекта на сервере NGINX в Linux Ubuntu
Наше развертывание мы разделим на два этапа:
- Установка и настройка среды Python и UWSGI.
- Настройка веб-сервера NGINX.
Рассмотрим эти процессы по шагам.
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:
service uwsgi restart
Настройка 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/;
>
>
systemctl restart nginx
Подключение к базе данных
Рассмотрим пример настройки подключения к СУБД MariaDB/MySQL. Нам необходимо будет настроить как сам сервер баз данных, так и фреймворк. В инструкции опишем полный процесс, начиная от установки СУБД.
MariaDB
Выполним установку и настройку сервера баз данных. Начнем с установки:
apt-get install mariadb-server
Разрешаем автозапуск СУБД:
systemctl enable mariadb
Зададим пароль для учетной записи 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
pip3 install mysqlclient
Первая команда установит библиотеки, необходимые для установки 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. Пример кода будет таким:
- from django.db import connection
- cursor = connection.cursor()
- cursor.execute(«SELECT * FROM users»)
- print(cursor.fetchall())
В данном примере мы извлечем все содержимое таблицы users и выведем это на экран.
Источник