Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
https://www.coursereport.com/blog/ruby-on-rails-vs-python-and-django-which-should-a-beginner-learn
Over a year ago I found myself in a position where my career options looked bleak. I had intended on going to graduate school for economic development. But, instead of dishing out the time and money for another two years of school, I decided to teach myself how to code. (I had always loved to problem solve, anyways.) But, like most beginners, I struggled with knowing where to start. I want to create web apps: but where should I begin?
My ultimate goal was to eventually build web apps. After a little “web application development” research on Google, it became clear that Ruby on Rails (#RoR) and #Python and #Django are two very popular methods to create web apps. But which is best for a beginner to learn?
#RoR requires less work to get up and running and #Django allows for more customization.
http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html
Previous versions of #Celery required a separate library to work with #Django, but since 3.1 this is no longer the case. Django is supported out of the box now so this document only contains a basic way to integrate Celery and Django. You’ll use the same #API as non-Django users so you’re recommended to read the First Steps with Celery tutorial first and come back to this tutorial. When you have a working example you can continue to the Next Steps guide.
Добро пожаловать в мир продвинутогоPython программирования: @pro_python_code
В канале вы найдет :
📃Статьи ,
📚Книги
👨💻Код
🔗Ссылки
и много другой полезной информации
#Python#Django
#Machine Learning #DataScience
#Django#Advancedresearch
1 канал вместо тысячи учебников и курсов, подписывайтесь: 👇👇👇
🐍@pythonl
http://kennypham.me/2015/11/10/problem-with-react-router-and-django-url/
Hello there,
I have faced this problem since the beginning of the current project. The problem is that #react-router and #Django#urls don't like each others.
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
How to deploy with #WSGI
Django’s primary deployment platform is WSGI, the Python standard for web servers and applications.
Django’s startproject management command sets up a simple default WSGI configuration for you, which you can tweak as needed for your project, and direct any WSGI-compliant application #server to use.
#django
https://realpython.com/blog/python/caching-in-django-with-redis/
Caching in #Django With #Redis
Application performance is vital to the success of your product. In an environment where users expect website response times of less than a second, the consequences of a slow application can be measured in dollars and cents. Even if you are not selling anything, fast page loads improve the experience of visiting your site.
Everything that happens on the server between the moment it receives a request to the moment it returns a response increases the amount of time it takes to load a page. As a general rule of thumb, the more processing you can eliminate on the server, the faster your application will perform. Caching data after it has been processed and then serving it from the #cache the next time it is requested is one way to relieve stress on the server. In this tutorial, we will explore some of the factors that bog down your application, and we will demonstrate how to implement caching with Redis to counteract their effects.
#Django REST #framework is a powerful and flexible toolkit for building #Web APIs.
Some reasons you might want to use REST framework:
The Web browsable #API is a huge usability win for your developers.
Authentication policies including packages for OAuth1a and OAuth2.
Serialization that supports both ORM and non-ORM data sources.
Customizable all the way down - just use regular function-based views if you don't need the more powerful features.
Extensive documentation, and great community support.
Used and trusted by internationally recognised companies including Mozilla, Red Hat, Heroku, and Eventbrite.
http://www.django-rest-framework.org/
https://medium.com/@djstein/modern-django-part-2-rest-apis-apps-and-django-rest-framework-ea0cac5ab104
Modern #Django — Part 2: #REST APIs, Apps, and #Django_REST Framework
#Python#Django#bootcamp#webDeveloper
🐍
Python and Django Full Stack Web Developer Bootcamp for 2023
We will teach you the latest technologies for building great web applications with Python 3 and Django! But we don’t just teach that, we also teach the Front End technologies you need to know, including HTML, CSS, and Javascript. This course can be your one stop shop for everything you need! It will serve as a useful reference for many of your questions as you begin your journey in becoming a web developer!
🔗Link
🔐@repo_science
-----
Main channel: @repo_science
Coupons: @freecoupons_reposcience
-----
https://realpython.com/blog/python/asynchronous-tasks-with-django-and-celery/
Asynchronous Tasks With #Django and #Celery
“Celery is an asynchronous task queue/job #queue based on distributed message passing. It is focused on real-time operation, but supports scheduling as well.” For this post, we will focus on the scheduling feature to periodically run a job/task.
http://mongoengine.readthedocs.io/en/latest/index.html
#MongoEngine is an Object-Document Mapper, written in #Python for working with #MongoDB. To install it, simply run
#Django