Skip to content

Instantly share code, notes, and snippets.

@evnchn
Created March 14, 2025 01:45
Show Gist options
  • Select an option

  • Save evnchn/1772e80587775f9603ae91606aa7fdf1 to your computer and use it in GitHub Desktop.

Select an option

Save evnchn/1772e80587775f9603ae91606aa7fdf1 to your computer and use it in GitHub Desktop.
# Pieced together from:
# (1) https://github.com/Vizonex/Winloop?tab=readme-ov-file#how-to-use-winloop-with-fastapi
# (2) https://www.reddit.com/r/nicegui/comments/1dlx3or/fastapi_nicegui_integration/
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
import winloop
import uvicorn
import asyncio
import datetime
from nicegui import ui
app = FastAPI()
@app.on_event("startup")
def make_assertion():
# Check to make sure that we bypassed the original eventloop Policy....
assert isinstance(asyncio.get_event_loop_policy(), winloop.EventLoopPolicy)
# not WinLoopPolicy. (1) is outdated. I'll see when I can update it.
@app.get("/test")
async def test_get_request():
return HTMLResponse("<html><body><h1>FAST API WORKS WITH WINLOOP!</h1></body></html>")
# starllete will use asyncio.to_thread() so that this can remain asynchronous
@app.get("/date")
def test_dynamic_response():
return str(datetime.datetime.now())
@app.get("/str")
def test_str_response():
return str(asyncio.get_event_loop_policy())
def init(fastapi_app: FastAPI) -> None:
@ui.page("/")
def index():
ui.label("Hello, world!") #
ui.label(str(asyncio.get_event_loop_policy()))
ui.run_with(
fastapi_app,
storage_secret='hmm',
)
# Although tricky to pass and is not normal, it does in fact work...
if __name__ == "__main__":
init(app)
winloop.install()
# Winloop's eventlooppolicy will be passed to uvicorn after this point...
loop = asyncio.get_event_loop()
config = uvicorn.Config(app=app,port=8040,loop=loop) # sadly no reload=True, since that would need `isinstance(self.app, str)`
server = uvicorn.Server(config)
asyncio.run(server.serve())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment