I can't offer much assistance with this apart form saying that doing this in Python was perhaps the wrong thing to do. You can't use any of the built-in WordPress functions, and you can't use the built-in $wpdb
object for database interaction. If it was me, I'd build it the correct way - in PHP, connected to the WordPress functions, and using the WordPress functions. That way you'll get the script to do what you want it to.
Looking at the code above I don't like the queries. I've always been taught that you should not use double-quotes inside SQL strings. That might just be my own ideas, but it could also be causing some issues. Without knowing Python, I can't say much though.