Forums

Cannot Write Postgres Database Even Though I Can Connect Remotely

I don't understand what I'm doing wrong here.

I can connect to my database using Python in VS Code with the following script (yes, I have a paid account and all of that, and I'm sorry if the formatting gets messed up below).

from sqlalchemy import create_engine, Column, Integer, String, DateTime, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.orm import declarative_base
from sqlalchemy.orm import sessionmaker
from datetime import datetime
from flask_login import UserMixin
import hashlib
import psycopg2
import sshtunnel

sshtunnel.SSH_TIMEOUT = 5.0
sshtunnel.TUNNEL_TIMEOUT = 5.0

postgres_hostname = "ASSIGNED_URL_PREFIX.postgres.pythonanywhere-services.com" 
postgres_host_port = ASSIGNED_PORT

with sshtunnel.SSHTunnelForwarder(
        ('ssh.pythonanywhere.com'),
        ssh_username='ACCOUNT_USERNAME',
        ssh_password='ACCOUNT_PASSWORD',
        remote_bind_address=(postgres_hostname, postgres_host_port)
) as tunnel:
    connection = psycopg2.connect(
        user='DB_USERNAME', password='DB_PASSWORD',
        host='HOST', port=tunnel.local_bind_port,
        database='DB_NAME',
    )
    # Do stuff inside the context manager block

    connection.close()

But when I try to involve SQLAlchemy, everything goes downhill.

...same imports...

sshtunnel.SSH_TIMEOUT = 5.0
sshtunnel.TUNNEL_TIMEOUT = 5.0

postgres_hostname = "ASSIGNED_URL_PREFIX.postgres.pythonanywhere-services.com"
postgres_host_port = ASSIGNED_PORT

with sshtunnel.SSHTunnelForwarder(
        ('ssh.pythonanywhere.com'),
        ssh_username='ACCOUNT_USERNAME,
        ssh_password='ACCOUNT_PASSWORD',
        remote_bind_address=(postgres_hostname, postgres_host_port)
) as tunnel:
    # PostgreSQL connection through the tunnel
    connection = psycopg2.connect(
        user='DB_USERNAME', password='DB_PASSWORD',
        host='ASSIGNED_HOST', port=tunnel.local_bind_port,
        database='DB_NAME',
    )

    # Create SQLAlchemy engine
    db_url = f"postgresql+psycopg2://DB_USERNAME:DB_PASSWORD@ASSIGNED_URL_PREFIX.postgres.pythonanywhere-services.com:ASSIGNED_PORT/DB_NAME"
    engine = create_engine(db_url)

    # Define Base and models
    Base = declarative_base() .... the rest of my script ....

It clearly has something to do with the db_url, but I can't figure out how to fix it:

postgresql+psycopg2://DB_USERNAME:DB_PASSWORD@ASSIGNED_URL_PREFIX.postgres.pythonanywhere-services.com:ASSIGNED_PORT/DB_NAME

Here's the error I get:

sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) could not translate host name "ASSIGNED_URL_PREFIX.postgres.pythonanywhere-services.com" to address: nodename nor servname provided, or not known

Please help.

I've tried everything, and I'm pulling my hair out!

From the poin tof view of your SQLAlchemy you need to connect to your localhost not to ASSIGNED_URL_PREFIX.postgres.pythonanywhere-services.com

I've tried that (assuming this URL is correct):

   # Create SQLAlchemy engine
    db_url = f"postgresql+psycopg2://DB_USERNAME:DB_PASSWORD@LOCALHOST:LOCALPORT/DB_NAME"
    engine = create_engine(db_url)

I receive this error:

sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) connection to server failed: FATAL:  role "DB_USERNAME" does not exist

I've also tried this URL:

 # Create SQLAlchemy engine
    db_url = f"postgresql+psycopg2://DB_USERNAME:DB_PASSWORD@LOCALHOST:{tunnel.local_bind_port}/DB_NAME"
    engine = create_engine(db_url)

And I get this error:

sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) connection to server failed: Connection refused
        Is the server running on that host and accepting TCP/IP connections?

That last option looks pretty much right; are you using '127.0.0.1' where you have "LOCALHOST" in there?

That's correct. I should note that the port seems to change every time I run it.

Did you mean to be interpolating the username and password in the string db_url = f"postgresql+psycopg2://DB_USERNAME:DB_PASSWORD@LOCALHOST:{tunnel.local_bind_port}/DB_NAME"

The only thing interpolated is {tunnel.local_bind_port}, so no, I'm just hiding my username and password for security reasons.

I've also tried this, and I have the same problem:

# Create SQLAlchemy engine
db_url = "postgresql+psycopg2://DB_USERNAME:DB_PASSWORD@127.0.0.1:{}/tfftt".format(local_bind_port)
engine = create_engine(db_url)

I also read on another forum that sometimes you guys have to reset the server....

I ran each operation one by one, and that worked, so maybe creating tables all at once overloaded the server. I'm not sure, but I'm just glad it's working now.

Glad you got that working!