Skip to content

Instantly share code, notes, and snippets.

@hamelsmu
Created November 2, 2024 18:57
Show Gist options
  • Save hamelsmu/4d6d74c8ed5ab0189003895c1d5588b7 to your computer and use it in GitHub Desktop.
Save hamelsmu/4d6d74c8ed5ab0189003895c1d5588b7 to your computer and use it in GitHub Desktop.
Modern web applications in pure Python

Read docs

Modern web applications in pure Python

Built on solid web foundations, not the latest fads - with FastHTML you can get started on anything from simple dashboards to scalable web applications in minutes.

Learn more Watch intro 7min 30sec

Try now

This home page is a FastHTML app.

Click the buttons below to see four small, live components in action.

card3d.py

        def card_3d_demo():
"""This is a standalone isolated Python component.
Behavior and styling is scoped to the component."""
def card_3d(text, background, amt, left_align):
    # JS and CSS can be defined inline or in a file
    scr = ScriptX('card3d.js', amt=amt)
    align='left' if left_align else 'right'
    sty = StyleX('card3d.css', background=f'url({background})', align=align)
    return Div(text, Div(), sty, scr)
# Design credit: https://codepen.io/markmiro/pen/wbqMPa
card = card_3d("Mouseover me", bgurl, amt=1.5, left_align=True)
return Div(card, style=cardcss)


Mouseover me

weather.py

        async def weather_table():
"""Dynamically generated python content
directly incorporated into the HTML"""
# These are actual real-time weather.gov observations
try: results = await all_weather()
except: return P('Weather not available')
rows = [Tr(Td(city), *map(Td, d.values()), cls="even:bg-purple/5")
        for city,d in results.items()]
flds = 'City', 'Temp (C)', 'Wind (kmh)', 'Humidity'
head = Thead(*map(Th, flds), cls="bg-purple/10")
return Table(head, *rows, cls="w-full")


City | Temp (C) | Wind (kmh) | Humidity | New York | 14.4 | 7.6 | 35.7
---|---|---|---
San Francisco | 14.4 | NA | 67.0
Chicago | 12.2 | 9.4 | 52.6
Houston | 26.1 | 13.0 | 84.6
Washington | 17.8 | 18.4 | 38.0

accordion.py

        def accordion_demo():
"""UI components can be styled and reused.
UI libraries can be installed using `pip`."""
accs = [accordion(id=id, question=q, answer=a,
    question_cls="text-black s-body", answer_cls=a_cls, container_cls=c_cls)
    for id,(q,a) in enumerate(qas)]
return Div(*accs, cls=acc_cls)


What is this?

This is a little demo of a reusable accordion component.

What is FastHTML?

FastHTML is a Python library for building web apps.

What is HTMX?

HTMX is a JavaScript library that extends browser interaction behavior.

todos.py

            class Todo:
    "Use any database system you like"
    id:int; title:str; done:bool
    def __ft__(self):
        "`__ft__` defines how FastHTML renders an object"
        return Li("✅ " if self.done else "", self.title)

todos = db.create(Todo)
def todos_table():
    "This example uses the `fastlite` DB lib"
    return Ul(*todos(), cls=list_class)


DB-generated todo list

  • ✅ Create sample todos
  • ✅ Create a sample FastHTML app
  • Read this todo list

GET STARTED IN MINUTES

The fastest way to create a real web application.

With FastHTML you create good-looking modern web applications in pure Python and deploy them in minutes.

Get started fast

A single Python file is all that's needed to create any app you can think of. Or bring in any Python or JS library you like.

Flexibility

FastHTML provides full access to HTTP, HTML, JS, and CSS, bringing the foundations of the web to you. There's no limits to what you can build.

Speed & scale

FastHTML applications are fast and scalable. They're also easy to deploy, since you can use any hosting service that supports Python.

TECH STACK

FastHTML scales up and scales down.

Read more about our design philosophy here , or click a button below:

Build on solid foundations

FastHTML stands on the shoulders of giants:

ASGI

HTMX

