Postgresql While Loop Exit Python Code