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

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