HTTP

HTML

Use tools you already know

FastHTML embraces the familiar:

Python

Uvicorn

Starlette

SQLite

Deploy anywhere

FastHTML runs anywhere Python does, including 1-click deploy to:

Railway

Vercel

Hugging Face

PythonAnywhere

SAMPLES

See FastHTML in action

FastHTML can be used for everything from collaborative games to multi-modal UI. We've selected small self-contained examples for you to learn from.

Game of life

To-do

Chat bot

Pictionary AI

Discover all

FAQ

Questions? Answers.

Your top FastHTML questions clarified.

What kinds of applications can be written with this?

It's good for: general purpose web applications (i.e anything you'd build with React, Django, Next.js, etc); quick dashboards, prototypes, and in-company apps (e.g. like what you might use gradio/streamlit/etc for); Analytics/models/dashboards interactive reports; Custom blogs and content-heavy sites where you also want some interactive/dynamic content.

Where can I deploy my FastHTML to? What's needed?

You can deploy a FastHTML app to any service or server that supports Python. We have guides and helpers for Railway.app, Vercel, Hugging Face Spaces, Replit, and PythonAnywhere. You can also use any VPS or server, or any on-premise machine with Python installed. All major operating systems are supported.

How does FastHTML relate to FastAPI?

FastAPI is one of the inspirations for FastHTML. We are fans of its developer experience and tried to make FastHTML extremely familiar for FastAPI users. FastAPI is designed for creating APIs, whereas FastHTML is designed for creating HTML (i.e "Hypermedia applications"). Anything you could create with FastAPI (plus a JS frontend), you could also create with FastHTML, and vice versa -- if you prefer mainly writing JS, you might prefer FastAPI, since you can move a lot of client-side logic into the JS. If you prefer mainly writing Python, you'll probably want to use FastHTML, since you can often avoid using JS entirely.

Is this only for multi-page "old style" web apps, or can FastHTML be used for modern SPA apps too?

FastHTML is specifically designed to make writing modern SPA apps as fast and easy as possible, whilst also ensuring the apps you write are scalable and performant. By default, FastHTML routes return lightweight "partials" that update the DOM directly, rather than doing a full page refresh.

What is HTMX, and what's it go to do with FastHTML?

HTMX is best thought of as filling in the missing bits of a web browser -- in fact, web browser manufacturers are considering incorporating similar features directly into future browsers. It is a small javascript library that with a single line of HTML lets you respond to any event from any part of a web page by modifying the DOM in any way you like, all directly from Python. Whilst you don't have to use it with FastHTML, it will dramatically increase the amount of stuff you can do!

Do I need to know JS? Can I use it if I want, with FastHTML?

No, and yes! You can write nearly any standard web app with just Python. However, using a bit of JS can be helpful -- for instance, nearly any existing JS lib can be incorporated into a FastHTML app, and you can sprinkle bits of JS into your pages anywhere you like.

Are FastHTML apps slower than React, Next.js, etc?

It depends. Apps using FastHTML and HTMX are often faster than JS-based approaches using big libraries, since they can be very lightweight.

LOVE IS IN THE AIR

What the experts say

Top web programmers tell us that they love working with FastHTML.

FastHTML is as intuitive as FastAPI, lends itself to clean architecture, and its HTML+HTMX structure makes it a good competitor to Django for building webapps. Most importantly, it's fun to use.

Daniel Roy Greenfeld

Co-author

Two Scoops of Django

Python has always been a wonderful tool for creating web applications; with FastHTML, it's even better!

Giles Thomas

Founder

PythonAnywhere

With FastHTML and Railway, Pythonistas can now have a real web application running in minutes, and can scale it all the way up to sophisticated production deployments.

Jake Cooper

CEO

Railway.app

  • ergonomic af
  • fast af
  • slick af
  • SSR af

(From twitter)

Guillermo Rauch

CEO

Vercel

© 2024 onwards AnswerDotAI. All rights reserved.

  • Github
  • Join Discord
  • Docs
  • Site design
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment