Ejemplo n.º 1
0
    def update_cache(self):
        """
            uses non-presistent Redis to create a cache of donor values
        """
        donors = self.get_list_of_donors()

        d = login_database.login_redis_cloud()

        for value in d.keys():
            d.delete(value)

        r = login_database.login_redis_cloud()

        print("\nUpdating Donor cache...\n")

        for name in donors:
            summary = self.get_donor_summary(name)

            # Create donor cache
            r.hmset(
                name, {
                    'phone': self.get_phone_number(),
                    'email': self.create_email(name),
                    'zip': self.get_zip(),
                    'last_donation': '$' + str(summary["last_donation"]),
                    'last_donation_date': self.get_date()
                })
Ejemplo n.º 2
0
def redis_mailroom():
    """
        uses non-presistent Redis only (as a cache).
        seeding data one at a time
    """

    log = utilities.configure_logger('default', '../logs/redis_script.log')

    try:
        log.info('Connect to Redis')
        r = login_database.login_redis_cloud()

        r.set('Donor_tjefferson', 'Thomas Jefferson')
        r.set('Email_tjefferson', '*****@*****.**')
        r.set('Donation_tjefferson','100')
        r.set('Donor_brubble', 'Betty Rubble')
        r.set('Email_brubble', '*****@*****.**')
        r.set('Donation_brubble','500')
        r.set('Donor_gjetson', 'George Jetson')
        r.set('Email_gjetson', '*****@*****.**')
        r.set('Donation_gjetson','60')
        r.set('Donor_lsimpson', 'Lisa Simpson')
        r.set('Email_lsimpson', '*****@*****.**')
        r.set('Donation_lsimpson','100')

        log.info('Retrieve some customer info')
        donor_name = r.get('Donor_brubble')
        log.info(f'Donor name is: {donor_name}')
        donor_email = r.get('Email_lsimpson')
        log.info(f'Lisa Simpson has email: {donor_email}')
        donation = r.get('Donation_gjetson')
        log.info(f'The initial donation by George Jetson: ${donation}')

    except Exception as e:
        print(f'Redis error: {e}')
def run_example():
    """
        uses non-persistent Redis only (as a cache)

    """

    log = utilities.configure_logger('default', '../logs/redis_script.log')

    try:
        log.info('Step 1: connect to Redis')
        r = login_database.login_redis_cloud()

        log.info('Step 2: do the homework')
        r.rpush('William Gates III', '*****@*****.**')
        r.rpush('William Gates III', '4255551212')
        r.rpush('William Gates III', '98101')
        r.rpush('Jeff Bezos', '*****@*****.**')
        r.rpush('Jeff Bezos', '2065551212')
        r.rpush('Jeff Bezos', '98115')
        r.rpush('Paul Allen', '*****@*****.**')
        r.rpush('Paul Allen', '2065559000')
        r.rpush('Paul Allen', '98104')
        r.rpush('Mark Zuckerberg', '*****@*****.**')
        r.rpush('Mark Zuckerberg', '4255552912')
        r.rpush('Mark Zuckerberg', '98125')

    except Exception as e:
        print(f'Redis error: {e}')
Ejemplo n.º 4
0
 def __init__(self):
     try:
         self.r = login_database.login_redis_cloud()
         self.r.flushdb()
         self.populate_db()
     except Exception as e:
         print(f"Redis error: {e}")
Ejemplo n.º 5
0
    def donor_lookup(self, name, value):
        """
            uses Redis cache to validate a users value
        """

        r = login_database.login_redis_cloud()

        str_format_1 = "\n    {0}'s {1} is: {2}"
        str_format_2 = "    {0}: {1}"
        list_of_values = [
            'phone', 'email', 'zip', 'last_donation', 'last_donation_date'
        ]

        if (value == "all"):
            print(f"\n{name}\'s stored values:\n")
            for i in list_of_values:
                print(
                    str_format_2.format(
                        i.replace('_', ' ').capitalize(), r.hget(name, i)))
        else:
            # Get requested value
            req_val = r.hget(name, value)

            frmt_val = value.lower().replace('_', ' ').capitalize()
            print(str_format_1.format(name, frmt_val, req_val))
