Snippets Collections
from fastapi import FastAPI, HTTPException, Security, status
from fastapi.security import APIKeyHeader


api_keys = [
    "my_api_key"
]

app = FastAPI()

api_key_header = APIKeyHeader(name="X-API-Key")

def get_api_key(api_key_header: str = Security(api_key_header)) -> str:
    if api_key_header in api_keys:
        return api_key_header
    raise HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Invalid or missing API Key",
    )

@app.get("/protected")
def protected_route(api_key: str = Security(get_api_key)):
    # Process the request for authenticated users
    return {"message": "Access granted!"}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)


wget https://blah/blah/stats --header="X-API-Key: key1"
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
import io
import pandas as pd

app = FastAPI()

@app.get("/get_csv")
async def get_csv():
    df = pd.DataFrame(dict(col1 = 1, col2 = 2), index=[0])
    stream = io.StringIO()
    df.to_csv(stream, index = False)
    response = StreamingResponse(iter([stream.getvalue()]),
                                 media_type="text/csv"
                                )
    response.headers["Content-Disposition"] = "attachment; filename=export.csv"
    return response
# Configuration file for `gunicorn` command.
# 1) Set the settings in this file.
# 2) Run `gunicorn` from the terminal in the directory containing this file

import multiprocessing
import os

from dotenv import load_dotenv

load_dotenv()

# Get the `ENVIRONMENT` env variable and convert it to lowercase if it exists
environment = os.getenv("ENVIRONMENT")
environment = environment.lower() if environment else "dev"


# Gunicorn app
# Tell Gunicorn which application to run
wsgi_app = "app.main:app"

# Requests
# Restart workers after so many requests, with some variability.
max_requests = 1000
max_requests_jitter = 50

# Logging
# Use stdout for logging
log_file = "-"

# The IP address and port to accept requests on
bind = "0.0.0.0:8000"

# Use this formula for production, otherwise only run 2 workers
workers = (
    multiprocessing.cpu_count() * 2 + 1
    if environment in ["prod", "production"]
    else 2
)
worker_class = "uvicorn.workers.UvicornWorker"
FROM python:3.11-slim


# Create a non-root user to run the app as
RUN addgroup --system app && adduser --system --group app

# Environment variables
ENV PYTHONUNBUFFERED=1 \
    PYTHONDONTWRITEBYTECODE=1 \
    PIP_NO_CACHE_DIR=off \
    PIP_DISABLE_PIP_VERSION_CHECK=on \
    PIP_DEFAULT_TIMEOUT=100 \
    POETRY_VIRTUALENVS_IN_PROJECT=true \
    # Set Poetry to NOT install the dependencies into a virtual environment, instead install them into the system's Python environment
    POETRY_VIRTUALENVS_CREATE=false \
    POETRY_NO_INTERACTION=1 \
    PYTHONPATH=${PYTHONPATH}:${PWD}

# Make a directory for the project
RUN mkdir /app

# Change to the `/app` directory
WORKDIR /app

# Copy the project files over to the container
COPY pyproject.toml /app
COPY . /app

# Chown all the files to the app user
RUN chown -R app:app /app

# Install Poetry
RUN pip3 install poetry

# Export the Poetry pack list to another format
RUN poetry export -f requirements.txt > requirements.txt

# Install the Python dependencies
RUN poetry install --only main

# Become the `app` user
USER app

# Expose port 8000 on the container
EXPOSE 8000

#CMD ["poetry", "run", "gunicorn"]
CMD ["gunicorn"]
import io

from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from fastapi.staticfiles import StaticFiles


app = FastAPI()

# create a 'static files' directory
# create a '/static' prefix for all files
# serve files from the 'media/' directory under the '/static/' route
#   /Big_Buck_Bunny_1080p.avi becomes '/static/Big_Buck_Bunny_1080p.avi'
# name='static' is used internally by FastAPI
app.mount("/static", StaticFiles(directory="media"), name="static")


@app.get("/")
async def main():
    # open the movie file to stream it
    movie = open("media/Big_Buck_Bunny_1080p.avi", "rb")
    # return a stream response with the movie and a MIME type of 'video/avi'
    return StreamingResponse(movie, media_type="video/avi")
from datetime import datetime
import asyncio

from fastapi import FastAPI, WebSocket


app = FastAPI(
    title='WebSocket example',
    description='WebSocket example',
    version='0.0.1'
)


@app.websocket("/task/{task_uuid}")  # take a 'task_uuid' URL parameter
async def websocket_page(task_uuid, websocket: WebSocket):
    await websocket.accept()  # accept connections

    i = 0

    """
    create a loop to send the value of 'i' every second with a timestamp:
      13:30:01 - i is 5
      13:30:02 - i is 6
      13:30:03 - i is 7
    """
    while i < 10:
        timestamp = datetime.now().strftime("%H:%M:%S")
        await websocket.send_text(f"[{timestamp}] - i is {i}")
        i += 1
        await asyncio.sleep(1)
version: '3.8'

services:
  fastapi_api:
    build:
      context: ./<path to Dockerfile>
    # the 'app.main' part of the next line assumes your main.py file is in a folder named 'app'
    command: gunicorn app.main:app --bind 0.0.0.0:5000 -w 2 -k uvicorn.workers.UvicornWorker
    ports:
      # host:container
      - "8000:5000"
FROM python:3.11-rc-slim

ENV WORKDIR=/usr/src/app
ENV USER=app
ENV APP_HOME=/home/app/web
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1

WORKDIR $WORKDIR

RUN pip install --upgrade pip
COPY ./requirements.txt $WORKDIR/requirements.txt
RUN pip install -r requirements.txt

RUN adduser --system --group $USER
RUN mkdir $APP_HOME
WORKDIR $APP_HOME

COPY . $APP_HOME
RUN chown -R $USER:$USER $APP_HOME
USER $USER
star

Fri Dec 22 2023 09:37:50 GMT+0000 (Coordinated Universal Time) https://medium.com/@valerio.uberti23/a-beginners-guide-to-using-api-keys-in-fastapi-and-python-256fe284818d

#python #fastapi
star

Fri Dec 22 2023 09:11:04 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/61140398/fastapi-return-a-file-response-with-the-output-of-a-sql-query

#python #fastapi #pandas
star

Sun Jul 23 2023 16:11:29 GMT+0000 (Coordinated Universal Time)

#python #fastapi
star

Sat Jul 22 2023 23:20:25 GMT+0000 (Coordinated Universal Time)

#python #fastapi #poetry #docker
star

Sat Oct 08 2022 22:56:22 GMT+0000 (Coordinated Universal Time)

#python #async #fastapi
star

Mon Jan 31 2022 02:31:04 GMT+0000 (Coordinated Universal Time)

#python #fastapi #websocket
star

Mon Jan 31 2022 02:16:16 GMT+0000 (Coordinated Universal Time)

#python #fastapi #docker
star

Mon Jan 31 2022 02:15:50 GMT+0000 (Coordinated Universal Time)

#python #fastapi #docker

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension