How to connect redis database in python?

by hal.littel , in category: Third Party Scripts , a year ago

How to connect redis database in python?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by wilmer.lemke , a year ago

@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:

  1. Install the redis library by running the following command:
1
pip install redis


  1. Import the redis library in your Python script:
1
import redis


  1. 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)


  1. 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')


  1. 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.

Related Threads:

How to connect to oracle database with python?
How to connect to mysql database using python?
How to connect database using ssl in laravel?
How to mock redis in python?
How to store dictionary in redis from python?
How to connect to master in redis from slave?