Home / File/ tutorial002_py39.py — fastapi Source File

tutorial002_py39.py — fastapi Source File

Architecture documentation for tutorial002_py39.py, a python file in the fastapi codebase. 3 imports, 0 dependents.

File python FastAPI Applications 3 imports 3 functions

Entity Profile

Dependency Diagram

graph LR
  f565d9f5_3e56_319e_ccb9_cd9f01a5b196["tutorial002_py39.py"]
  0dda2280_3359_8460_301c_e98c77e78185["typing"]
  f565d9f5_3e56_319e_ccb9_cd9f01a5b196 --> 0dda2280_3359_8460_301c_e98c77e78185
  534f6e44_61b8_3c38_8b89_6934a6df9802["__init__.py"]
  f565d9f5_3e56_319e_ccb9_cd9f01a5b196 --> 534f6e44_61b8_3c38_8b89_6934a6df9802
  967b6712_70e2_f5fa_f671_7c149857a445["responses.py"]
  f565d9f5_3e56_319e_ccb9_cd9f01a5b196 --> 967b6712_70e2_f5fa_f671_7c149857a445
  style f565d9f5_3e56_319e_ccb9_cd9f01a5b196 fill:#6366f1,stroke:#818cf8,color:#fff

Relationship Graph

Source Code

from typing import Union

from fastapi import (
    Cookie,
    Depends,
    FastAPI,
    Query,
    WebSocket,
    WebSocketException,
    status,
)
from fastapi.responses import HTMLResponse

app = FastAPI()

html = """
<!DOCTYPE html>
<html>
    <head>
        <title>Chat</title>
    </head>
    <body>
        <h1>WebSocket Chat</h1>
        <form action="" onsubmit="sendMessage(event)">
            <label>Item ID: <input type="text" id="itemId" autocomplete="off" value="foo"/></label>
            <label>Token: <input type="text" id="token" autocomplete="off" value="some-key-token"/></label>
            <button onclick="connect(event)">Connect</button>
            <hr>
            <label>Message: <input type="text" id="messageText" autocomplete="off"/></label>
            <button>Send</button>
        </form>
        <ul id='messages'>
        </ul>
        <script>
        var ws = null;
            function connect(event) {
                var itemId = document.getElementById("itemId")
                var token = document.getElementById("token")
                ws = new WebSocket("ws://localhost:8000/items/" + itemId.value + "/ws?token=" + token.value);
                ws.onmessage = function(event) {
                    var messages = document.getElementById('messages')
                    var message = document.createElement('li')
                    var content = document.createTextNode(event.data)
                    message.appendChild(content)
                    messages.appendChild(message)
                };
                event.preventDefault()
            }
            function sendMessage(event) {
                var input = document.getElementById("messageText")
                ws.send(input.value)
                input.value = ''
                event.preventDefault()
            }
        </script>
    </body>
</html>
"""


@app.get("/")
async def get():
    return HTMLResponse(html)


async def get_cookie_or_token(
    websocket: WebSocket,
    session: Union[str, None] = Cookie(default=None),
    token: Union[str, None] = Query(default=None),
):
    if session is None and token is None:
        raise WebSocketException(code=status.WS_1008_POLICY_VIOLATION)
    return session or token


@app.websocket("/items/{item_id}/ws")
async def websocket_endpoint(
    websocket: WebSocket,
    item_id: str,
    q: Union[int, None] = None,
    cookie_or_token: str = Depends(get_cookie_or_token),
):
    await websocket.accept()
    while True:
        data = await websocket.receive_text()
        await websocket.send_text(
            f"Session cookie or query token value is: {cookie_or_token}"
        )
        if q is not None:
            await websocket.send_text(f"Query parameter q is: {q}")
        await websocket.send_text(f"Message text was: {data}, for item ID: {item_id}")

Domain

Subdomains

Dependencies

Frequently Asked Questions

What does tutorial002_py39.py do?
tutorial002_py39.py is a source file in the fastapi codebase, written in python. It belongs to the FastAPI domain, Applications subdomain.
What functions are defined in tutorial002_py39.py?
tutorial002_py39.py defines 3 function(s): get, get_cookie_or_token, websocket_endpoint.
What does tutorial002_py39.py depend on?
tutorial002_py39.py imports 3 module(s): __init__.py, responses.py, typing.
Where is tutorial002_py39.py in the architecture?
tutorial002_py39.py is located at docs_src/websockets/tutorial002_py39.py (domain: FastAPI, subdomain: Applications, directory: docs_src/websockets).

Analyze Your Own Codebase

Get architecture documentation, dependency graphs, and domain analysis for your codebase in minutes.

Try Supermodel Free