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)

댓글

이 블로그의 인기 게시물

Creating an synchronous HTTP request using Spring RestTemplate

how to delete all issues on project in sentry, 센트리 이슈 삭제하기

동남아 국가들이 사용하는 언어

형태소 분석 태그

MySQL GRANT

max_active_runs of Airflow

Read a file in Java, 자바 파일 읽기

dagrun_timeout of Airflow

ssh-copy-id in ansible

Create fixed rounded button by Tailwind