Skip to content

Instantly share code, notes, and snippets.

@emersonmx
Last active August 11, 2021 12:41
Show Gist options
  • Save emersonmx/ef1590200541495b4c0df6e776147d08 to your computer and use it in GitHub Desktop.
Save emersonmx/ef1590200541495b4c0df6e776147d08 to your computer and use it in GitHub Desktop.
Python tips

Python Tips

Poetry

Setup dev tools

poetry add -D flake8 mypy black isort pytest coverage invoke ipdb jedi rope

Export requirements.txt

poetry export -f requirements.txt -o requirements.txt
pip install --require-hashes -r requirements.txt

Docker

FastAPI

FROM Ubuntu

FROM ubuntu:focal

RUN : \
    && apt-get update \
    && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
        software-properties-common \
    && add-apt-repository ppa:deadsnakes \
    && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
        curl \
        python3.9 \
        python3.9-distutils \
    && curl --location --output /virtualenv.pyz https://bootstrap.pypa.io/virtualenv.pyz \
    && python3.9 /virtualenv.pyz /venv \
    && rm virtualenv.pyz \
    && apt-get autoremove -y curl \
    && apt-get clean \
    && rm -rf /var/lib/apt/lists/* \
    && :

ENV PATH=/venv/bin:$PATH \
    PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1 \
    PYTHONPATH=/app

WORKDIR /app

RUN useradd --create-home appuser

COPY requirements.txt .
RUN : \
    && pip install --require-hashes -r /app/requirements.txt \
    && :

COPY . .

USER appuser

EXPOSE 8000

CMD ["uvicorn", "--host", "0.0.0.0", "src.main:app"]

FROM Python

FROM python:3.9-buster as venv

RUN : \
    && curl --location --output /virtualenv.pyz https://bootstrap.pypa.io/virtualenv.pyz \
    && python3.9 /virtualenv.pyz /opt/venv \
    && :

ENV PATH=/opt/venv/bin:$PATH

COPY requirements.txt .
RUN pip install --require-hashes -r requirements.txt

FROM python:3.9-slim-buster

COPY --from=venv /opt/venv /opt/venv

ENV PATH=/opt/venv/bin:$PATH \
    PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1 \
    PYTHONPATH=/app

WORKDIR /app

COPY . .

# https://github.com/tiangolo/uvicorn-gunicorn-docker/tree/master/docker-images

COPY ./start.sh /start.sh
RUN chmod +x /start.sh

COPY ./gunicorn_conf.py /gunicorn_conf.py

RUN useradd --create-home appuser
USER appuser

EXPOSE 8000

CMD ["/start.sh"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment