Python application with redis

To set a key-value pair in Redis with an expiry date using Python, you can use the redis library. Here's how you can do it:

Step 1: Install the redis library

If you don’t already have the Redis Python client installed, you can install it using pip:

pip install redis

Step 2: Connect to Redis and Set the Key-Value Pair

Here's an example of setting a key-value pair with an expiry date (TTL):

import redis

# Connect to the Redis server
client = redis.Redis(host='localhost', port=6379, db=0)

# Set a key-value pair with an expiration time (in seconds)
key = "example_key"
value = "example_value"
expiration_seconds = 3600  # Expire in 1 hour

client.set(key, value, ex=expiration_seconds)

# Verify the value
retrieved_value = client.get(key)
print(f"The value for '{key}' is: {retrieved_value.decode('utf-8')}")

Explanation:

  • client.set(key, value, ex=expiration_seconds): This sets the key with a value and an expiry in seconds.
  • The decode('utf-8') is used to convert the byte response from Redis into a string.

Optional: Use Python datetime for more readable expiration

If you want to specify a TTL in terms of a specific date or time, calculate the seconds until that time:

from datetime import datetime, timedelta

# Calculate expiration in seconds
now = datetime.now()
expiry_date = now + timedelta(hours=1)  # 1 hour from now
expiration_seconds = int((expiry_date - now).total_seconds())

# Set the key with the calculated expiration
client.set(key, value, ex=expiration_seconds)

댓글

이 블로그의 인기 게시물

Using the MinIO API via curl

How to split a list into chunks of 100 items in JavaScript, 자바스크립트 리스트 쪼개기

HTML Inline divisions at one row by Tailwind

Boilerplate for typescript server programing

가속도 & 속도

Gradle multi-module project

How to checkout branch of remote git, 깃 리모트 브랜치 체크아웃

CDPEvents in puppeteer

Sparse encoder

Reactjs datetime range picker