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)

댓글

이 블로그의 인기 게시물

To switch to a specific tag in a Git repository

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

Using the MinIO API via curl

To download a file from MinIO using Spring Boot, 스프링부트 Minio 사용하기

리눅스의 부팅과정 (프로세스, 서비스 관리)

Chromium 개발 환경 세팅, 크로미움 개발 준비하기

Joining an additional control plane node to an existing Kubernetes cluster

urllib3 with proxy settings

CDPEvents in puppeteer

Avro + Grpc in python