Client library reference

Everything the `pycorner` module exposes inside your Stlite app.

The pycorner module is injected into every preview’s Pyodide filesystem at pycorner.py. You don’t add it to requirements.txt; it’s just there.

pycorner.connect(name)

Open a logical “connection” to a Database resource. Returns a thin DB-API 2.0 facade.

db = pycorner.connect("proddb")
cur = db.cursor()
cur.execute("SELECT id, name FROM users WHERE active = %s", (True,))
rows = cur.fetchall()           # list of tuples
cols = [d[0] for d in cur.description]

Parameter style follows the driver: PostgreSQL and MySQL use %s.

pycorner.api(name)

Get a requests-like client for an API resource.

api = pycorner.api("stripe")

r = api.get("/v1/charges", params={"limit": 5})
r = api.post("/v1/refunds", json={"charge": "ch_..."})
r = api.put("/v1/things/42", json={"name": "renamed"})
r = api.patch("/v1/things/42", json={"name": "renamed"})
r = api.delete("/v1/things/42")
r = api.request("PATCH", "/v1/things/42", json={...}, headers={...})

The Response object exposes:

AttributeTypeMeaning
status_codeintUpstream HTTP status
headersdictUpstream response headers, except Set-Cookie (see APIs)
contentbytesRaw body bytes
textstrBody decoded as UTF-8
okbool200 ≤ status_code < 300
json()anyParses text as JSON

pycorner.tunnel

The Mode 3 (raw TCP) entry point. Three calls:

pycorner.tunnel.install()

Monkey-patches socket.create_connection so that connecting to any hostname matching one of your Tunnel resource names routes through a WebSocket-to-TCP bridge. Returns True on success, False if there’s nothing to intercept (no Tunnel resources in this preview’s scope) or the environment is missing SharedArrayBuffer.

pycorner.tunnel.install()
import pg8000.dbapi
conn = pg8000.dbapi.connect(host="proddb", port=5432, ..., ssl_context=False)

pycorner.tunnel.connect(name, port=0)

Lower-level: returns a raw _WsSocket for the named tunnel. Useful if you want bytes-level control or are doing something other than feeding it to pg8000/pymysql.

sock = pycorner.tunnel.connect("my-thing", port=4242)
sock.sendall(b"GET / HTTP/1.0\r\n\r\n")
data = sock.recv(1024)

pycorner.tunnel.reset()

Closes every live tunnel socket and removes the socket.create_connection monkey-patch. The next install() re-reads the current token and re-patches.

try:
    conn.cursor().execute("SELECT 1")
except Exception:
    pycorner.tunnel.reset()
    raise

pycorner.set_debug(enabled)

Toggles verbose per-byte send/recv + hex-dump logging to the browser console. Off by default (only important events log). The env var PYCORNER_DEBUG=1 does the same at import time.

pycorner.set_debug(True)

stlite-specific gotchas

A short cheat-sheet of the things that bite you the first time:

SymptomCauseFix
st.dataframe renders an empty boxstlite mocks pyarrowUse st.table(rows) or st.write(rows) instead.
pg8000.dbapi.connect → InterfaceError “SSL”pg8000 tries import ssl, fails in PyodidePass ssl_context=False.
ModuleNotFoundError: pycornerEditor hasn’t injected the file yet (race)Save the project once to force a fresh remount.
RuntimeError: PyCorner preview token missingRunning outside an editor previewOnly works inside a signed-in preview.
tunnel.install() returns False silentlyNo Raw TCP resources in this preview’s scopeCreate one (Resources → New Resource → Raw TCP), then re-save the project.
IncompleteRead(0 bytes) from urllibstlite’s urllib chunked-decode quirkUse pyodide.http.pyfetch directly. (pycorner.api(...) already does.)

Auth flow under the hood

The client lib reads a preview JWT from /_pycorner/token (the editor writes it at mount). Token claims include owner_id, project_id, tunnel_names, api_base, ws_base, and an 8-hour expiry. Every backend call carries the token; resource lookup happens server-side scoped to that token’s (owner, project).

When the editor remounts (any Save, or a hard refresh), it mints a fresh token. So if a long-running app outlives the 8-hour window, the next request will 401 — the simplest fix is to reload the editor; for fancier apps you can catch the 401 and surface a “your session expired, please reload” message.