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.