Skip to content

Commit

Permalink
Add FastAPI and Litestar server examples
Browse files Browse the repository at this point in the history
  • Loading branch information
miguelgrinberg committed Oct 5, 2023
1 parent 58b5706 commit 2e1f026
Show file tree
Hide file tree
Showing 3 changed files with 85 additions and 0 deletions.
10 changes: 10 additions & 0 deletions examples/server/asgi/README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,16 @@ fiddle.py
This is a very simple application based on a JavaScript example of the same
name.

fastapi-fiddle.py
-----------------

A version of `fiddle.py` that is integrated with the FastAPI framework.

litestar-fiddle.py
------------------

A version of `fiddle.py` that is integrated with the Litestar framework.

Running the Examples
--------------------

Expand Down
37 changes: 37 additions & 0 deletions examples/server/asgi/fastapi-fiddle.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
#!/usr/bin/env python
from fastapi import FastAPI
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles
import socketio
import uvicorn

app = FastAPI()
app.mount('/static', StaticFiles(directory='static'), name='static')

sio = socketio.AsyncServer(async_mode='asgi')
combined_asgi_app = socketio.ASGIApp(sio, app)


@app.get('/')
async def index():
return FileResponse('fiddle.html')


@app.get('/hello')
async def hello():
return {'message': 'Hello, World!'}


@sio.event
async def connect(sid, environ, auth):
print(f'connected auth={auth} sid={sid}')
await sio.emit('hello', (1, 2, {'hello': 'you'}), to=sid)


@sio.event
def disconnect(sid):
print('disconnected', sid)


if __name__ == '__main__':
uvicorn.run(combined_asgi_app, host='127.0.0.1', port=5000)
38 changes: 38 additions & 0 deletions examples/server/asgi/litestar-fiddle.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
#!/usr/bin/env python
from litestar import Litestar, get, MediaType
from litestar.response import File
from litestar.static_files.config import StaticFilesConfig
import socketio
import uvicorn

sio = socketio.AsyncServer(async_mode='asgi')


@get('/', media_type=MediaType.HTML)
async def index() -> File:
return File('fiddle.html', content_disposition_type='inline')


@get('/hello')
async def hello() -> dict:
return {'message': 'Hello, World!'}


@sio.event
async def connect(sid, environ, auth):
print(f'connected auth={auth} sid={sid}')
await sio.emit('hello', (1, 2, {'hello': 'you'}), to=sid)


@sio.event
def disconnect(sid):
print('disconnected', sid)


app = Litestar([index, hello], static_files_config=[
StaticFilesConfig('static', directories=['static'])])
combined_asgi_app = socketio.ASGIApp(sio, app)


if __name__ == '__main__':
uvicorn.run(combined_asgi_app, host='127.0.0.1', port=5000)

0 comments on commit 2e1f026

Please sign in to comment.