Last active
August 3, 2024 15:04
-
-
Save cgarciae/a11185da9d693a1f60389c49412c476f to your computer and use it in GitHub Desktop.
FastHTMLResponse class for 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
from typing import Iterable | |
from fastapi import FastAPI | |
from fastapi.responses import HTMLResponse | |
import fasthtml.common as fasthtml | |
from fasthtml.components import * | |
app = FastAPI() | |
class FastHTMLResponse(HTMLResponse): | |
def render(self, content) -> bytes: | |
if isinstance(content, str): | |
pass | |
elif isinstance(content[0], str): | |
content = fasthtml.to_xml(content) | |
else: | |
content = "\n".join(fasthtml.to_xml(c) for c in content) | |
return super().render(content) | |
@app.get("/", response_class=FastHTMLResponse) | |
def index(): | |
return [ | |
Title("App"), | |
Div( | |
H1("Hello, World!"), | |
P("This is a paragraph."), | |
), | |
] | |
if __name__ == "__main__": | |
import uvicorn | |
uvicorn.run("main:app", host="0.0.0.0", port=5001, reload=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
FastHTML integration with FastAPI
Simple example of how to use FastHTML python components with FastAPI.