Redis - Create key value pairs using Python

by
Jeremy Canfield |
Updated: February 11 2024
| Redis articles
This assumes you are already able to connect to Redis using Python. If not, check out my article Connect to Redis using Python. Here is an example of how to create a key value pair using set and then immediately get the key value using get.
#!/usr/bin/python3
import redis
try:
client = redis.Redis.from_url("redis://my-redis-cluster.abc123.clustercfg.use1.cache.amazonaws.com:6379")
except Exception as exception:
print(f"got the following exception when trying redis.Redis.from_url - {exception}")
else:
print(f"It appears the connection to Redis was successful")
try:
client.set('foo', 'bar')
except Exception as exception:
print(f"got the following exception when trying to set key 'foo' to have a value of 'bar' - {exception}")
else:
print(f"successfully set the 'foo' key to have a value of 'bar'")
try:
response = client.get('foo')
except Exception as exception:
print(f"got the following exception when trying to get key 'foo' - {exception}")
else:
print(f"foo = {response.decode('utf-8')}")
Something like this should be returned.
It appears the connection to Redis was successful
successfully set the 'foo' key to have a value of 'bar'
foo = bar
In the above expire, the "foo" key will never expire. In this example, the key will expire after 60 seconds.
#!/usr/bin/python3
import redis
try:
client = redis.Redis.from_url("redis://my-redis-cluster.abc123.clustercfg.use1.cache.amazonaws.com:6379")
except Exception as exception:
print(f"got the following exception when trying redis.Redis.from_url - {exception}")
else:
print(f"It appears the connection to Redis was successful")
try:
client.set('foo', 'bar', ex=60)
except Exception as exception:
print(f"got the following exception when trying to set key 'foo' to have a value of 'bar' - {exception}")
else:
print(f"successfully set the 'foo' key to have a value of 'bar'")
try:
response = client.get('foo')
except Exception as exception:
print(f"got the following exception when trying to get key 'foo' - {exception}")
else:
print(f"foo = {response.decode('utf-8')}")
Did you find this article helpful?
If so, consider buying me a coffee over at