Getting started

Installation

Red Dwarf is not available on PyPI yet. For now, clone the GitHub repository and extract the red_dwarf package into your project. Once it is on your Python path, you can start writing your application.

Your first app

A Red Dwarf application is just a collection of routes returning HTML. Let's build one in three small steps.

Start with a page that says hello.

import red_dwarf as rd

@rd.get("/")
async def index(request):
    return rd.html("""
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Hello</title>
    <script type="module" src="https://cdn.jsdelivr.net/gh/starfederation/datastar@v1.0.2/bundles/datastar.js"></script>
  </head>
  <body>
    <main>
      <h1>Hello, world!</h1>
      <p id="message">Welcome to Red Dwarf.</p>
      <button data-on:click="@get('/message')">Simple Update</button>
      <button data-on:click="@get('/clock')">Streamed Update</button>
    </main>
  </body>
</html>
""")

if __name__ == "__main__":
    rd.run()

Note that routes are automatically registered.

Open http://127.0.0.1:8080/ and you should see your first page.

Update an element

Returning a patch lets you replace part of the page without sending the whole document again.

Careful, the request has to be triggered by a Datastar action!

import red_dwarf as rd

@rd.get("/message")
async def message(request):
    return rd.patch("""
<p id="message">
  This text was updated by the server.
</p>
""")

Only the element with id="message" changes. Everything else stays exactly where it is.

Streamed updates

If a route returns a Python generator, Red Dwarf keeps the connection open and sends each patch as it is produced.

import red_dwarf as rd
import asyncio

@rd.get("/clock")
async def clock(request):
    while True:
        yield rd.patch(f"""
<p id="message">
  The time is {asyncio.get_running_loop().time():.0f}.
</p>
""")
        await asyncio.sleep(1)

That's all there is to it.

Your application starts with plain HTML, and whenever something changes, you send a small HTML fragment describing the new state.

Or a big one! You can morph the whole HTML if you want. We call this view = f(state).

More information on the Datastar website .

Now go build!