-
-
Save vrslev/6d0602bfa939a01844f645c608afb85a to your computer and use it in GitHub Desktop.
| import os | |
| import arel | |
| from fastapi import FastAPI, Request | |
| from fastapi.templating import Jinja2Templates | |
| app = FastAPI() | |
| templates = Jinja2Templates("templates") | |
| if _debug := os.getenv("DEBUG"): | |
| hot_reload = arel.HotReload(paths=[arel.Path(".")]) | |
| app.add_websocket_route("/hot-reload", route=hot_reload, name="hot-reload") | |
| app.add_event_handler("startup", hot_reload.startup) | |
| app.add_event_handler("shutdown", hot_reload.shutdown) | |
| templates.env.globals["DEBUG"] = _debug | |
| templates.env.globals["hot_reload"] = hot_reload | |
| @app.get("/") | |
| def index(request: Request): | |
| return templates.TemplateResponse("index.html", context={"request": request}) | |
| # run: | |
| # DEBUG=true uvicorn main:app --reload |
| fastapi | |
| uvicorn[standard] | |
| arel | |
| jinja2 |
| <body> | |
| {% block content %}{% endblock %} | |
| <!-- Hot reload script --> | |
| {% if DEBUG %} {{ hot_reload.script(url_for('hot-reload')) | safe }} {% endif | |
| %} | |
| </body> |
| {% extends "base.html" %} {% block content %} Hello, world! {% endblock %} |
This works for me, but only on the routes defined within the main file where app is defined. Any ideas on how to get this to work on other routes? I have separate routes defined within a routers directory and then apply them in the main file with app.include_router(my_router).
@dicolasi Please share your code ๐
@thisisthemurph I don't understand exactly your setup. Can you share a minimal reproducible example of what you're saying?
It works in Safari (Version 17.2 (19617.1.17.11.9)) just fine.
It works in Safari (Version 17.2 (19617.1.17.11.9)) just fine.
@yanky2000 Just tested it in Safari 17.1โit also works. Removed the comment, thanks.
thx ๐
Is it also possible to hot reload when we modify .html files ? it works only for .py files for me.
I can see a WS connection open from the logs:
and I can see the script in html:
however the page does not get reloaded on save. Am I missing something?