getting this error in my pyhon code psycopg2.OperationalError: fe_sendauth: no password supplied

huangapple go评论68阅读模式
英文:

getting this error in my pyhon code psycopg2.OperationalError: fe_sendauth: no password supplied

问题

I try to run python app with docker-compose and the app using postgres as container, but when i run docker-compose up the Database run successfully but the app allways getting error "psycopg2.OperationalError: fe_sendauth: no password supplied".

The setting of the postgres using a init.sql file that i've been created and copy to the container in a directory that run this file automatically.

import psycopg2
import psycopg2.extras
import os
from dotenv import load_dotenv

dotenv_path = os.path.join(os.path.dirname(__file__), '..', '.env')
load_dotenv(dotenv_path)

db_username = os.environ.get('POSTGRES_USER')
db_password = os.environ.get('POSTGRES_PASSWORD')
postgres_port = os.environ.get('POSTGRES_PORT')
database_name = os.environ.get('POSTGRES_DB')

# Connect to the PostgreSQL database
conn = psycopg2.connect(
    host="db",
    port=postgres_port,
    database=database_name,
    user=db_username,
    password=db_password    
)

# get the data from the DB in json format
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)

# select data from DB
def get_data(query):
    try:
        cur.execute(query)
        data = cur.fetchall()
        return data
    except Exception as error:
        print(error)
        
# update the DB        
def set_data(query):
    try:
        cur.execute(query)
        conn.commit()
        return "Database was updated"
    except Exception as error:
        print(error)
version: "3.8"
services:
  db:
    build: ./database/
    container_name: todo-db
    environment:
      POSTGRES_USER: ${POSTGRES_USER}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
      POSTGRES_DB: ${POSTGRES_DB}
    restart: always
    ports:
      - 5432:5432
    volumes:
      - ./database/data:/var/lib/postgresql/data
    
  app :
    build: ./app/
    container_name: todo-app
    ports: 
      - 8002:8000
    links:
      - db
    depends_on:
      - db  

  pgadmin:
    container_name: pgadmin4_container
    image: dpage/pgadmin4
    restart: always
    environment:
      PGADMIN_DEFAULT_EMAIL: ${PGADMIN_EMAIL}
      PGADMIN_DEFAULT_PASSWORD: ${PGADMIN_PASSWORD}
    ports:
      - "5050:80"

Dockerfile of the python app:

FROM python:3.9

WORKDIR /code

COPY ./requirements.txt /code/requirements.txt

RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt

COPY . /code

CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

Dockerfile of the postgres DB:

FROM postgres:latest

WORKDIR /app

COPY init.sql /docker-entrypoint-initdb.d/init.sql

EXPOSE 5432

CMD [ "postgres" ]

init.sql file:

CREATE USER IF NOT EXISTS todo_user WITH PASSWORD '${POSTGRES_PASSWORD}';

CREATE DATABASE todo_db WITH OWNER todo_user;

GRANT ALL PRIVILEGES ON DATABASE todo_db TO todo_user;

\c todo_db todo_user;

CREATE TABLE tasks(
   id SERIAL PRIMARY KEY,
   task VARCHAR NOT NULL,
   ststus VARCHAR NOT NULL
);

.env file:

POSTGRES_USER = todo_user
POSTGRES_PASSWORD = Aa123456
POSTGRES_DB = todo_db
POSTGRES_PORT = 5432

I tried in the connection string in the app to set the default username and password of postgres database and it's working i successfully connect to database but when i use variable from .env file i'm getting the error.

In the postgres container i can see that the user and the DB created.

英文:

I try to run python app with docker-compose and the app using postgres as container, but when i run docker-compose up the Database run successfully but the app allways getting error "psycopg2.OperationalError: fe_sendauth: no password supplied".

The setting of the postgres using a init.sql file that i've been created and copy to the container in a directory that run this file automatically.

======================== connection to DB file ========================

import psycopg2
import psycopg2.extras
import os
from dotenv import load_dotenv

dotenv_path = os.path.join(os.path.dirname(__file__), '..', '.env')
load_dotenv(dotenv_path)

