IT-новости про Python, которые стоит знать

Собрали в одном месте самые важные ссылки
читайте нас в Telegram

     18.10.2024       Выпуск 566 (14.10.2024 - 20.10.2024)       Статьи

Building an automatically updating live blog in Django

Django co-creator Simon Willison wrote a live blogging app for OpenAI's DevDay event.

     18.10.2024       Выпуск 566 (14.10.2024 - 20.10.2024)       Статьи

Proposal for a Django project template

A take on what could be a project template for Django advanced usage, with modern tooling (for Python and UI dependencies, as well as configuration/environment management), but not too opinionated.

     14.10.2024       Выпуск 566 (14.10.2024 - 20.10.2024)       Статьи
     27.09.2024       Выпуск 563 (23.09.2024 - 29.09.2024)       Статьи
     19.09.2024       Выпуск 562 (16.09.2024 - 22.09.2024)       Статьи
     09.09.2024       Выпуск 561 (09.09.2024 - 15.09.2024)       Статьи

Django: hoist repeated decorator definitions

Django provides us with a rich set of view decorators. In this post, we’ll look at a technique for hoisting repeated use of these decorators to reduce repetition. Repeated @cache_control calls Here are two public views with the same @cache_control decorator: from django.views.decorators.cache import cache_control @cache_control(max_age=60 * 60, public=True) def about(request): ... @cache_control(max_age=60 * 60, public=True) def contact_us(request): ... To avoid this repetition, we can call cache_control once at the top of the module and use that result as the decorator: from django.views.decorators.cache import cache_control cache_public = cache_control(max_age=60 * 60, public=True) @cache_public def about(request): ... @cache_public def team(request): ... This works because cache_control is technically not a decorator but a function that returns a decorator. So we can separate the call of cache_control from the decorating. Aside from reducing redundant repetition, this technique also saves a tiny bit of time and memory when importing the module, because cache_control is only called once. Repeated @require_http_methods calls Here’s another example, instead using @require_http_methods: from django.views.decorators.http import require_http_methods require_GET_POST = require_http_methods(("GET", "POST")) @require_GET_POST def contact_us(request): ... @require_GET_POST def store_feedback(request): ... (Actually, it would be neat if Django provided require_GET_POST out of the box…) Hoisting @method_decorator calls for class-based views This technique is particularly beneficial for class-based views, where view decorators mostly need extra wrapping with method_decorator: from django.utils.decorators import method_decorator from django.views.decorators.cache import cache_control from django.views.generic import TemplateView cache_public = method_decorator(cache_control(max_age=60 * 60, public=True)) @cache_public class AboutView(TemplateView): ... @cache_public class TeamView(TemplateView): ... I also like to use this technique with decorators that don’t take arguments, such as the new @login_not_required from Django 5.1: from django.contrib.auth.decorators import login_not_required from django.utils.decorators import method_decorator from django.views.generic import TemplateView login_not_required_m = method_decorator(login_not_required, name="dispatch") @login_not_required_m class AboutView(TemplateView): ... @login_not_required_m class TeamView(TemplateView): ... I like adding an “m” suffix to the variable name to indicate that it’s a method decorator version of the original. Test decorators This deduplication technique can also dramatically improve test readability, where many tests often need the same decorator applied. For example, third-party apps may mark version-restricted tests with unittest’s @skipIf or pytest’s @pytest.mark.skipif: from unittest import skipIf import django django_5_1_plus = skipIf(django.VERSION < (5, 1), "Django 5.1+ required") class AcmeAuthMiddlewareTests(TestCase): ... @django_5_1_plus def test_view_login_not_required(self): ... @django_5_1_plus def test_view_login_required(self): ... Fin May your decorators be DRYer than the Kalahari, —Adam

     06.09.2024       Выпуск 560 (02.09.2024 - 08.09.2024)       Статьи
     05.09.2024       Выпуск 560 (02.09.2024 - 08.09.2024)       Статьи
     03.09.2024       Выпуск 560 (02.09.2024 - 08.09.2024)       Статьи

Автотесты на Django: менеджмент данных тестирования на монолите

Тестировать монолитное приложение может быть непросто — особенно, когда сервис активно развивается. На проверку каждой фичи уходит всё больше ресурсов, а времени на оптимизацию мало. Как поступить?

     01.09.2024       Выпуск 559 (26.08.2024 - 01.09.2024)       Статьи
     31.08.2024       Выпуск 559 (26.08.2024 - 01.09.2024)       Статьи
     14.08.2024       Выпуск 557 (12.08.2024 - 18.08.2024)       Статьи
     06.08.2024       Выпуск 556 (05.08.2024 - 11.08.2024)       Статьи

Система оценивания для проведения экзаменов, срезов в СПО

Сегодня я расскажу вам о моей системе оценивания, которая создана для проведения экзаменов и оценки знаний студентов. Система построена на Django Rest Framework (DRF) для бэкенда и React с MaterialUI для фронтенда. Я добавил множество полезных функций, включая интеграцию с ISPmanager, которые делают систему удобной и эффективной.

     26.07.2024       Выпуск 554 (22.07.2024 - 28.07.2024)       Статьи

Implementing Single Sign-On (SSO) with SAML for a Django Application

A straightforward tutorial on adding SSO via SAML to a Django application, which can otherwise be a complex process.

     26.07.2024       Выпуск 554 (22.07.2024 - 28.07.2024)       Статьи
     23.07.2024       Выпуск 554 (22.07.2024 - 28.07.2024)       Статьи

Самый быстрый фреймворк на Диком Западе: ускоряем Django-rest-framework вместе с Rust

На этапе запуска TestY в качестве фреймворка для разработки мы выбрали Django, так как он позволяет в максимально короткие сроки реализовать MVP. Однако развивать такой продукт — добавлять фичи, наращивать число пользователей и объем хранимых данных в системе — бывает сложно.

     20.07.2024       Выпуск 553 (15.07.2024 - 21.07.2024)       Статьи

Введение в оптимизация запросов к БД на django c помощью silk

Стоит ли использовать django в 2024? Я думаю - да. DRF очень удобен, скорость разработки очень высока(особенно, если использовать generic views, django-filters), огромное количество готовых батареек сильно облегчает жизнь и встроенная админка хорошо подходит для большинства сайтов.

     14.07.2024       Выпуск 553 (15.07.2024 - 21.07.2024)       Статьи

pytest-unordered: сравнение коллекций без учёта порядка

Во время работы над проектом на Django Rest Framework (DRF) я столкнулся с необходимостью писать тесты для API, которые возвращали неотсортированные данные. Сортировка данных в API не требовалась, и делать её только ради тестов казалось нелогичным. Использовать для решения этой задачи множества оказалось невозможным, так как элементы множества должны быть хэшируемыми, коими словари не являются.

     03.07.2024       Выпуск 551 (01.07.2024 - 07.07.2024)       Статьи

Как настроить уведомления в Django с помощью сигналов: пошаговое руководство

В Django сигналы используются для отправки и получения важной информации при сохранении, изменении или даже удалении модели данных и это относится к определенным прошлым или настоящим событиям в реальном времени. Сигналы помогают нам связывать события с действиями.

     02.07.2024       Выпуск 551 (01.07.2024 - 07.07.2024)       Статьи

Безопасность в Django: защита от распространенных угроз веб-приложений

Безопасность — ключевой аспект разработки веб-приложений. Но это понятие очень широкое, поэтому для его понимания нужно четко определить роль безопасности в современных веб-приложениях и то, какие аспекты она охватывает.