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
1
  • On line after engine_string = ... do print(engine_string) to see what you are actually building. Post result as update to your question. Commented Jun 9, 2021 at 21:16

2 Answers 2

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)
``
Sign up to request clarification or add additional context in comments.

1 Comment

I think that this would be really useful to have in the linked dupe target as well.
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.