Use cache concept with Redis : Let's do Redis programming with Python

CK CK 3788 
Created at  
529 0 0

Redis is an open-source, in-memory data structure store, used as a database, cache, and message broker.

It supports data structures such as strings, hashes, lists, sets, sorted sets, bitmaps, hyperloglogs, geospatial indexes, and streams, allowing for flexible data modeling and efficient retrieval.

Its in-memory nature provides extremely fast read and write speeds, making it ideal for applications requiring high performance and low latency.

Use cache concept with Redis : Let's do Redis programming with Python

To use Redis in Python, you'll need to install the redis library (now called redis-py) and then connect to your Redis server to perform operations. Here's a step-by-step guide with an example:


 

Install Redis Library

You can install the library using pip:

pip install redis


 

Example: Basic Usage of Redis in Python

import redis

# Connect to Redis server
client = redis.StrictRedis(
    host='localhost',  # Replace with your Redis server host (default: 'localhost')
    port=6379,         # Redis server port (default: 6379)
    db=0,              # Redis database index (default: 0)
    decode_responses=True  # Automatically decode string responses
)

# Set a key-value pair
client.set('name', 'Alice')

# Get the value of a key
value = client.get('name')
print(f"The value of 'name' is: {value}")

# Increment a key
client.set('counter', 0)  # Initialize counter
client.incr('counter')    # Increment by 1
print(f"The value of 'counter' is: {client.get('counter')}")

# Delete a key
client.delete('name')

# Check if a key exists
exists = client.exists('name')
print(f"Does 'name' exist? {bool(exists)}")

# Add to a list
client.rpush('tasks', 'task1', 'task2', 'task3')

# Retrieve the list
tasks = client.lrange('tasks', 0, -1)
print(f"Tasks list: {tasks}")

# Remove all keys in the database
client.flushdb()
print("Database cleared.")


 

Explanation of Key Functions:

  • set(key, value): Store a key-value pair.
  • get(key): Retrieve the value associated with a key.
  • incr(key): Increment the value of a key (useful for counters).
  • delete(key): Delete a key from Redis.
  • exists(key): Check if a key exists.
  • rpush(key, *values): Push elements to the end of a list.
  • lrange(key, start, end): Get a range of elements from a list.
  • flushdb(): Remove all keys from the current database.


 

Running Redis Server

Ensure that a Redis server is running locally or remotely before executing the code. You can start a Redis server with:

redis-server

This basic example demonstrates Redis as a key-value store, but Redis also supports other data structures like hashes, sets, and sorted sets. Let me know if you'd like more advanced examples!


 

Methods to Set Expiration:

  1. Using the expire Method
    Set an expiration time (in seconds) after creating a key.

    client.set('temp_key', 'temporary_value')
    client.expire('temp_key', 10)  # Expire after 10 seconds
    
  2. Setting Expiration When Creating a Key
    Use the ex (seconds) or px (milliseconds) parameter when using set.

    client.set('temp_key', 'temporary_value', ex=10)  # Expires after 10 seconds
    client.set('temp_key_ms', 'temporary_value', px=5000)  # Expires after 5000ms (5 seconds)
    
  3. Using setex Method
    Combines setting a key and expiration in a single step.

    client.setex('temp_key', 10, 'temporary_value')  # Set value with 10 seconds expiration
    


 

Example Code with Expiration:

import redis
import time

# Connect to Redis
client = redis.StrictRedis(
    host='localhost',
    port=6379,
    db=0,
    decode_responses=True
)

# Set a key with an expiration time
client.set('temp_key', 'temporary_value', ex=5)  # Expires in 5 seconds
print(f"temp_key: {client.get('temp_key')}")

# Wait for 6 seconds
time.sleep(6)

# Try to get the key after expiration
value = client.get('temp_key')
print(f"temp_key after expiration: {value}")  # Should print None


 

Useful Expiration-Related Commands:

  • ttl(key): Check the remaining time-to-live (TTL) of a key (in seconds). Returns -1 if no expiration is set and -2 if the key doesn't exist.

    ttl = client.ttl('temp_key')
    print(f"Time-to-live for temp_key: {ttl} seconds")
    
  • persist(key): Remove the expiration from a key, making it permanent.

    client.persist('temp_key')
    
Tags Cache In-Memory Processing Pythin Redis Library Python Redis Reis redis-py Facebook X
Comments 0
Similar posts
  1. Using Queue Algorithm with Redis - RPUSH and LPOP
    767
  2. CloudFront Settings for Dynamic HLS Streaming
    650
  1. Python ML Technologies used for the target Segmentation
    376
  2. Managing WHITE_LIST in FastAPI to Improve the Server Security
    346
  3. A common async example
    966
  4. Milvus and LLM Integration - Very Smart Approach!
    294
  5. Automated API Documentation with PyCharm
    889
  6. How to install python 3.9 alongside python 3.8 on CentOS 7?
    707
  7. How to run Python 3.9 on Mac?
    647
  8. Python Quizs
    501
  9. Automated OpenAPI documentation for a Python Flask API
    1,118
  10. Automated API documentation for a Django REST Framework (DRF) project using drf-yasg (Yet Another Swagger Generator)
    1,026
  11. Uploading a file to a Google Drive Folder programmatically with Python
    3,305
  12. Garbage Collection when your system does not have enough memory in your Python App
    1,009
  13. Method to maximize full CPU performance with Python
    314
  14. How do I get the maximum available of thread in python?
    981
  15. Using Queue Algorithm with Redis - RPUSH and LPOP
    767
  16. Installing Python 3.8 in a venv environment on CentOS 7
    461
  17. CUDA versus OpenCL
    577
  18. Simple gRPC server based on Python
    393
  19. Python code to convert PDF file to Excel Spreadsheet
    695
  20. Python script to list files on your Google Drive and download one of them
    939
  21. Coinbase Python API - Basic Example
    461
  22. AWS Lambda Code Example based on Python
    333
  23. Python code using GPU on CentOS with AWS
    1,248
  24. Video Scence Detection with PySceneDetect
    2,318
  25. Python Audio Separation Libraries allowing you to isolate individual tracks
    1,433
  26. Python Version Control for Library Compatibility with pyenv - Downgrading/Upgrading Python Version
    902
  27. Deleting a specific user voice from the original audio track with Python
    547
  28. Creating an MR from the original MP3 audio in Python - Deleting Voice Track from Audio File
    436
  29. Creating mp3 audio file based on the text input with Python
    464
  30. Implementing Text To Speech / Audio with Python3 and pyttsx3
    354
Recently updated
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    27
  2. Why SPF and DKIM Are Essential for Linux Email Servers?
    24
  3. How do I create animated background for Google Meet?
    19,733
  4. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    217
  5. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    86
  6. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    153
  7. Array of arguments passed to script in PHP
    85
  8. Invalid Auction Storms in Ad Tech
    93
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    198
  10. The Two Clocks of Ad Server Architecture
    63
  11. Frequency Cap Architecture Overview
    509
  12. Collecting Proof-of-Play from 100,000 Screens
    141
  13. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    280
  14. What is RedisVL?
    105
  15. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    224
  16. TPU & GPU Cluster Management Tools
    234
  17. The Concept of Scaffolding in AI Agents
    222
  18. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    576
  19. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    253
  20. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    328
  21. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    197
  22. Machine Learning: Training vs. Ranking
    213
  23. The Continuous Learning Machine: Designing a Loop That Actually Turns
    217
  24. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    189
  25. Designing a Data Curation System Around a Vector Database
    215
  26. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    229
  27. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    649
  28. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    185
  29. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    207
  30. Understanding Data Lineage
    252