db_username = os.environ.get('POSTGRES_USER')
db_password = os.environ.get('POSTGRES_PASSWORD')
postgres_port = os.environ.get('POSTGRES_PORT')
database_name = os.environ.get('POSTGRES_DB')
# postgres_host = os.environ.get('POSTGRES_HOST')

print (database_name)

# Connect to the PostgreSQL database
conn = psycopg2.connect(
    host="db",
    port=postgres_port,
    database=database_name,
    user=db_username,
    password=db_password    
)

# get the data from the DB in json format
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)

# select data from DB
def get_data(query):
    try:

        # Run the query and fetch the results
        cur.execute(query)
        data = cur.fetchall()
        return data
    except Exception as error:
        print(error)
        
# update the DB        
def set_data(query):
    try:
        # Run the query and fetch the results
        cur.execute(query)
        conn.commit()
        return "Database was updated"
    except Exception as error:
        print(error)

===================== docker-compose file =====================

version: "3.8"
services:
  db:
    build: ./database/
    container_name: todo-db
    environment:
      POSTGRES_USER: ${POSTGRES_USER}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
      POSTGRES_DB: ${POSTGRES_DB}
    restart: always
    ports:
      - 5432:5432
    volumes:
      - ./database/data:/var/lib/postgresql/data
      # - ./database/init.sql:/docker-entrypoint-initdb.d/init.sql
    # env_file:
    #   - ../TODO-App/.env
    
  app :
    build: ./app/
    container_name: todo-app
    ports: 
      - 8002:8000
    links:
      - db
    depends_on:
      - db  

  pgadmin:
    container_name: pgadmin4_container
    image: dpage/pgadmin4
    restart: always
    environment:
      PGADMIN_DEFAULT_EMAIL: ${PGADMIN_EMAIL}
      PGADMIN_DEFAULT_PASSWORD: ${PGADMIN_PASSWORD}
    ports:
      - "5050:80"

============================== Dockerfile of the python app ==============================

FROM python:3.9

# 
WORKDIR /code

# 
COPY ./requirements.txt /code/requirements.txt

# 
RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt

# 
COPY . /code

# 
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

=============================== Dockerfile of the postgres DB ===============================

FROM postgres:latest

WORKDIR /app

COPY init.sql /docker-entrypoint-initdb.d/init.sql

EXPOSE 5432

CMD [ "postgres" ]

============== init.sql file ==============

CREATE USER IF NOT EXISTS todo_user WITH PASSWORD '${POSTGRES_PASSWORD}';

CREATE DATABASE todo_db WITH OWNER todo_user;

GRANT ALL PRIVILEGES ON DATABASE todo_db TO todo_user;

\c todo_db todo_user;

CREATE TABLE tasks(
   id SERIAL PRIMARY KEY,
   task VARCHAR NOT NULL,
   ststus VARCHAR NOT NULL
);

=========== .env file ===========

POSTGRES_USER = todo_user
POSTGRES_PASSWORD = Aa123456
POSTGRES_DB = todo_db
POSTGRES_PORT = 5432

I tried in the connection string in the app to set the default username and password of postgres database and it's working i successfully connect to database but when i use variable from .env file i'm getting the error.

In the postgres coantainer i can see that the user and the DB created.

答案1

得分: 0

看起来你只在"db"容器中使用环境变量,而没有在"app"容器中使用。

假设你的用于获取环境变量的Python代码有效,将envvars 添加到你的应用容器中:

app:
  build: ./app/
  container_name: todo-app
  environment:
    POSTGRES_USER: ${POSTGRES_USER}
    POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
    POSTGRES_DB: ${POSTGRES_DB}
  ports: 
    - 8002:8000
  links:
    - db
  depends_on:
    - db
英文:

Looks like you're only using environment variables for your "db" container, but not for the "app" container.

Provided that your python code for getting environment variables works, add envvars to your app container:

  app:
    build: ./app/
    container_name: todo-app
    environment:
      POSTGRES_USER: ${POSTGRES_USER}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
      POSTGRES_DB: ${POSTGRES_DB}
    ports: 
      - 8002:8000
    links:
      - db
    depends_on:
      - db  

huangapple
  • 本文由 发表于 2023年3月31日 22:46:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/75899863.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定