TGViewer
Аналитик данных Аналитик данных @dataanlitics · 6.26K subscribers
Post #10 459
🔥 5 примеров использования Redis с кодом на Python

1. Caching
Redis можно использовать для кэширования часто используемых данных, снижая нагрузку на ваше основное хранилище данных. Вот пример того, как реализовать кэширование с помощью Redis в Python

import 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

@data_analysis_ml
More from @dataanlitics
  1. Oct 2, 2026🚀 LLM всё лучше пишут код. Следующая проблема - как человеку быстро понимать их результат…
  2. Sep 30, 2026⚡️ DeepSeek перенесла DeepGEMM на Huawei Ascend и выжала из железа 99,8% DeepSeek выложила…
  3. Sep 22, 2026👣 Google открыла исходный код AX, среды для запуска AI-агентов в продакшене. AX изолирует…
  4. Sep 15, 2026📘 Бесплатный 17-страничный PDF по Hidden Markov Models (HMM) Короткий материал от Stanfor…
  5. Sep 15, 2026🔥 Один из лучших обучающих курсов на StepiK по SQL SQL можно знать годами и всё равно тер…
  6. Sep 10, 2026✔️ Hugging Face запустила агента для ML-экспериментов Платформа встроила в свой чат-бот от…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →