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)

댓글

이 블로그의 인기 게시물

Install and run an FTP server using Docker

Using the MinIO API via curl

PYTHONPATH, Python 모듈 환경설정

Elasticsearch Ingest API

오늘의 문장2

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

Fundamentals of English Grammar #1

To switch to a specific tag in a Git repository

You can use Sublime Text from the command line by utilizing the subl command

티베트-버마어파 와 한어파(중국어파)의 어순 비교