def redis_assignment_create():
    log = utilities.configure_logger('default', 'logs/redis_script.log')

    try:
        log.info('Step 1: connect to Redis')
        r = login_database.login_redis_cloud()
        phoneidx = 0
        zipidx = 1

        r.rpush('Jeroen', 15555222)
        r.rpush('Jeroen', 2800)

        r.rpush('Heinz', 2001589)
        r.rpush('Heinz', 1000)

        r.rpush('Knudde', 3658714)
        r.rpush('Knudde', 6900)

        r.rpush('Gaston', 22222221111)
        r.rpush('Gaston', 98139)

        r.rpush('Neintje', 121212129)
        r.rpush('Neintje', 7000)

        r.rpush('Bumbalu', 31346546)
        r.rpush('Bumbalu', 9999)
        phone = r.lindex('Jeroen', phoneidx)
        log.info(f'Jeroen Phone Number = {phone}')
        zipcode = r.lindex('Jeroen', zipidx)
        log.info(f'Jeroen Zip Code = {zipcode}')
    except Exception as e:
        print(f'Redis error: {e}')
Ejemplo n.º 7
0
def run_example():
    """
        uses non-presistent Redis only (as a cache)
    """

    log = utilities.configure_logger('default', '../logs/redis_script.log')

    try:
        log.info('Step 1: Connect to Redis')
        r = login_database.login_redis_cloud()

        log.info('Step 2: Adding 8 customers to the data cache')
        r.hmset('Bill', {'phone': '2538-234-1433', 'zip': 98277})
        r.hmset('Elon', {'phone': '125-290-2443', 'zip': 23904})
        r.hmset('Jeff', {'phone': '654-490-2300', 'zip': 49039})
        r.hmset('Nikola', {'phone': '453-872-9982', 'zip': 23922})
        r.hmset('Steve', {'phone': '238-403-4923', 'zip': 34095})
        r.hmset('John', {'phone': '299-343-4785', 'zip': 18492})
        r.hmset('Joe', {'phone': '947-239-1114', 'zip': 24909})
        r.hmset('Harry', {'phone': '808-333-9942', 'zip': 54848})

        log.info('Step 3: Retrieve zip code')
        ret_zip = r.hmget('Elon', 'zip')
        log.info(f"Elon's zip is {ret_zip[0]}.")

        log.info('Step 4: Retrieve phone number')
        ret_phone = r.hmget('John', 'phone')
        log.info(f"John's phone number is {ret_phone[0]}.")

    except Exception as e:
        print(f'Redis error: {e}')
def list_donors():
    try:
        r = login_database.login_redis_cloud()
        for i in r.keys():
            print(i)
    except Exception as e:
        print(f'Redis error: {e}')
def send_thankyou():
    don_input = None
    while not don_input:
        don_input = donor_input()
        if don_input.lower() == "list":
            list_donors()
            don_input = None            
        
    donation = None
    while not donation:
        try:
            donation = int(donation_prompt())
        except ValueError:
            print("Enter donations numerically")
    phone = input('Input phone number in format XXX-XXX-XXXX: ')
    zpcd = input('Input zip code in format: XXXXX: ')
    email = input('Input email address: ')
    try:
        r = login_database.login_redis_cloud()
        r.hmset(don_input, {'phone': phone,
                            'zip': zpcd,
                            'donation': [donation],
                            'email': email})
    except:
        print("Error in inputing user to database")
    
    print("Thank you {} for your donation of ${}"
              .format(don_input, donation))
Ejemplo n.º 10
0
def clear_redis():
    '''
    Clear all keys from redis.
    '''
    r = login_database.login_redis_cloud()
    for key in r.keys():
        r.delete(key)
Ejemplo n.º 11
0
def delete_donor():
    name = input('Enter name to delete from database: ')
    r = login_database.login_redis_cloud()
    if r.exists(name):
        r.delete(name)
    else:
        print('{} is not in the database'.format(name))
