[Tutor] get key value from Redis instance

Steven D'Aprano steve at pearwood.info
Sun May 27 19:40:57 EDT 2018


On Sun, May 27, 2018 at 08:31:26PM +0200, Silviu Chiric wrote:

> try:
>     conn = redis.StrictRedis( host='
> redis-15838.c44.us-east-1-2.ec2.cloud.redislabs.com', port=15838,
> password='DavidLavinia2')

You just shared your password with the entire world.


>     print (conn)
>     conn.ping()
>     print ('Connected!')
> print 'Set Record:', conn.set("best_car_ever", "Tesla Model S")
>     print 'Get Record:', conn.get("best_car_ever")
>     print 'Delete Record:', conn.delete("best_car_ever")
>     print 'Get Deleted Record:', conn.get("best_car_ever")
> except Exception as ex:
>         print ('Error:', ex)
>         exit('Failed to connect, terminating.')


Get rid of the try...except block. It is evil.

If a problem occurs, it could happen in any one of twelve operations. 
Six of them are calls to print, so they are probably okay, but the other 
six are complex operations that could go wrong for a billion different 
reasons.

Nevertheless, whatever the *real* reason the code fails, your 
try...except block catches the exception, strips out the useful 
traceback which is indispensible for debugging, and prints a LIE that 
you failed to connect. You didn't fail to connect, as you can see: the 
connection was successfully made.

Don't let your code lie to you. Debugging is hard. When your program 
deliberately strips away the useful traceback information showing which 
line failed, and then lies about the error that occurred, it becomes 
nearly impossible.

(1) Change your password. Immediately.

(2) Remove the try...except block.

(3) When an error occurs, the interpreter will print a full traceback 
showing which line failed as well as the failure type and error message, 
and then exit. There is no need for you to catch the exception and then 
exit yourself.

(4) COPY AND PASTE (don't summarise it, don't retype it from memory) the 
ENTIRE traceback and post it for us to see.


We can't debug a problem we can't see.



-- 
Steve


More information about the Tutor mailing list