Skip to main content
Markdown

Getting started with Flask

Live updates, chat, who is online, calls and group calls in a Flask app, or any Python framework that takes a route, through WordPlus Cloud. Two packages:

  • Your server (wordplus-realtime) declares your rooms once, says who may join them and call whom, and sends events to rooms and to users. In Flask it is one route and a few rules.
  • The page (@wordplus/realtime, from npm) connects to WordPlus Cloud, joins rooms, and sends and gets events: emit, emitWithAck, volatile.

What goes through WordPlus Cloud is sealed with keys only your server and the browsers of your users hold. Ready-made parts come with it, all optional: the Better Messages chat, its list of who is online and its call screen. The example app is a whole shop built this way.

Your framework can run websockets of its own. Why WordPlus Cloud says what the cloud runs for you, and what it adds.

Try it live at flask.docs.wordplus.cloud: the example app of this guide as a demo, a shop of your own for a day, with Ben and Cara opening in windows of their own.

Two browsers side by side: Ann marks order 1042 as shipped on the staff page of the shop, and the order page of Ben shows Shipped at once, without a reload

1. Your app in WordPlus Cloud​

In your WordPlus Cloud account, go to Apps → Add app. Name it, and list the addresses its pages are served from: https://shop.example.com, and http://localhost:8000 while you develop. Only pages on those addresses may connect.

You get the app key, public because every page carries it, and its secret, for your server only. Make a local key of your own too: everything sealed is sealed with keys derived from it, and it never leaves your servers.

WORDPLUS_SITE=s1500000007
WORDPLUS_SECRET=…
WORDPLUS_LOCAL_KEY=… # openssl rand -hex 32; the same on every server of the app, kept as long as the app

2. Install​

pip install wordplus-realtime              # uv add works the same
npm install @wordplus/realtime
npx wordplus-realtime copy static/ # the worker, the room client and the script of the components

The worker lets the tabs of a user share one connection, the room client runs group calls, and realtime-ui.min.js is the ready-made parts. Copy them again after every update of the npm package, in your build.

3. Your server​

# app.py
from flask import Flask, jsonify, request, session
from wordplus_realtime import Realtime

realtime = Realtime.from_environment( # WORDPLUS_SITE, WORDPLUS_SECRET, WORDPLUS_LOCAL_KEY
# What others see of a user: in presence, calls and the directory.
profile=lambda user: {"name": name_of(user), "avatar": avatar_of(user)},
worker="/static/realtime-worker.js",
rooms="/static/realtime-rooms.min.js",
)

# The room of an order: its customer may join, and the last 20 updates are kept.
realtime.room("order:{id}", lambda user, p: user is not None and owner_of(p["id"]) == user, history=20)

app = Flask(__name__)

# POST /api/realtime/auth, /calls and /keys, for the user of the session, and the webhook, which the realtime server signs.
@app.post("/api/realtime/<action>")
def realtime_route(action):
if action == "webhook":
path = request.path + ("?" + request.query_string.decode() if request.query_string else "")
status, body = realtime.webhook(request.get_data(), request.headers, path)
else:
status, body = realtime.answer_request(request.method, request.content_type or "", action, request.get_data(), session.get("user"))
return ("", 204) if status == 204 else (jsonify(body), status, {"Cache-Control": "no-store"})
  • The user is whatever id your app knows them by, an int or a str, or None: here the Flask session, or the Flask-Login current_user.get_id().
  • The pattern of a room names its parts: order:{id} matches order:1042, and the rule gets {"id": "1042"}.
  • The route takes JSON POSTs only. A page on another site cannot send JSON without asking first, and it is never allowed to, so the session cookie needs no CSRF token here (the Flask-WTF csrf.exempt for it, if you use CSRFProtect).
  • Another framework (Bottle, Pyramid, Falcon, Litestar) answers the same way: answer_request() and webhook() give (status, body).

4. The page​

@app.get("/orders/<int:pk>")
def order_page(pk):
return render_template("order.html", realtime=realtime.config(session.get("user")), pk=pk)
<!-- templates/order.html: tojson escapes it for a <script> -->
<script type="application/json" id="realtime">{{ realtime|tojson }}</script>
<script type="module" src="{{ url_for('static', filename='order.js') }}"></script>
// order.js, through your bundler (esbuild, Vite, webpack)
import { connect } from '@wordplus/realtime';

const rt = await connect( JSON.parse( document.getElementById( 'realtime' ).textContent ) );

const order = rt.join( 'order:1042' );
order.on( 'updated', ( data ) => showStatus( data.status ) );
order.on( 'error', ( e ) => console.warn( e.code ) ); // forbidden, no_rule …

5. Send​

After your own work is saved:

realtime.to("order:1042").emit("updated", {"status": "shipped"})

Everyone in the room gets { status }, sealed with the room key on the way, and a page that reconnects later gets it from the room history.

Next​