Ejemplo n.º 12
0
def run_example():
    """
        uses non-presistent Redis only (as a cache)

    """

    log = utilities.configure_logger('default', '../logs/redis_script.log')

    try:
        log.info('Step 1: connect to Redis')
        r = login_database.login_redis_cloud()
        log.info('Step 2: cache some data in Redis')
        r.set('andy', '*****@*****.**')

        log.info('Step 2: now I can read it')
        email = r.get('andy')
        log.info('But I must know the key')
        log.info(f'The results of r.get: {email}')

        log.info('Step 3: cache more data in Redis')
        r.set('pam', '*****@*****.**')
        r.set('fred', '*****@*****.**')

        log.info('Step 4: delete from cache')
        r.delete('andy')
        log.info(f'r.delete means andy is now: {email}')

        log.info(
            'Step 6: Redis can maintain a unique ID or count very efficiently')
        r.set('user_count', 21)
        r.incr('user_count')
        r.incr('user_count')
        r.decr('user_count')
        result = r.get('user_count')
        log.info('I could use this to generate unique ids')
        log.info(f'Redis says 21+1+1-1={result}')

        log.info('Step 7: richer data for a SKU')
        r.rpush('186675', 'chair')
        r.rpush('186675', 'red')
        r.rpush('186675', 'leather')
        r.rpush('186675', '5.99')

        log.info('Step 8: pull some data from the structure')
        cover_type = r.lindex('186675', 2)
        log.info(f'Type of cover = {cover_type}')

        log.info('Step 9: add users with phone # and zip code')
        r.hmset('Bugs Bunny', {'Phone':'800-214-1234', 'Zip_Code':'98042'})
        r.hmset('Porky Pig', {'Phone':'999-555-1212', 'Zip_Code':'98031'})
        r.hmset('Foghorn Leghorn', {'Phone':'805-637-7032', 'Zip_Code':'93454'})
        r.hmset('Tweety Bird', {'Phone':'425-222-333', 'Zip_Code':'90210'})
        r.hmset('Elmer Fudd', {'Phone':'900-315-7654', 'Zip_Code':'99888'})

        log.info('Step 10: Get phone and zip for user')
        data = r.hgetall('Foghorn Leghorn')
        log.info(f'Foghorn Leghorn info: Phone #: {data["Phone"]} Zip Code: {data["Zip_Code"]}')

    except Exception as e:
        print(f'Redis error: {e}')
Ejemplo n.º 13
0
def run_example():
    """
    Refactored Redis example
    """

    log = utilities.configure_logger('default', '../logs/redis_script.log')

    try:
        r = login_database.login_redis_cloud()

        log.info(f'Add more customer data')
        customers = [
            ['halpert', {'telephone': '111-111-1111', 'zip': '11111'}],
            ['michael', {'telephone': '222-222-2222', 'zip': '22222'}],
            ['kevin', {'telephone': '333-333-3333', 'zip': '33333'}],
            ['oscar', {'telephone': '444-444-4444', 'zip': '44444'}],
            ['ryan', {'telephone': '555-555-5555', 'zip': '55555'}],
            ['Phyllis', {'telephone': '666-666-6666', 'zip': '66666'}]
        ]

        for key, data in customers:
            r.hmset(key, data)

        log.info(f'Retreive customer info')
        key = "oscar"
        result = r.hgetall(key)
        print(f"Telephone for {key}: {result['telephone']}")
        print(f"Zip for {key}: {result['zip']}")

    except Exception as e:
        print(f'Redis error: {e}')
