@hal.littel
To connect to a Redis database in Python, you can use the redis
library. Here's a step-by-step guide on how to connect to a Redis database in Python:
- Install the redis library by running the following command:
- Import the redis library in your Python script:
- Create a Redis connection by specifying the host, port, and database number:
1
2
3
4
5
|
redis_host = 'localhost'
redis_port = 6379
redis_db = 0
r = redis.Redis(host=redis_host, port=redis_port, db=redis_db)
|
- You can perform various operations on the Redis database using the r object. Here are some examples:
1
2
3
4
5
6
7
8
9
|
# Set a key-value pair in the database
r.set('key', 'value')
# Get the value of a key
value = r.get('key')
print(value)
# Delete a key
r.delete('key')
|
- You can also use Redis commands directly using the r object. For example:
1
2
3
4
5
6
|
# Add an item to a list
r.rpush('mylist', 'item1')
# Get all items from a list
items = r.lrange('mylist', 0, -1)
print(items)
|
That's it! You have successfully connected to a Redis database in Python and can start interacting with it using the redis
library.