Django: Python веб-фреймворк для разработки сайтов
Django (web framework)
Django – мощный Python веб-фреймворк для быстрой разработки сложных сайтов с базами данных. MTV архитектура, повторное использование кода, DSF поддержка.
Сравнивайте с английским: нажмите на абзац — оригинал откроется в окне. Кнопка EN под абзацем показывает его прямо в тексте.
Содержание
Введение
Python web framework Django (/dʒ//æ//ŋ//ɡ//oʊ/ JANGgoh; иногда стилизованный как django) – это бесплатный и открытый веб-фреймворк на языке Python, работающий на веб-сервере. Он следует архитектурному шаблону «модель-шаблон-представление» (MTV). Поддержка фреймворка осуществляется Django Software Foundation (DSF) – независимой организацией, зарегистрированной в США как некоммерческая организация 501(c)(3). Основная цель Django – упростить создание сложных веб-сайтов, работающих с базами данных. Фреймворк делает акцент на повторном использовании и возможности подключения компонентов, минимальном объеме кода, слабой связанности, быстрой разработке и принципе DRY ("Don't Repeat Yourself"). Python используется повсеместно, включая настройки, файлы и модели данных. Django также предоставляет опциональный административный интерфейс для создания, чтения, обновления и удаления данных, который генерируется динамически с помощью интроспекции и настраивается через административные модели. Среди известных сайтов, использующих Django, – Instagram, Mozilla, Disqus, Bitbucket, Nextdoor и Clubhouse.
Python web framework
Django ('/dʒ//æ//ŋ//ɡ//oʊ/ JANGgoh; sometimes stylized as django) is a free and open source, Python based web framework that runs on a web server. It follows the model–template–views (MTV) architectural pattern. It is maintained by the Django Software Foundation (DSF), an independent organization established in the US as a 501(c)(3) non profit. Django's primary goal is to ease the creation of complex, database driven websites. The framework emphasizes reusability and "pluggability" of components, less code, low coupling, rapid development, and the principle of don't repeat yourself. Python is used throughout, even for settings, files, and data models. Django also provides an optional administrative create, read, update and delete interface that is generated dynamically through introspection and configured via admin models. Some well known sites that use Django includes Instagram, Mozilla, Disqus, Bitbucket, Nextdoor and Clubhouse.
История
Django был создан осенью 2003 года, когда веб-программисты газеты Lawrence Journal World, Адриан Холовати и Саймон Уиллисон, начали использовать Python для разработки приложений. Джейкоб Каплан Мосс был нанят на ранней стадии разработки Django незадолго до завершения стажировки Саймона Уиллисона. Он был опубликован под лицензией BSD в июле 2005 года. Фреймворк получил название в честь гитариста Джанго Рейнхардта. Адриан Холовати – ромский джазовый гитарист, вдохновленный, в частности, музыкой Рейнхардта. В июне 2008 года было объявлено о создании Django Software Foundation (DSF), которая в дальнейшем будет поддерживать Django.
Django was created in the autumn of 2003, when the web programmers at the Lawrence Journal World newspaper, Adrian Holovaty and Simon Willison, began using Python to build applications. Jacob Kaplan Moss was hired early in Django's development shortly before Simon Willison's internship ended. It was released publicly under a BSD license in July 2005. The framework was named after guitarist Django Reinhardt. Adrian Holovaty is a Romani jazz guitar player inspired in part by Reinhardt's music. In June 2008, it was announced that a newly formed Django Software Foundation (DSF) would maintain Django in the future.
Расширяемость
Конфигурационная система Django позволяет подключать код сторонних разработчиков к обычному проекту, при условии соблюдения соглашений о повторно используемых приложениях. Доступно более 5000 пакетов для расширения базовой функциональности фреймворка, предлагающих решения задач, которые изначально не решались: регистрация пользователей, поиск, предоставление и использование API, системы управления контентом и т.д. Однако эта расширяемость ограничена зависимостями внутренних компонентов. Несмотря на то, что философия Django подразумевает слабую связанность, фильтры и теги шаблонов рассчитаны на использование одной системы шаблонов, а встроенные приложения для аутентификации и администрирования требуют использования внутреннего ORM. Ни один из этих фильтров или встроенных приложений не является обязательным для запуска проекта Django, но повторно используемые приложения часто зависят от них, что побуждает разработчиков продолжать использовать официальный стек для полноценного использования экосистемы приложений.
Django's configuration system allows third party code to be plugged into a regular project, provided that it follows the reusable app conventions. More than 5000 packages are available to extend the framework's original behavior, providing solutions to issues the original tool didn't tackle: registration, search, API provision and consumption, CMS, etc. This extensibility is, however, mitigated by internal components' dependencies. While the Django philosophy implies loose coupling, the template filters and tags assume one engine implementation, and both the auth and admin bundled applications require the use of the internal ORM. None of these filters or bundled apps are mandatory to run a Django project, but reusable apps tend to depend on them, encouraging developers to keep using the official stack in order to benefit fully from the apps ecosystem.
Устройство серверов
Django может работать в сочетании с Apache, Nginx с использованием WSGI, Gunicorn или Cherokee с помощью flup (модуля Python). Django также включает возможность запуска сервера FastCGI, что позволяет использовать его с любым веб-сервером, поддерживающим FastCGI, например, Lighttpd или Hiawatha. Также возможно использование других веб-серверов, соответствующих стандарту WSGI. Django официально поддерживает пять серверных частей для баз данных: PostgreSQL, MySQL, MariaDB, SQLite и Oracle. Microsoft SQL Server можно использовать с django mssql, а также существуют сторонние серверные части для IBM Db2, SQL Anywhere и Firebird. Существует форк под названием django nonrel, который поддерживает NoSQL базы данных, такие как MongoDB и Google App Engine's Datastore. Django также может работать с Python на любом Java EE сервере приложений, таком как GlassFish или JBoss. В этом случае необходимо установить django jython для обеспечения драйверами JDBC для подключения к базам данных, что также может предоставить возможность компиляции Django в WAR-файл, подходящий для развертывания.
Django can be run in conjunction with Apache, Nginx using WSGI, Gunicorn, or Cherokee using flup (a Python module). Django also includes the ability to launch a FastCGI server, enabling use behind any web server which supports FastCGI, such as Lighttpd or Hiawatha. It is also possible to use other WSGI compliant web servers. Django officially supports five database backends: PostgreSQL, MySQL, MariaDB, SQLite, and Oracle. Microsoft SQL Server can be used with django mssql while similarly external backends exist for IBM Db2, SQL Anywhere and Firebird. There is a fork named django nonrel, which supports NoSQL databases, such as MongoDB and Google App Engine's Datastore. Django may also be run in conjunction with Python on any Java EE application server such as GlassFish or JBoss. In this case django jython must be installed in order to provide JDBC drivers for database connectivity, which also can provide functionality to compile Django in to a war suitable for deployment.
История версий
Команда Django иногда определяет определенные релизы как релизы "длительной поддержки" (LTS). Для релизов LTS в течение гарантированного периода времени, обычно более 3 лет, применяются исправления безопасности и предотвращения потери данных, независимо от скорости последующих выпусков.
The Django team will occasionally designate certain releases to be "long term support" (LTS) releases. LTS releases will get security and data loss fixes applied for a guaranteed period of time, typically 3+ years, regardless of the pace of releases afterwards. Version Release DateEnd of mainstream supportEnd of extended support Notes scope="row" format=dmy scope="row" format=dmy "new admin" scope="row" format=dmy "magic removal" scope="row" format=dmy "newforms", testing tools scope="row" format=dmy API stability, decoupled admin, unicode scope="row" format=dmy Aggregates, transaction based tests scope="row" format=dmy Multiple db connections, CSRF, model validation scope="row" format=dmy format=dmy format=dmy Class based views, staticfiles scope="row" format=dmy format=dmy format=dmy Time zones, in browser testing, app templates. scope="row" format=dmy format=dmyformat=dmy Python 3 Support, configurable user model scope="row" format=dmy format=dmy format=dmy Dedicated to Malcolm Tredinnick, db transaction management, connection pooling. scope="row" format=dmy format=dmyformat=dmy Migrations, application loading and configuration. scope="row" format=dmy format=dmyformat=dmy Native support for multiple template engines. Support ended on 1 April 2018 scope="row" format=dmy format=dmyformat=dmy Automatic password validation. New styling for admin interface. scope="row" format=dmy format=dmyformat=dmy Full text search for PostgreSQL. New style middleware. scope="row" format=dmy format=dmyformat=dmy Last version to support Python 2.7. Support ended on 1 April 2020 scope="row" format=dmy format=dmyformat=dmy First Python 3 only release, Simplified URL routing syntax, Mobile friendly admin. scope="row" format=dmy format=dmyformat=dmy Model "view" permission. scope="row" format=dmy format=dmyformat=dmy Security release. scope="row" format=dmy format=dmyformat=dmy ASGI support scope="row" format=dmy format=dmyformat=dmy Asynchronous views and middleware scope="row" format=dmy format=dmyApril 2024 Tracking many to many relationships, added support for Python 3.11 scope="row" format=dmy format=dmyApril 2023 Support for pytz is now deprecated and will be removed in Django 5.0. scope="row" format=dmy April 2023December 2023 Asynchronous ORM interface, CSRF COOKIE MASKED setting, outputting a form, like form scope="row" format=dmyDecember 2023April 2026 Psycopg 3 support, ENGINE as django. db. backends. postgresql supports both libraries. scope="row" format=dmy August 2024April 2025
Версия | Дата выпуска | Конец основной поддержки | Конец расширенной поддержки | Замечания
------- | -------- | -------- | -------- | --------
scope="row" format=dmy | | | | "новый админ"
scope="row" format=dmy | | | | "удаление магии"
scope="row" format=dmy | | | | "newforms", инструменты тестирования
scope="row" format=dmy | | | | стабильность API, отсоединенный админ, Unicode
scope="row" format=dmy | | | | агрегаты, транзакционные тесты
scope="row" format=dmy | | | | множественные подключения к БД, CSRF, валидация моделей
scope="row" format=dmy | | | | классовые представления, статические файлы
scope="row" format=dmy | | | | часовые пояса, тестирование в браузере, шаблоны приложений
scope="row" format=dmy | | | | поддержка Python 3, настраиваемая модель пользователя
scope="row" format=dmy | | | | посвящено Малкольму Трединнику, управление транзакциями БД, объединение соединений
scope="row" format=dmy | | | | миграции, загрузка и конфигурация приложений
scope="row" format=dmy | | | | нативная поддержка нескольких движков шаблонов. Поддержка завершена 1 апреля 2018 г.
scope="row" format=dmy | | | | автоматическая проверка пароля. Новый стиль интерфейса администратора.
scope="row" format=dmy | | | | полнотекстовый поиск для PostgreSQL. Новая стилизация middleware.
scope="row" format=dmy | | | | последняя версия, поддерживающая Python 2.7. Поддержка завершена 1 апреля 2020 г.
scope="row" format=dmy | | | | первый релиз, работающий только с Python 3, упрощенный синтаксис маршрутизации URL, удобный для мобильных устройств админ.
scope="row" format=dmy | | | | разрешение "просмотра" модели.
scope="row" format=dmy | | | | выпуск безопасности.
scope="row" format=dmy | | | | поддержка ASGI
scope="row" format=dmy | | | | асинхронные представления и middleware
scope="row" format=dmy | апрель 2024 | | | отслеживание связей "многие ко многим", добавлена поддержка Python 3.11
scope="row" format=dmy | апрель 2023 | | | поддержка pytz устарела и будет удалена в Django 5.0.
scope="row" format=dmy | апрель 2023 | декабрь 2023 | | асинхронный интерфейс ORM, настройка CSRF COOKIE MASKED, вывод формы, например `<form>`
scope="row" format=dmy | декабрь 2023 | апрель 2026 | | поддержка Psycopg 3, ENGINE как `django.db.backends.postgresql` поддерживает обе библиотеки.
scope="row" format=dmy | август 2024 | апрель 2025 | |
The Django team will occasionally designate certain releases to be "long term support" (LTS) releases. LTS releases will get security and data loss fixes applied for a guaranteed period of time, typically 3+ years, regardless of the pace of releases afterwards. Version Release DateEnd of mainstream supportEnd of extended support Notes scope="row" format=dmy scope="row" format=dmy "new admin" scope="row" format=dmy "magic removal" scope="row" format=dmy "newforms", testing tools scope="row" format=dmy API stability, decoupled admin, unicode scope="row" format=dmy Aggregates, transaction based tests scope="row" format=dmy Multiple db connections, CSRF, model validation scope="row" format=dmy format=dmy format=dmy Class based views, staticfiles scope="row" format=dmy format=dmy format=dmy Time zones, in browser testing, app templates. scope="row" format=dmy format=dmyformat=dmy Python 3 Support, configurable user model scope="row" format=dmy format=dmy format=dmy Dedicated to Malcolm Tredinnick, db transaction management, connection pooling. scope="row" format=dmy format=dmyformat=dmy Migrations, application loading and configuration. scope="row" format=dmy format=dmyformat=dmy Native support for multiple template engines. Support ended on 1 April 2018 scope="row" format=dmy format=dmyformat=dmy Automatic password validation. New styling for admin interface. scope="row" format=dmy format=dmyformat=dmy Full text search for PostgreSQL. New style middleware. scope="row" format=dmy format=dmyformat=dmy Last version to support Python 2.7. Support ended on 1 April 2020 scope="row" format=dmy format=dmyformat=dmy First Python 3 only release, Simplified URL routing syntax, Mobile friendly admin. scope="row" format=dmy format=dmyformat=dmy Model "view" permission. scope="row" format=dmy format=dmyformat=dmy Security release. scope="row" format=dmy format=dmyformat=dmy ASGI support scope="row" format=dmy format=dmyformat=dmy Asynchronous views and middleware scope="row" format=dmy format=dmyApril 2024 Tracking many to many relationships, added support for Python 3.11 scope="row" format=dmy format=dmyApril 2023 Support for pytz is now deprecated and will be removed in Django 5.0. scope="row" format=dmy April 2023December 2023 Asynchronous ORM interface, CSRF COOKIE MASKED setting, outputting a form, like form scope="row" format=dmyDecember 2023April 2026 Psycopg 3 support, ENGINE as django. db. backends. postgresql supports both libraries. scope="row" format=dmy August 2024April 2025