etc

DB 접속 시 패스워드에 @ 가 포함되어 있을때 발생하는 오류!! 해결방법

JavaPark 2021. 8. 25. 12:24

현상 및 조치

로컬에서 flask_svc 수행 시 다음과 같은 오류를 본 적이 있는가?

could not translate host name "#@localhost" to address: Unknown server error

DB 접속하는 URL 을 보자. DB_PASS 의 값에 ~@#라는 특수문자가 있을 경우 패스워드를 @ 앞에서 자르고 Host 를 #@localhost로 해석하는 경우이다

    SQLALCHEMY_DATABASE_URI = "postgresql+pygresql://{DB_USER}:{DB_PASS}@{DB_HOST}:{DB_PORT}/{DB_NAME}".format(
        DB_USER=pg_db_username,
        DB_PASS=pg_db_password,
        DB_HOST=pg_db_host,
        DB_PORT=pg_db_port,
        DB_NAME=pg_db_name)

물론 해결방법이 있다. urllib.parse.quote 를 이용하여 DB_PASS 처리 시 문제 없이 돌아가는 것을 확인할 수 있다

    from urllib.parse import quote  

    SQLALCHEMY_DATABASE_URI = "postgresql+pygresql://{DB_USER}:%s@{DB_HOST}:{DB_PORT}/{DB_NAME}".format(
        DB_USER=pg_db_username,
        DB_HOST=pg_db_host,
        DB_PORT=pg_db_port,
        DB_NAME=pg_db_name) % quote(pg_db_password)

print 를 통해 출력해보면 %40%23@localhost 로 바뀌어서 처리된것을 확인할 수 있다

Ref