Forums

Need help connecting to Postgres Server with SQLAlchemy

I'm trying to connect to my postgres server on PythonAnywhere from a flask app i'm making. Right now i've created a db on the server and have it running and have the following in my app:

app.config["SQLALCHEMY_DATABASE_URI"] = 'postgresql+psycopg2://<username>:<password>@<host>:<port>/<dbname>'
db = SQLAlchemy(app)

with all the values in <> filled out correctly. Yet when I try and go db.create_all() the server times out and i receive the error:

sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) could not connect to server: Operation timed out

Any help would be appreciated!

You have a free account, so there is no way you can have a Postgres server on PythonAnywhere. They are only available on paid accounts.

Should have clarified, I'm using a different (paid) account that does indeed have a Postgres server running. Thats the account Im getting all the <> values from.

Which account is it? And can I take a look at the code? We can see your code from our admin interface, but we always ask for permission first.

The account is authenticsclub, and the code for the app is just running on my computer right now. Does it have to be running on the PA server for that URI to work? Excuse my ignorance, this is my first time deploying a web app!

Ah yes, that would explain it -- the Postgres server is only accessible directly from inside PythonAnywhere.

It is possible to set up an SSH tunnel on your own machine that will allow access; basically, you run a program that looks (to other programs on your machine) like it's a Postgres server, but actually connects to PythonAnywhere over SSH and then connects from there to your Postgres instance, and passes messages back and forth. If you'd like to set that up, let me know what operating system you're using on your own machine and I can give you some details.

Alternatively, you could just move the code up to PythonAnywhere and run it there.