Skip to content

Instantly share code, notes, and snippets.

@Kvit
Last active January 29, 2025 19:50
Show Gist options
  • Select an option

  • Save Kvit/6c3fe514fd7d36eddf9c9b6b59124a22 to your computer and use it in GitHub Desktop.

Select an option

Save Kvit/6c3fe514fd7d36eddf9c9b6b59124a22 to your computer and use it in GitHub Desktop.
Trying to change session value in socket
# Testing managing session values with websockets in FastHTML
from fasthtml.common import *
import uuid
app = FastHTML(exts='ws')
rt = app.route
@rt("/")
def get(session):
session.setdefault("session_id", str(uuid.uuid4()))
return Body(
Div(f" Value in session['person'] is: {session.get('person', " Not Defined ")}. | Session ID: {session.get('session_id', None)} "),
Div(A('Change name to BOB via HTTP Request ', href="/login")),
# Change session['person'] value via websocket
Div(
P("Set new value in session['person'] via websocket"),
Form(Input(id='msg'), id='form', ws_send=True),
hx_ext="ws", ws_connect="/ws"
),
Div(id='notifications'),
),
@ rt('/login')
def get(session):
# set session['person'] value in http request
session["person"] = "BOB"
return Body(
Div(f" session['person'] now is: {session.get('person')} | Session ID: {session.get('session_id', None)}"),
Div(A("Go Home", href="/"))
)
@ app.ws('/ws')
async def ws(msg:str, send, session):
prior_name = session.get('person', 'Not Defined')
# change session['person'] value via websocket
session['person'] = msg
await send(Div(f'Prior session["person"] value was {prior_name}, not it is changed to: {session.get("person")}. Refresh browser to see if it changes | Session ID: {session.get('session_id', None)} ' , id='notifications'))
serve()
@Kvit
Copy link
Author

Kvit commented Jan 29, 2025

Changing session['person'] in http route is visible to all routes, changes done in websocket are not saved in global session object

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment