redis.py 2.13 KB
Newer Older
崔为之's avatar
崔为之 committed
1 2 3 4 5 6 7 8 9
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
# @Version     : Python 3.11.4
# @Software    : Sublime Text 4
# @Author      : StudentCWZ
# @Email       : StudentCWZ@outlook.com
# @Date        : 2023/11/7 15:47
# @File        : redis.py
崔为之's avatar
崔为之 committed
10
# @Description : Defines the RedisUri class for generating a Redis connection URI.
崔为之's avatar
崔为之 committed
11 12 13 14 15 16 17 18 19 20 21
"""


class RedisUri:
    """
    A class to generate a Redis connection URI.
    """
    def __init__(self, host='localhost', port=6379, db=0, username=None, password=None):
        """
        Initializes a new instance of the RedisUri class.

崔为之's avatar
崔为之 committed
22 23 24 25 26 27
        Args:
            host (str): The hostname of the Redis server. Default is 'localhost'.
            port (int): The port number to connect on the Redis server. Default is 6379.
            db (int): The database number to connect on the Redis server. Default is 0.
            username (str, optional): The username for authentication to the Redis server.
            password (str, optional): The password for authentication to the Redis server.
崔为之's avatar
崔为之 committed
28 29 30 31 32 33 34 35 36 37 38
        """
        self.host = host
        self.port = port
        self.db = db
        self.username = username
        self.password = password

    def create(self) -> str:
        """
        Creates and returns the Redis connection URI.

崔为之's avatar
崔为之 committed
39 40
        Returns:
            str: The Redis connection URI.
崔为之's avatar
崔为之 committed
41 42 43 44 45 46 47 48 49 50
        """
        if self.username and self.password:
            return f'redis://{self.username}:{self.password}@{self.host}:{self.port}/{self.db}'
        else:
            return f'redis://{self.host}:{self.port}/{self.db}'

    def __repr__(self):
        """
        Returns a formal string representation of the RedisUri object.

崔为之's avatar
崔为之 committed
51 52
        Returns:
            str: The formal string representation of the RedisUri object.
崔为之's avatar
崔为之 committed
53 54 55 56 57 58
        """
        return (f'RedisUri(host={self.host}, port={self.port}, db={self.db}, username={self.username}, '
                f'password={self.password})')

    def __str__(self):
        """
崔为之's avatar
崔为之 committed
59
        Returns a string representation of the RedisUri object, which is the Redis connection URI.
崔为之's avatar
崔为之 committed
60

崔为之's avatar
崔为之 committed
61 62
        Returns:
            str: The string representation of the RedisUri object.
崔为之's avatar
崔为之 committed
63 64
        """
        return self.create()