Ejemplo n.º 14
0
def run_example():
    """
        uses non-presistent Redis only (as a cache)

    """

    log = utilities.configure_logger('default', '../logs/redis_script.log')

    try:
        log.info('Step 1: connect to Redis')
        r = login_database.login_redis_cloud()

        log.info('Step 2: Add customer data to the cache')
        r.hmset('Aaron', {'phone': '505-554-3729', 'zip': 11561})
        r.hmset('Blake', {'phone': '594-640-0741', 'zip': 17050})
        r.hmset('Charles', {'phone': '711-652-1354', 'zip': 16614})
        r.hmset('Denise', {'phone': '821-667-5095', 'zip': 30144})
        r.hmset('Edward', {'phone': '808-558-9987', 'zip': 46530})
        r.hmset('Frank', {'phone': '322-946-6274', 'zip': 28104})

        log.info('Step 3: Retrieve Blake\'s phone number')
        phone_blake = r.hmget('Blake', 'phone')
        log.info(f'Blake\'s phone number: {phone_blake}')

        log.info('Step 4: Retrieve Blake\'s zip code')
        zip_blake = r.hmget('Blake', 'zip')
        log.info(f'Blake\'s zip code: {zip_blake}')

    except Exception as e:
        print(f'Redis error: {e}')
Ejemplo n.º 15
0
 def get_donors(self):
     """Returns a dictionary of all donors and their donations."""
     donor_dict = {}
     r = login_database.login_redis_cloud()
     for donor in r.keys():
         donor_dict[donor] = [float(n) for n in r.lrange(donor, 0, -1)]
     return donor_dict
Ejemplo n.º 16
0
def run_example():
    """
        uses non-presistent Redis only (as a cache)

    """

    log = utilities.configure_logger('default', '../logs/redis_script.log')

    try:
        log.info('Step 1: connect to Redis')
        r = login_database.login_redis_cloud()

        log.info('Step 2: Add donor data to the cache')
        r.hmset('Aaron', {'phone': '505-554-3729', 'zip': 11561,
                          'donation': [20], 'email': '*****@*****.**'})
        r.hmset('Blake', {'phone': '594-640-0741', 'zip': 17050,
                          'donation': [20, 50], 'email': '*****@*****.**'})
        r.hmset('Charles', {'phone': '711-652-1354', 'zip': 16614,
                            'donation': [100], 'email': '*****@*****.**'})
        r.hmset('Denise', {'phone': '821-667-5095', 'zip': 30144,
                           'donation': [5], 'email': '*****@*****.**'})
        r.hmset('Edward', {'phone': '808-558-9987', 'zip': 46530,
                           'donation': [15], 'email': '*****@*****.**'})

    except Exception as e:
        print(f'Redis error: {e}')
Ejemplo n.º 17
0
def run_example():
    """
        uses non-presistent Redis only (as a cache)

    """

    log = utilities.configure_logger('default', '../logs/redis_script.log')

    try:
        log.info('Step 1: connect to Redis')
        r = login_database.login_redis_cloud()

        log.info('Step 2: cache some data in Redis')
        #r.set('andy', '*****@*****.**')

        r.rpush('customer1', 'sirisha', '206-111-1111', '98111')
        r.rpush('customer2', 'jessy', '206-222-2222', '98129')
        r.rpush('customer3', 'david', '206-333-3333', '98127')
        r.rpush('customer4', 'sam', '425-111-2222', '98052')
        r.rpush('customer5', 'alex', '425-222-3333', '98007')
        r.rpush('customer6', 'bill', '425-333-4444', '98006')

        print(f"Length of list for customer1 is: {r.llen('customer1')}")
        print(f"Database size: {r.dbsize()}")
        print(f"customer1 name:{r.lindex('customer1', 0)}")
        print(f"customer1 telephone: {r.lindex('zip',1)}")
        print(f"customer1 zip: {r.lindex('customer1', 2)}")

    except Exception as e:
        print(f'Redis error: {e}')
Ejemplo n.º 18
0
def run_example():
    """
        uses non-persistent Redis only (as a cache)

    """

    log = utilities.configure_logger('default', '../logs/redis_script.log')

    try:
        log.info('Step 1: connect to Redis')
        r = login_database.login_redis_cloud()
        log.info('Step 2: cache some data in Redis')
        r.set('test', '*****@*****.**')

        log.info('Step 2: adding some data to cache')
        r.hmset('Keith', {'phone': '425-123-4567', 'zip code': '91234'})
        r.hmset('Allison', {'phone': '206-987-6543', 'zip code': '94321'})
        r.hmset('Jesse', {'phone': '360-123-4567', 'zip code': '90101'})
        r.hmset('Lauren', {'phone': '425-606-6060', 'zip code': '96060'})
        r.hmset('John', {'phone': '206-206-2062', 'zip code': '92062'})
        r.hmset('Merlin', {'phone': '800-900-1000', 'zip code': '87654'})

        log.info('Step 3: return Merlin\'s zip code.')
        merlin_zip = r.hmget('Merlin', 'zip code')
        log.info(f'Merlin\'s zip code: {merlin_zip}')

        log.info('Step 4: return Merlin\'s phone number.')
        merlin_phone = r.hmget('Merlin', 'phone number')
        log.info(f'Merlin\'s phone number: {merlin_phone}')

    except Exception as e:
        print(f'Redis error: {e}')
