Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для URL, имени файла, имени объекта в каком-то софте и тд. Требования совместимости простые: в тексте должны быть только допустимые символы. Обычно это a-z, 0-9 и "_" или "-". То есть, только прописные буквы латинского алфавита и цифры (как пример).
Допустим, нам нужно название статьи в блоге преобразовать в slug для добавления его в URL этой статьи. Как это лучше всего сделать?
В Django по умолчанию есть готовая функция slugify для таких случаев.
Но я её никогда не использую. Почему? Потому что её недостаточно!
Приведём пример
>>> from django.utils.text import slugify
>>> slugify('This is a Title')
'this-is-a-title'
Пока всё отлично
>>> slugify('This is a "Title!"')
'this-is-a-title'
Спец символы удалились, всё хорошо.
>>> slugify('Это заголовок статьи')
''
Вот и приехали 😢. Если текст не английский то буквы просто игнорируются. Можно это поправить
>>> slugify('Это заголовок статьи', allow_unicode=True)
'это-заголовок-статьи'
Но тогда мы не вписываемся в условие. У нас появилась кириллица в тексте.
Так как я часто пишу сайты для русскоязычных пользователей эта проблема весьма актуальна. Я не использую стандартную функцию и всегда пишу свою.
Оригинал я не беру в расчёт и пишу полностью свою функцию. И так, по порядку:
🔸1. Исходный текст:
>>> text = 'Мой заголовок №10 😁!'
Взял специально посложней со специальными символами.
🔸2. Транслит
Необходимо сделать транслит всех символов в латиницу. Здесь очень выручает библиотека unidecode. Помимо простого транслита кириллицы в латиницу она умеет преобразовывать спец символы и иероглифы в текстовые аналоги.
from unidecode import unidecode
>>> unidecode("Ñ Σ ® µ ¶ ¼ 月 山")
'N S (r) u P 1/4 Yue Shan'
Очень крутая библиотека, советую👍
В нашем случае получаем такое преобразование:
>>> text = unidecode(text)
>>> print(text)
'Moi zagolovok No. 10 !'
Отличный транслит. Смайл просто удалился, хотя я ждал что-то вроде :). Ну и ладно, всë равно невалидные символы.
А еще наш код уже поддерживает любой язык, будь то хинди или корейский.
🔸4. Фильтр символов
Unidecode не занимается фильтрацией по недопустимым символам. Это мы делаем в следующем шаге через regex. Просто заменим все символы на "_" если они вне указанного диапазона.
>>> text = re.sub(r'[^a-zA-Z0-9]+', '_', text)
>>> print(text)
'Moi_zagolovok_No_10_'
Символ "+" в паттерне выручает когда несколько недопустимых символов идут рядом. Все они заменяются на один символ "_".
🔸5. Slugify
Осталось удалить лишние символы по краям и сделать нижний регистр
>>> text = text.strip('_').lower()
>>> print(text)
'moi_zagolovok_no_10'
Получаем отличный slug! 😎
🌎 Полный код в виде функции.
______________
PS. Проверку что в строке остался хоть один допустимый символ я бы вынес в отдельную функцию.
#libs#tricks#django
News update: #Tigray Democratic Solidarity rejects HoF decision, threatens to boycott elections and similar ‘illegal acts’ if unresolved
Tigray Democratic Solidarity (#Simret) has called on the House of #Federation (HoF) to reconsider its decision to remove electoral constituencies in districts previously under the Tigray region administration, describing the move as “unconstitutional” and warning that it undermines Ethiopia’s federal system.
In a letter addressed to both the House of Federation and the National Election Board of Ethiopia (#NEBE), Simret said the decision constitutes an act that “undermines the country’s constitutional order, crushes institutional independence, and effectively declares ‘constitutional anarchy’.”
Citing Article 62 of the FDRE Constitution, the party argued that the House of Federation’s powers are limited to constitutional interpretation & the resolution of regional boundary disputes.
Simret further argued that boundary...
Read more: https://addisstandard.com/?p=55350
News: Armed #Tigrai Peace Force converge with Interim Admin in rejecting House of #Federation decision
An unusual alignment is emerging among rival Tigrayan actors after the National Electoral Board of Ethiopia (#NEBE) issued a decision, in line with a ruling by the House of Federation, concerning five electoral districts previously under the Tigray regional state ahead of the 7th General Elections.
The Tigrai Peace Force, an armed group that has positioned itself in opposition to both the Tigray People’s Liberation Front (#TPLF) and the current Tigray Interim Administration, released a statement through its Military Council strongly rejecting the electoral board’s decision. On the same day, the Tigray Communication Affairs Bureau, representing the Interim Administration, issued a separate statement condemning the move as unconstitutional.
Despite deep political and military divisions between them, these & other political actors adopted strikingly similar...
Read more: https://addisstandard.com/?p=55371
News: Demonstration held in #Kobo town, #Amhara region, supporting House of Federation decision; IDPs allege pressure to participate
A public demonstration was held on Saturday in Kobo town, #North_Wollo Zone of the Amhara Region, in support of a decision by the House of #Federation and the National Election Board of #Ethiopia allowing elections to be conducted in disputed areas of the Raya zone outside the administration of the Tigray Region.
However, internally displaced people (#IDPs) and residents who participated in the gathering told Addis Standard they were warned that failure to take part could affect their access to humanitarian assistance.
On 23 February 2026, it was reported that Ethiopia’s House of Federation had ordered the upcoming federal parliamentary elections in five electoral districts previously under the Tigray regional state to be conducted outside the Tigray administration’s oversight until the “ownership claim is resolved.”..........
Read more: https://addisstandard.com/?p=55671
News: #NAMA, #ADPM welcome House of Federation decision to hold elections in five districts outside #Tigray oversight
The National Movement of #Amhara (NAMA) and the Amhara Democratic Force Movement (ADPM) have welcomed a recent decision by the House of #Federation to conduct elections in five districts outside the oversight of the Tigray regional authorities, pending the resolution of their constitutional status.
In separate statements issued following emergency executive meetings, both organisations said the decision provides a legal response to long-standing questions of political participation and identity in the “contested” electoral districts, while also raising concerns about its implementation.
NAMA said it respects the decision, which followed communication between the House of Federation and #NEBE, & described it as consistent with the spirit of the Pretoria Agreement.
For its part, ADPM described the House’s move as “the beginning of historical....
Read more: https://addisstandard.com/?p=55369
@ICManagerBot
Qué puede hacer este bot?
Este es un bot moderador de grupos
Idioma: Inglés, Italiano
(visto en @BotsGram_cu)
#lista negra, #ban, #unban, #management, #manage, #manager, #groups, #administration, #federation
@PBlacklistBot
Qué puede hacer este bot?
Con este bot puede crear o unirse a Federaciones, lista negra personalizada que se puede aplicar a muchos grupos al mismo tiempo, y que se administra fácilmente.
Idioma: Inglés, Italiano
(visto en @BotsGram_cu)
#lista negra, #ban, #unban, #management, #manage, #manager, #groups, #administration, #federation
#python#agents#ai#api_gateway#asyncio#authentication_middleware#devops#docker#fastapi#federation#gateway#generative_ai#jwt#kubernetes#llm_agents#mcp#model_context_protocol#observability#prompt_engineering#python#tools
The MCP Gateway is a powerful tool that unifies different AI service protocols like REST and MCP into one easy-to-use endpoint. It helps you manage multiple AI tools and services securely with features like authentication, retries, rate-limiting, and real-time monitoring through an admin UI. You can run it locally or in scalable cloud environments using Docker or Kubernetes. It supports various communication methods (HTTP, WebSocket, SSE, stdio) and offers observability with OpenTelemetry for tracking AI tool usage and performance. This gateway simplifies connecting AI clients to diverse services, making development and management more efficient and secure.
https://github.com/IBM/mcp-context-forge