Search code examples
pythonangularflasksqlalchemypsycopg2

sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) could not translate host name to address: Unknown server error


while doing this tutorial: https://auth0.com/blog/using-python-flask-and-angular-to-build-modern-apps-part-1/

I bumped on an error that wasn't described anywhere on Stack.

The problematic code:

from datetime import datetime
from sqlalchemy import create_engine, Column, String, Integer, DateTime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

db_url = 'localhost:5432'
db_name = 'FLASK_ANGULAR'
db_user = 'postgres'
db_password = 'Password@22'
engine = create_engine(f'postgresql://{db_user}:{db_password}@{db_url}/{db_name}')
Session = sessionmaker(bind=engine)

Base = declarative_base()


class Entity():
    id = Column(Integer, primary_key=True)
    created_at = Column(DateTime)
    updated_at = Column(DateTime)
    last_updated_by = Column(String)

    def __init__(self, created_by):
        self.created_at = datetime.now()
        self.updated_at = datetime.now()
        self.last_updated_by = created_by

Solution

  • The problem was with this line of code:

    engine = create_engine(f'postgresql://{db_user}:{db_password}@{db_url}/{db_name}')
    

    and the password:

    db_password = 'Password@22'
    

    The password contains '@' which python interpreted as a prompt to start parsing the db_url address.

    The solution was to change the password to the one that does not contain the special symbols. If you encounter a similar error, please check if your password or any other element of the engine formula contains special symbols that might be misinterpreted by Python while connecting to your database.

    To successfully change the password in PostgreSQL (pgAdmin 4):

    1. enter your server
    2. click on the database
    3. From Tools in the top-menu choose Query Tool
    4. Use the command: ALTER USER your_username PASSWORD 'NewPasswordWithoutSpecialSymbols'
    5. Press Execute/Refresh just above the command line (a button with Play or Ligthning symbol on it)
    6. Disconnect your PostrgeSQL from the server (right click in the right column)
    7. Reconnect