Ejemplo n.º 19
0
def populate_donor_data():
    """
    Populate donor data
    """
    # Define our initial donor data
    try:
        log.info('login to redis')
        r = login_database.login_redis_cloud()

        log.info('Push the data to the database')
        r.rpush('Jimmy Nguyen', 'Houston')
        r.rpush('Jimmy Nguyen', '3784.49')

        r.rpush('Steve Smith', 'Seattle')
        r.rpush('Steve Smith', '933')

        r.rpush('Julia Norton', 'Portland')
        r.rpush('Julia Norton', '708.42')

        r.rpush('Ed Johnson', 'Atlanta')
        r.rpush('Ed Johnson', '16396.25')

        r.rpush('Elizabeth McBath', 'Austin')
        r.rpush('Elizabeth McBath', '16396.25')

    except Exception as e:
        log.info('Error in creating database with initial donors')
        log.info(e)
    finally:
        log.info('closed the database')
Ejemplo n.º 20
0
def run_example():
    """
        uses non-presistent Redis only (as a cache)

    """

    log = utilities.configure_logger('default', '../logs/redis_script.log')

    try:
        log.info('Step 1: connect to Redis')
        r = login_database.login_redis_cloud()
        log.info('Step 2: cache some data in Redis')
        # r.set('andy', '*****@*****.**')

        r.rpush('cust1', 'Albert', '206-555-1111', '98111')
        r.rpush('cust2', 'Bill', '206-555-2222', '98222')
        r.rpush('cust3', 'Charlie', '206-555-3333', '98333')
        r.rpush('cust4', 'David', '206-555-4444', '98444')
        r.rpush('cust5', 'Edward', '206-555-5555', '98555')
        r.rpush('cust6', 'Frank', '206-555-6666', '98666')

        print(f"Length of list for a customer: {r.llen('cust4')}")
        print(f"DBSize: {r.dbsize()}")
        print(f"Cust4 name: {r.lindex('cust4', 0)}")
        print(f"Cust4 zip: {r.lindex('cust4', 2)}")
        print(f"Cust4 phone: {r.lindex('cust4', 1)}")

        r.flushdb()

    except Exception as e:
        print(f'Redis error: {e}')
def run_example_activity():
    """
        uses non-presistent Redis only (as a cache)

    """

    log = utilities.configure_logger('default', '../logs/redis_script.log')

    try:
        log.info('Step 1: connect to Redis')
        r = login_database.login_redis_cloud()
        log.info('Step 2: Have Redis store a customer name, telephone and zip for 6 or so customers')
        r.rpush('andy', '111-111-1111', '11111')
        r.rpush('bonnie', '222-222-2222', '22222')
        r.rpush('camden', '333-333-3333', '33333')
        r.rpush('duke', '444-444-4444', '44444')
        r.rpush('ethridge', '555-555-5555', '55555')
        r.rpush('foster', '777-777-7777', '77777')

        log.info('Step 3: Then show how you can retrieve a zip code, and then a phone number, for a known customer')
        log.info(f'Andy Phone: {r.lindex("andy", 0)}')
        log.info(f'Camden Zip: {r.lindex("camden", 1)}')

    except Exception as e:
        print(f'Redis error: {e}')
 def get_donor_by_id(donor_id):
     try:
         db = login_database.login_redis_cloud()
         result = db.hgetall(donor_id)
         return result
     except Exception as e:
         log.info(e)
