我正在按照 youtube 教程 使用 FastAPI 创建 API。我对 Docker 和 FastAPI 都是新手。我已成功使用此 Dockerfile 和 docker-compose 为 API 创建了一个 Docker 容器,并为 Postgres 数据库创建了另一个容器:
Dockerfile:
FROM python:3.9.7
WORKDIR /usr/src/app
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
docker-compose:
version: '3'
services:
api:
build: .
depends_on:
- postgres
ports:
- 80:8000
volumes:
- ./:/usr/src/app.ro
env_file:
- ./.env
command: bash -c "uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload"
postgres:
image: postgres
ports:
- 5432:5432
env_file:
- ./.env
volumes:
- postgres-db:/var/lib/posgresql/data
volumes:
postgres-db:
我也在使用 Alembic,所以在设置两个容器后,我运行
docker-compose run api alembic upgrade head
以便创建相应的表。
使用 Postman 进行测试时,一切运行顺利。我可以运行与数据库交互的 GET 和 POST 查询,这没有问题。当尝试使用 FastAPI 中的 TestClient 测试 API 代码时,就会出现问题。我正在运行两个测试:
from fastapi.testclient import TestClient
from app.main import app
client = TestClient(app)
def test_root():
response = client.get("/")
assert response.json().get('message') == "Welcome to my API"
assert response.status_code == 200
def test_create_user():
response = client.post("/users/", json = {"email": "[email protected]", "password": "test"})
assert response.status_code == 201
第一个通过,没有问题,但第二个失败,并显示以下错误消息:
FAILED tests/test_users.py::test_create_user - sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) could not translate host name "postgres" to address: nodename nor servname provided, or not known
我不知道我做错了什么。由于使用Postman测试时没有问题,所以我不确定是否需要设置任何配置才能使用TestClient。
有人可以帮助我吗?
您应该安装 pytest-env 并添加具有以下配置的 pytest.ini:
[py测试] 环境= DB_URL=postgresql+psycopg2://用户:pass@localhost/dbname
请将 DB_URL(环境变量名称)、user、pass 和 dbname 更改为您的实际值。