Pycharm 使用 FastApi 和 docker 组合的调试器设置

Pycharm debugger setup with FastApi and docker compose

我很难通过 docker-compose fastAPI 设置 Pycharm 附加调试器

docker-撰写

    version: '3.8'

services:
  api:
    build: .
    volumes:
      - .:/app
    ports:
      - "8080:80"
    environment:
      - DATABASE_URL=postgresql://test_user:test_pwd@db:5432/test_db
    depends_on:
      - db
  
  db:
    image: postgres:13-alpine
    volumes:
      - postgres_data:/var/lib/postgres/data/
    ports:
      - "5432:5432"
    environment:
      - POSTGRES_USER=test_user
      - POSTGRES_PASSWORD=test_pwd
      - POSTGRES_DB=test_db

volumes:
  postgres_data:

docker文件:

FROM tiangolo/uvicorn-gunicorn:python3.9

COPY requirements.txt /tmp/requirements.txt
RUN pip install --no-cache-dir -r /tmp/requirements.txt

COPY ./app /app/app

CMD [ "/start-reload.sh" ]

我已经为 docker-compose 在 pycharm 中设置了一个远程解释器 当我启动应用程序时它工作但断点不

我尝试设置 python 配置:

应用程序启动但断点没有启动

如果您有什么建议? 谢谢

这对我有用(来自 https://github.com/tiangolo/fastapi/issues/23#issuecomment-571602787):

The following works with the pycharm debugger with reload running in a docker-compose remote interpreter

from fastapi import FastAPI
import uvicorn

app = FastAPI()

@app.get("/")
def root():
    a = "a"
    b = "b" + a
    return {"hello world": b}


if __name__ == '__main__':
    uvicorn.run("main:app", host='0.0.0.0', port=8000, reload=True)

Notice the it's "main:app" and not app otherwise you get an error: WARNING: You must pass the application as an import string to enable 'reload' or 'workers'.