Ejemplo n.º 23
0
def run_exercise():
    """
    redis exercise

    Assignment:
    Add some customer data to the cache.
    Have Redis store a customer name, telephone and zip for 6 or so customers.
    Then show how you can retrieve a zip code, and then a phone number, for a known customer.
    """

    log = utilities.configure_logger('default', '../logs/redis_script.log')

    try:
        log.info('Step 1: connect to Redis')
        r = login_database.login_redis_cloud()

        log.info('Step 2: cache customer data in Redis')
        r.rpush('Mark', '808-555-1234', '96825')
        r.rpush('Roger', '717-123-4567', '17331')
        r.rpush('Tom', '425-222-1234', '98275')
        r.rpush('Mimi', '206-999-9999', '98101')
        r.rpush('Maureen', '212-867-5309', '10002')
        r.rpush('Joanne', '617-542-3779', '02114')

        log.info('Step 3: read customer info')
        log.info(f"Roger's phone number is {r.lindex('Roger',2)}, and his zipcode is {r.lindex('Roger', 1)}.")
        log.info(f"Mark's phone number is {r.lindex('Mark',2)}, and his zipcode is {r.lindex('Mark', 1)}.")

    except Exception as e:
        print(f'Redis error: {e}')
 def get_donor_by_last(last_name):
     try:
         db = login_database.login_redis_cloud()
         result = db.hgetall(last_name)
         return result
     except Exception as e:
         log.info(e)
    def update_cache(self):
        try:
            db = login_database.login_redis_cloud()
            qm = QueriesMongo()  # noqa F403
            dl = qm.get_donors()
            self.flush_cache()

            # format for redis
            nl = []
            for d in dl:
                nl.append([str(d['_id']), {
                    '_id': str(d['_id']),
                    'first_name': d['first_name'],
                    'last_name': d['last_name'],
                    'email': d['email'],
                    'phone': d['phone'],
                    'zip_code': d['zip_code'],
                    'donations': d['donations']
                }])

            # set each donor
            for key, data in nl:
                db.hmset(key, data)

        except Exception as e:
            log.info(e)
class TestRedis(unittest.TestCase):
    # connect to database
    r = login_database.login_redis_cloud()
    # Populate the Redis database
    Load_Tables.populate_redis(r)

    def test_Exists(self):
        """ Test to see if your donor exists in database"""
        result = self.__class__.r.exists('Zach')
        self.assertEqual(result, 1)

        # Test to see if your donor does NOT exist in database
        result = self.__class__.r.exists('John')
        self.assertEqual(result, 0)

    def test_Get_CheckEntry(self):
        """Test that when the database loads,
        first it deletes existing entries"""
        result = self.__class__.r.llen('Zach')
        self.assertEqual(result, 3)

    def test_Get_Email(self):
        """Test that we can collect the email from Zach"""
        result = self.__class__.r.lindex('Zach', 2)
        self.assertEqual(result, '*****@*****.**')

    def test_donor_verification(self):
        """Test that we can confirm donor information in Redis"""
        Load_Tables.populate_redis(self.__class__.r)
        result = d.Individual.donor_verification(self.__class__.r, 'Joe')
        self.assertEqual(result, ['Slinger', '677-0182', '*****@*****.**'])

    def test_update_last_name(self):
        """Test that we can confirm donor information in Redis"""
        Load_Tables.populate_redis(self.__class__.r)
        result = d.Individual.update_last_name(self.__class__.r, 'Joe',
                                               'Sling')
        self.assertEqual(result, ['Sling', '677-0182', '*****@*****.**'])

    def test_update_telephone(self):
        """Test that we can confirm donor information in Redis"""
        Load_Tables.populate_redis(self.__class__.r)
        result = d.Individual.update_telephone(self.__class__.r, 'Joe',
                                               '312-000-0000')
        self.assertEqual(result, ['Slinger', '312-000-0000', '*****@*****.**'])

    def test_update_email(self):
        """Test that we can confirm donor information in Redis"""
        Load_Tables.populate_redis(self.__class__.r)
        result = d.Individual.update_email(self.__class__.r, 'Joe',
                                           '*****@*****.**')
        self.assertEqual(result, ['Slinger', '677-0182', '*****@*****.**'])

    def test_redis_add_new(self):
        """Test that we can confirm donor information in Redis"""
        result = d.Individual.redis_add_new(self.__class__.r, 'Sally', 'Hines',
                                            '847-987-4567',
                                            '*****@*****.**')
        self.assertEqual(result,
                         ['Hines', '847-987-4567', '*****@*****.**'])
