TGViewer
Python RU Python RU @pro_python_code · 12.3K subscribers
Post #1010 2.34K
🔥 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

@pro_python_code
  • 👍 8
  • ❤ 2
  • 🔥 1
More from @pro_python_code
  1. Oct 4, 2026Hugging Face исследовали multi-harness RL: обучение с подкреплением сразу через Claude Cod…
  2. Oct 1, 2026DeepSeek Harness вышел на десктоп: плагины без терминала и задачи по расписанию DeepSeek в…
  3. Sep 30, 2026Пишем игру на Python: неоновая аркада с разбором кода и ИИ Pygame часто считают библиотеко…
  4. Sep 29, 2026photo post
  5. Sep 28, 2026photo post
  6. Sep 26, 2026🐧 Linux Cheat Sheet - шпаргалка по командам Linux Самая удобная шпаргалка по Linux и Bash…
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 →