TGTGInsighttelegram intelligenceLIVE / telegram public index
← Python Заметки

TGINSIGHT SIMILAR POSTS

Најди сличен содржај

Изворен канал @pythonotes · Post #121 · 20 јул.

Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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

Резултати

Пронајдени 114 слични објави

Глобално пребарување

Repositorio data science

@repo_science · Post #3250 · 31.05.2023 г., 11:52

#python#flask#django#html#css#bootstrap 🐍 Python Web Dev Pro: Flask, Django, HTML, CSS & Bootstrap Elevate Your Web Development Skills: Master Back-End & Front-End Technologies with Python, Flask, Django, and Responsive 🔗Link ----- Main channel:@repo_science Coupons: @freecoupons_reposcience -----

djangoproject

@djangoproject · Post #434 · 07.09.2017 г., 12:28

#spaceless#django Removes whitespace between #HTML#tags. This includes tab characters and newlines. Example usage: {% spaceless %} <p> <a href="foo/">Foo</a> </p> {% endspaceless %} This example would return this HTML: <p><a href="foo/">Foo</a></p> https://docs.djangoproject.com/en/1.11/ref/templates/builtins/#spaceless

djangoproject

@djangoproject · Post #362 · 03.07.2017 г., 19:33

https://stackoverflow.com/questions/30288351/how-to-setup-django-1-8-to-use-jinja2 The #Jinja template folder for app dirs defaults to #jinja2 not the standard templates folder. So try the following directory structure and #Django will locate your Jinja #templates: mysite mysite myapp jinja2 myapp index.html manage.py And instead of: return render(request, 'myapp/index.html') you should write: return render(request, 'index.html')

djangoproject

@djangoproject · Post #428 · 30.08.2017 г., 03:40

How #Django knows to #UPDATE vs. #INSERT when you call #save (), #Django follows this algorithm: If the object’s primary key attribute is set to a value that evaluates to True (i.e., a value other than None or the empty string), Django executes an UPDATE. If the object’s primary key attribute is not set or if the UPDATE didn’t update anything, Django executes an INSERT.

djangoproject

@djangoproject · Post #440 · 13.09.2017 г., 14:50

Using the Django authentication system This document explains the usage of Django’s #authentication system in its default configuration. This configuration has evolved to serve the most common project needs, handling a reasonably wide range of tasks, and has a careful implementation of #passwords and #permissions. For projects where authentication needs differ from the default, #Django supports extensive extension and customization of authentication. https://docs.djangoproject.com/es/1.11/topics/auth/default/

djangoproject

@djangoproject · Post #429 · 30.08.2017 г., 18:28

https://docs.djangoproject.com/en/1.11/ref/contrib/syndication/ The syndication #feed framework #Django comes with a high-level syndication-feed-generating framework that makes creating #RSS and #Atom feeds easy. To create any syndication feed, all you have to do is write a short Python class. You can create as many feeds as you want. Django also comes with a lower-level feed-generating API. Use this if you want to generate feeds outside of a Web context, or in some other lower-level way.

djangoproject

@djangoproject · Post #180 · 02.10.2016 г., 20:21

An #apphook allows you to attach a #Django application to a page. For example, you might have a news application that you’d like integrated with #django_cms . In this case, you can create a normal django CMS page without any content of its own, and attach the news application to the page; the news application’s #content will be delivered at the page’s URL. http://docs.django-cms.org/en/release-3.3.x/how_to/apphooks.html

djangoproject

@djangoproject · Post #577 · 02.03.2018 г., 19:28

http://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication #Authentication is the mechanism of associating an incoming request with a set of identifying credentials, such as the user the request came from, or the token that it was signed with. The permission and throttling policies can then use those credentials to determine if the request should be permitted. #REST framework provides a number of authentication schemes out of the box, and also allows you to implement custom schemes. #Django_REST_Framework#Django#DRF

12•••678910
ПретходнаСтраница 8 од 10Следна