Python RU
Все для python разработчиков админ - @haarrp @python_job_interview - Python собеседования @ai_machinelearning_big_data - машинное обучение @itchannels_telegram - 🔥лучшие ит-каналы @programming_books_it - it книги @pythonl РКН: clck.ru/3Fmy2j
Show more📈 Analytical overview of Telegram channel Python RU
Channel Python RU (@pro_python_code) in the Russian language segment is an active participant. Currently, the community unites 12 379 subscribers, ranking 9 841 in the Technologies & Applications category and 52 034 in the Russia region.
📊 Audience metrics and dynamics
Since its creation on невідомо, the project has demonstrated rapid growth, gathering an audience of 12 379 subscribers.
According to the latest data from 30 August, 2026, the channel demonstrates stable activity. Although there has been a change in the number of participants by -49 over the last 30 days and by -7 over the last 24 hours, overall reach remains high.
- Verification status: Not verified
- Engagement rate (ER): The average audience engagement rate is 7.54%. Within the first 24 hours after publication, content typically collects 3.16% reactions from the total number of subscribers.
- Post reach: On average, each post receives 933 views. Within the first day, a publication typically gains 391 views.
- Reactions and interaction: The audience actively supports content: the average number of reactions per post is 6.
- Thematic interests: Content is focused on key topics such as api, docker, github, sql, linux.
📝 Description and content policy
The author describes the resource as a platform for expressing subjective opinions:
“Все для python разработчиков
админ - @haarrp
@python_job_interview - Python собеседования
@ai_machinelearning_big_data - машинное обучение
@itchannels_telegram - 🔥лучшие ит-каналы
@programming_books_it - it книги
@pythonl
РКН: clck.ru/3Fmy2j”
Thanks to the high frequency of updates (latest data received on 31 August, 2026), the channel maintains relevance and a high level of publication reach. Analytics show that the audience actively interacts with content, making it an important point of influence in the Technologies & Applications category.
pip3 install requests bs4
▪Импортируем необходимые модули:
import requests
from bs4 import BeautifulSoup as bs
from urllib.parse import urljoin
from pprint import pprint
# initialize an HTTP session & set the browser
s = requests.Session()
s.headers["User-Agent"] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36"
Мы также инициализировали сессию запросов и установили пользовательский агент.
▪Поскольку SQL-инъекция – это все о пользовательском вводе, нам нужно будет сначала извлечь веб-формы. Нам понадобятся следующие функции:
def get_all_forms(url):
"""Given a `url`, it returns all forms from the HTML content"""
soup = bs(s.get(url).content, "html.parser")
return soup.find_all("form")
def get_form_details(form):
"""
This function extracts all possible useful information about an HTML `form`
"""
details = {}
# get the form action (target url)
try:
action = form.attrs.get("action").lower()
except:
action = None
# get the form method (POST, GET, etc.)
method = form.attrs.get("method", "get").lower()
# get all the input details such as type and name
inputs = []
for input_tag in form.find_all("input"):
input_type = input_tag.attrs.get("type", "text")
input_name = input_tag.attrs.get("name")
input_value = input_tag.attrs.get("value", "")
inputs.append({"type": input_type, "name": input_name, "value": input_value})
# put everything to the resulting dictionary
details["action"] = action
details["method"] = method
details["inputs"] = inputs
return details
Функция get_all_forms() использует библиотеку BeautifulSoup для извлечения всех тегов формы из HTML и возвращает их в виде списка Python, а функция get_form_details() получает в качестве аргумента один объект тега формы и разбирает полезную информацию о форме, такую как действие (целевой URL), метод (GET, POST и т.д.) и все атрибуты поля ввода (тип, имя и значение).
▪Далее мы определяем функцию, которая сообщает нам, есть ли на веб-странице ошибки SQL, это будет удобно при проверке на уязвимость SQL-инъекции:
▪Продолжение
@pro_python_code``
a, b = b, a
```
2. Найти максимальное или минимальное значение в списке:
max_value = max(lst)
min_value = min(lst)
3. Найти индекс максимального или минимального значения в списке:
max_index = lst.index(max(lst))
min_index = lst.index(min(lst))
4. Конкатенация списка строк:
concatenated_string = ''.join(lst)
5. Подсчет вхождений элемента в список:
count = lst.count(item)
6. Переворачиваем строку:
reversed_string = string[::-1]
7. Преобразование строки в список символов:
char_list = list(string)
8. Сортировка списка в порядке убывания:
sorted_list = sorted(lst, reverse=True)
9. Удаление дубликатов из списка:
unique_list = list(set(lst))
10. Вычислить сумму списка чисел:
total = sum(lst)
11. Проверить, все ли элементы списка удовлетворяют условию:
all_true = all(item > 0 for item in lst)
12. Проверьте, удовлетворяет ли условию любой элемент списка:
any_true = any(item > 0 for item in lst)
13. Фильтр списка на основе условия
filtered_list = [item for item in lst if condition]
14. Получение последнего элемента списка:
element_counts = {item: lst.count(item) for item in set(lst)}
15. Получение уникальных элементов и их количества в списке:
element_counts = {item: lst.count(item) for item in set(lst)}
16. Сжимаем вложенный список:
flattened_list = [item for sublist in nested_list for item in sublist]
```
17. Найдите факториал числа:
factorial = 1 if num == 0 else num * factorial(num - 1)
18. Проверить, является ли строка палиндромом:
is_palindrome = string == string[::-1]
```
19. Преобразование списка в строку, разделенную запятым:
csv_string = ','.join(map(str, lst))
20. Получение расширения файла
file_extension = os.path.splitext(filename)[1]import polars as pl
pl.read_csv('https://www.football-data.co.uk/mmz4281/2122/E0.csv')
Получаем датафрейм Polars со всеми данными:
Но это только CSV-файл с данными Премьер-лиги. Чтобы получить файлы с данными других лиг, таких как Championship (Чемпионат), League 1 (Лига 1) и League 2 (Лига 2), нужно добавить цикл for.
Вот как это сделать:
import polars as pl
leagues = ['E0', 'E1', 'E2', 'E3', 'EC'] # список лиг
frames = []
for league in leagues:
df = pd.read_csv(root + "2122" + "/" + league + ".csv")
frames.append(df)
Приведенный выше цикл извлечет CSV-файлы из всех соревнований в сезоне 21/22. Список leagues содержит идентификатор каждой лиги. Например, “E0” означает Премьер-лигу.
Те же шаги можно выполнить для извлечения файлов из нескольких сезонов.
Теперь посмотрим, как извлекать данные из таблиц на HTML-страницах.
Скрейпинг HTML-страниц с Polars (обходной путь)
Polars нет функции .read_html, которая позволяла бы легко извлекать таблицы из HTML-страниц. Однако есть обходной путь, который поможет превратить таблицы из HTML-страниц в Polars-датафреймы.
Для этого в дополнение к Polars нужно установить следующие библиотеки:
!pip install pandas
!pip install lxml
!pip install pyarrow
Pandas и lxml помогут извлечь данные, а pyarrow понадобится для превращения Pandas-датафрейма в Polars-датафрейм.
Извлечем табличные данные из статьи Википедии “List of The Simpsons episodes (seasons 1–20) (“Список эпизодов “Симпсонов”, сезоны 1–20”):
Сначала используем .read_html Pandas для извлечения таблиц из Википедии:
import pandas as pd
my_list = pd.read_html('https://en.wikipedia.org/wiki/List_of_The_Simpsons_episodes_(seasons_1%E2%80%9320)')
my_list содержит список датафреймов. Каждый датафрейм — это таблица со страницы Википедии.
Выберем случайную таблицу и назовем ее pandas_df.
pandas_df = my_list[5]
Теперь нужно использовать .from_pandas, чтобы превратить Pandas-датафрейм в Polars-датафрейм.
polars_df = pl.from_pandas(pandas_df)
Теперь у нас есть Polars-датафрейм со всеми собранными данными.
Чтобы превратить все Pandas-датафреймы из my_list в Polars-датафреймы, можно использовать списковое включение.
my_new_list = [pl.from_pandas(pandas_df) for pandas_df in my_list]
Вот и все! Теперь вы можете пользоваться всеми преимуществами Polars! Чтобы узнать больше о Polars, ознакомьтесь с официальной документацией или посмотрите полное руководство по Polars.
@pro_python_codeimport redis
# Connect to Redis
r = redis.Redis(host='localhost', port=6379, db=0)
def get_data_from_cache(key):
# Check if data exists in the cache
if r.exists(key):
# Retrieve data from the cache
data = r.get(key)
return data.decode('utf-8') # Convert bytes to string
else:
# Fetch data from the primary data source
data = fetch_data_from_source()
# Store data in the cache with a timeout of 1 hour
r.setex(key, 3600, data)
return data
2. Pub/Sub (Publish/Subscribe):
Redis поддерживает паттерн pub/sub, позволяя вам создавать системы обмена сообщениями. Вот пример:
import redis
import time
# Connect to Redis
r = redis.Redis(host='localhost', port=6379, db=0)
def publish_message(channel, message):
# Publish a message to the specified channel
r.publish(channel, message)
def subscribe_channel(channel):
# Subscribe to a channel and process incoming messages
pubsub = r.pubsub()
pubsub.subscribe(channel)
for message in pubsub.listen():
print(message['data'].decode('utf-8')) # Process the received message
3. Rate Limiting:
Redis можно использовать для реализации ограничения скорости, чтобы контролировать количество запросов или операций за период времени. Пример:
import redis
# Connect to Redis
r = redis.Redis(host='localhost', port=6379, db=0)
def check_rate_limit(ip_address):
# Increment the request count for the IP address
request_count = r.incr(ip_address)
# If the count exceeds the limit (e.g., 100 requests per minute), deny the request
if request_count > 100:
return False
return True
4. Session Storage:
Redis можно использовать для хранения данных сеанса в веб-приложениях. Пример:
import redis
import uuid
# Connect to Redis
r = redis.Redis(host='localhost', port=6379, db=0)
def create_session(user_id):
# Generate a unique session ID
session_id = str(uuid.uuid4())
# Store the session data in Redis with a timeout of 30 minutes
r.setex(session_id, 1800, user_id)
return session_id
def get_user_id_from_session(session_id):
# Retrieve the user ID from the session data in Redis
user_id = r.get(session_id)
if user_id is not None:
return user_id.decode('utf-8') # Convert bytes to string
else:
return None
5. Leaderboard:
Redis можно использовать для создания таблиц лидеров или рейтингов на основе набранных баллов. Пример:
import redis
# Connect to Redis
r = redis.Redis(host='localhost', port=6379, db=0)
def update_score(player_id, score):
# Update the score of a player
r.zadd('leaderboard', {player_id: score})
def get_leaderboard():
# Get the top 10 players from the leaderboard
leaderboard = r.zrevrange('leaderboard', 0, 9, withscores=True)
for player, score in leaderboard:
print(f"Player: {player.decode('utf-8')}, Score: {score}")
Это лишь несколько примеров того, как Redis можно использовать в Python. Redis предоставляет множество других мощных функций и структур данных, которые можно использовать в различных приложениях.
▪Github
@pro_python_code