Ejemplo n.º 27
0
def get_donors_data():
    """
    current donors
    :return:
    """
    donors = [{
        "donor_name": "Jerry Seinfeld",
        'donations': [100.0, 200.0, 199.1]
    }, {
        "donor_name": "George Constanza",
        'donations': [22.0, 300.0, 24.1]
    }, {
        "donor_name": "Elaine Bennis",
        'donations': [11.0, 2.1, 66.1]
    }, {
        "donor_name": "Cosmo Kramer",
        'donations': [0.11, 0.21, 0.3]
    }, {
        "donor_name": "Newman",
        'donations': [20.0, 11.0, 5.13]
    }]
    donors_json = json.dumps(donors)
    log.info('JSON of donors: {}'.format(donors_json))
    r = login_database.login_redis_cloud()
    # setting users and emails
    r.set('donors', donors_json)
Ejemplo n.º 28
0
def run_example():
    """
        uses non-presistent Redis only (as a cache)

    """

    log = utilities.configure_logger('default', '../logs/redis_script.log')

    try:
        log.info('Step 1: connect to Redis')
        r = login_database.login_redis_cloud()
        log.info('Step 2: cache some data in Redis')
        r.rpush('0001', 'andy', '123-456-4444', '12345')
        r.rpush('0002', 'brad', '123-456-5555', '23456')
        r.rpush('0003', 'cory', '123-456-6666', '34567')
        r.rpush('0004', 'diane', '123-456-7777', '45678')
        r.rpush('0005', 'ellen', '123-456-8888', '56789')
        r.rpush('0006', 'felicity', '123-456-9999'. '67891')

        # log.info('Step 2: now I can read it')
        # email = r.get('andy')
        # log.info('But I must know the key')
        # log.info(f'The results of r.get: {email}')

        # log.info('Step 3: cache more data in Redis')
        # r.set('pam', '*****@*****.**')
        # r.set('fred', '*****@*****.**')

        # log.info('Step 4: delete from cache')
        # r.delete('andy')
        # log.info(f'r.delete means andy is now: {email}')

        # log.info(
        #     'Step 6: Redis can maintain a unique ID or count very efficiently')
        # r.set('user_count', 21)
        # r.incr('user_count')
        # r.incr('user_count')
        # r.decr('user_count')
        # result = r.get('user_count')
        # log.info('I could use this to generate unique ids')
        # log.info(f'Redis says 21+1+1-1={result}')

        # log.info('Step 7: richer data for a SKU')
        # r.rpush('186675', 'chair')
        # r.rpush('186675', 'red')
        # r.rpush('186675', 'leather')
        # r.rpush('186675', '5.99')

        # log.info('Step 8: pull some data from the structure')
        # cover_type = r.lindex('186675', 2)
        # log.info(f'Type of cover = {cover_type}')

        log.info('Step 2: Retrieve data for cust 0006')
        log.info(f'Zip code for cust 0006: {r.lindex('0006', 2)}')
        log.info(f'Phone number for cust 0006: {r.lindex('0006', 1)}')


    except Exception as e:
        print(f'Redis error: {e}')
 def donations_count(d):
     try:
         db = login_database.login_redis_cloud()
         result = db.hgetall(str(d['_id']))
         count = ast.literal_eval(result['donations'])
         return len(count)
     except Exception as e:
         log.info(e)
 def donations_total(d):
     try:
         db = login_database.login_redis_cloud()
         result = db.hgetall(str(d['_id']))
         totals = ast.literal_eval(result['donations'])
         return sum(totals)
     except Exception as e:
         log.info(e)