Snippets Collections
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

Sat Oct 08 2022 22:56:22 GMT+0000 (UTC)

#python #async #fastapi
star

Mon Jan 31 2022 02:31:04 GMT+0000 (UTC)

#python #fastapi #websocket
star

Mon Jan 31 2022 02:16:16 GMT+0000 (UTC)

#python #fastapi #docker
star

Mon Jan 31 2022 02:15:50 GMT+0000 (UTC)

#python #fastapi #docker

Save snippets that work with our extensions

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