-
-
Save yoomaxxx/7f7247e8af6a1fbaf0723dd2306c2188 to your computer and use it in GitHub Desktop.
Automatic browser reloading in FastAPI
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| fastapi | |
| uvicorn[standard] | |
| arel | |
| jinja2 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <body> | |
| {% block content %}{% endblock %} | |
| <!-- Hot reload script --> | |
| {% if DEBUG %} {{ hot_reload.script(url_for('hot-reload')) | safe }} {% endif | |
| %} | |
| </body> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| {% extends "base.html" %} {% block content %} Hello, world! {% endblock %} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment