Skip to content

Instantly share code, notes, and snippets.

@sripathikrishnan
Created February 21, 2018 03:49
Show Gist options
  • Select an option

  • Save sripathikrishnan/e71f7e2aa0c9ce415694ccb2c7473af6 to your computer and use it in GitHub Desktop.

Select an option

Save sripathikrishnan/e71f7e2aa0c9ce415694ccb2c7473af6 to your computer and use it in GitHub Desktop.
A simple python script to experiment with redis
from __future__ import print_function
from redis import StrictRedis, ConnectionError
import pprint
pp = pprint.PrettyPrinter(indent=4)
def get_connection():
# This is the object we will use to connect to redis server
# You can pass host, port and password to StrictRedis...
# ... but for this assigment, we will stick to defaults
# so that it connects to redis server on localhost:6379
return StrictRedis()
def test_connection(red):
try:
red.ping()
print("Successfully connected to redis server")
print("")
except ConnectionError as ce:
print("CANNOT connect to redis. Make sure you have installed redis and have started it")
print("")
raise
def get_question_details(red, questionid):
# red object has methods for all the redis commands
# here, we are using the hgetall command
# to get all field=value pairs for a particular question
#
# question is a standard python dict
question = red.hgetall("questions:%s" % questionid)
# we use pp.pprint to make the output easy to understand
# you can replace this with print(question), but the output
# will be a bit more difficult to understand
# In real world, this function will return the question object
# instead of printing it
print("Assignment #1: Get Question Details")
print("-----------------------------------")
pp.pprint(question)
print()
def main():
# create a connnection to redis server and test it
red = get_connection()
test_connection(red)
# this is the first assignment, solved for you
# from here on, create a new function for every assignment
get_question_details(red, 694)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment