Skip to content

Commit a19f275

Browse files
committed
Suggestion: don't import uvicorn to allow for alternative asgi servers
The `core.py` file imports uvicorn even though it's only used for `serve()` calls. I'm deploying a FastHTML app to AWS Lambda, and extra imports cause longer cold starts. I did a naive test (3 samples of each) and it seems like this uvicorn import takes 10-25ms to load. Moving the `uvicorn` import into `serve()` still works, and doesn't seem to violate the project style guide.
1 parent 11dc14b commit a19f275

File tree

2 files changed

+4
-2
lines changed

2 files changed

+4
-2
lines changed

fasthtml/core.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
'MiddlewareBase', 'FtResponse', 'unqid', 'setup_ws']
1212

1313
# %% ../nbs/api/00_core.ipynb
14-
import json,uuid,inspect,types,uvicorn,signal,asyncio,threading,inspect
14+
import json,uuid,inspect,types,signal,asyncio,threading,inspect
1515

1616
from fastcore.utils import *
1717
from fastcore.xml import *
@@ -638,6 +638,7 @@ def serve(
638638
if not appname:
639639
if glb.get('__name__')=='__main__': appname = Path(glb.get('__file__', '')).stem
640640
elif code.co_name=='main' and bk.f_back.f_globals.get('__name__')=='__main__': appname = inspect.getmodule(bk).__name__
641+
import uvicorn
641642
if appname:
642643
if not port: port=int(os.getenv("PORT", default=5001))
643644
print(f'Link: http://{"localhost" if host=="0.0.0.0" else host}:{port}')

nbs/api/00_core.ipynb

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@
4343
"outputs": [],
4444
"source": [
4545
"#| export\n",
46-
"import json,uuid,inspect,types,uvicorn,signal,asyncio,threading,inspect\n",
46+
"import json,uuid,inspect,types,signal,asyncio,threading,inspect\n",
4747
"\n",
4848
"from fastcore.utils import *\n",
4949
"from fastcore.xml import *\n",
@@ -1582,6 +1582,7 @@
15821582
" if not appname:\n",
15831583
" if glb.get('__name__')=='__main__': appname = Path(glb.get('__file__', '')).stem\n",
15841584
" elif code.co_name=='main' and bk.f_back.f_globals.get('__name__')=='__main__': appname = inspect.getmodule(bk).__name__\n",
1585+
" import uvicorn\n",
15851586
" if appname:\n",
15861587
" if not port: port=int(os.getenv(\"PORT\", default=5001))\n",
15871588
" print(f'Link: http://{\"localhost\" if host==\"0.0.0.0\" else host}:{port}')\n",

0 commit comments

Comments
 (0)