I've been trying for some days to connect my python 3 script to PostgresSQL database(psycopg2
) in Heroku, without Django.
I found some article and related questions, but I had to invest a lot of time to get something that I thought should be very straightforward, even for a newbie like me.
I eventually made it work somehow but hopefully posting the question (and answer) will help other people to achieve it faster.
Of course, if anybody has a better way, please share it.
As I said, I had a python script that I wanted to make it run from the cloud using Heroku. No Django involved (just a script/scraper).
Articles that I found helpful at the beginning, even if they were not enough:
You can do it using the SQLALCHEMY library. First, you need to install the SQLALCHEMY library using pip, if you don't have pip on your computer install, you will know-how using a simple google search
Here is the code snippet that do what you want:
Main steps:
1. Procfile
Procfile
has to be:2. Heroku add-on
Add-on
Heroku Postgres :: Database
has to be added to the appropriate personal app in the heroku account.To make sure this was properly set, this was quite helpful.
3. Python script with db connection
Finally, to create the connection in my python script
myscript.py
, I took this article as a reference and adapted it to Python 3:To create a new database, this SO question explains it. Key line is: