In a redis db I gotta save two things, 2. the hash of a question, then a list of hashes…
- User
In a redis db I gotta save two things, 2. the hash of a question, then a list of hashes of answers to those questions. How should i implement this in python so i can search for a question, then get a list of answers. The whole system works only on hashes so the code does not need any example questions just placeholder hashes. Make functions for adding a question with a starting answer, to add a new answer to a question, and to add a question with a blank answer
- Assistant
To implement this in Python using Redis, you can make use of the
redispackage. Here's an example implementation:import redis class RedisQuestionAnswer: def __init__(self, host='localhost', port=6379, db=0): self.redis_db = redis.Redis(host=host, port=port, db=db) def add_question_with_answer(self, question_hash, answer_hash): self.redis_db.hset('questions', question_hash, answer_hash) self.redis_db.lpush(f'answers:{question_hash}', answer_hash) def add_answer_to_question(self, question_hash, answer_hash): self.redis_db.lpush(f'answers:{question_hash}', answer_hash) def add_question_with_blank_answer(self, question_hash): self.redis_db.hset('questions', question_hash, '') def search_question_answers(self, question_hash): answer_hashes = self.redis_db.lrange(f'answers:{question_hash}', 0, -1) answers = [] for answer_hash in answer_hashes: answer = self.redis_db.get(answer_hash) if answer: answers.append(answer.decode('utf-8')) return answers # Example usage question_answer = RedisQuestionAnswer() # Add a question with a starting answer question_hash = 'question_hash' answer_hash = 'answer_hash' question_answer.add_question_with_answer(question_hash, answer_hash) # Add a new answer to a question new_answer_hash = 'new_answer_hash' question_answer.add_answer_to_question(question_hash, new_answer_hash) # Add a question with a blank answer blank_question_hash = 'blank_question_hash' question_answer.add_question_with_blank_answer(blank_question_hash) # Search for a question and retrieve the answers found_answers = question_answer.search_question_answers(question_hash) print(found_answers)