0

I have a python function that connects to Azure Postgresql and selects query some rows. In local run without problem. When I published on Azure and run it I received the below error:

OperationalError: (psycopg2.OperationalError) could not translate host name "Mypassword@database_ip" to address

enter image description here

I don't know why to change connection format to db_password@db_ip, as you see on screenshot.

My function is:

def get_engine(database='db_name', username='username', password='@password', host='ip', port=5432):
    engine_string = f"postgresql+psycopg2://{username}:{password}@{host}:{port}/{database}"
    engine = sqlalchemy.create_engine(engine_string)
    print("Database connection done!")
    return engine
Shadi
  • 193
  • 2
  • 12
  • On line after `engine_string = ...` do `print(engine_string)` to see what you are actually building. Post result as update to your question. – Adrian Klaver Jun 09 '21 at 21:16

2 Answers2

2

Rather than using plain string formatting you can use engine.URL.create to protect yourself against "special characters" in the username, password, etc.:

import sqlalchemy as sa

# …

url = sa.engine.URL.create(
    drivername="postgresql+psycopg2",
    username="username",
    password="@password",
    host="ip",
    port=5432,
    database="database",
)
print(url)  # postgresql+psycopg2://username:%40password@ip:5432/database
engine = sa.create_engine(url)
``
Gord Thompson
  • 116,920
  • 32
  • 215
  • 418
0

The literal @ in your password needs to be URI encoded.

jjanes
  • 37,812
  • 5
  • 27
  • 34