replit-py

repository·master·Indexed 41 days ago

https://github.com/replit/replit-py

A Python library for interacting with Replit features, including a client for Replit DB (supporting both synchronous and AsyncDatabase interfaces), a Flask-based web framework with built-in user authentication (Repl Auth), and utilities for retrieving Repl metadata via the replit.info module.

Tokens
10.5K
Snippets
50
Records
59
Agent score
51%

What's inside replit-py

  1. Overview of the replit Python package

    master

    The replit Python package provides three core capabilities for developers working on the Replit platform:

    1. Replit DB Client and CLI: A fully-featured client and command-line interface for interacting with Replit's key-value database.
    2. Flask-based Web Framework: An application framework built on top of Flask designed to accelerate web development within the Replit environment.
    3. Repl Authentication: A library to facilitate authentication between different Repls.
    import replit
  2. Use Repl Auth to identify users

    master

    Repl Auth allows users to log into your site using their Replit account. You can access the current user's state via web.auth or web.request.auth.

    • web.auth.name: Returns the username of the authenticated user.
    • web.auth.is_authenticated: A boolean indicating if the user is signed in.
    • web.sign_in_snippet: An HTML snippet containing a "Login With Replit" button. Include this in your HTML to allow users to sign in.

    Note: Repl Auth may not work in Safari due to cookie restrictions; ensure cookie blockers are disabled on replit.com.

    @app.route("/")
    def index():
        if web.auth.name:
            return f"You are {web.auth.name}"
        else:
            return f"You are not signed in! {web.sign_in_snippet}"
  3. Handling ObservedList and ObservedDict

    master

    To support in-place mutation, the database client uses special classes: replit.database.database.ObservedList and replit.database.database.ObservedDict.

    When working with these objects:

    • To JSON encode them: Use replit.database.dump(obj).
    • To convert to primitive Python types: Access the .value attribute or use the helper function replit.database.to_primitive(obj).
    • To avoid these classes entirely: Use get_raw and set_raw methods.
  4. Quickstart with the Replit Database (Sync API)

    master

    The Replit Database can be used like a standard Python dictionary. It uses JSON internally, allowing you to store any JSON-compatible type (numbers, strings, lists, dictionaries, None).

    Key features include:

    • Dictionary Interface: Use db[key] = value, del db[key], db.get(key), and db.pop(key).
    • Key Management: Use db.keys() to list keys and db.prefix(prefix) to find keys starting with a specific string.
    • In-place Mutation: You can mutate lists or dictionaries retrieved from the database, and changes will be automatically persisted to the database.
    from replit import db
    
    # Basic CRUD
    db["key"] = 12
    print(db["key"]) # => 12
    
    # Key management
    db["a"] = 1
    db["b"] = 2
    print(db.keys()) # => {"a", "b"}
    
    # Prefix search
    print(db.prefix("key")) # => ("key1", "key2")
    
    # Automatic mutation persistence
    db["user"] = {"score": 100}
    db["user"]["score"] += 100
    print(db["user"]["score"]) # => 200
    
    # List mutation
    db["friends"] = ["Alice", "Bob"]
    db["friends"].append("Carol")
    print(db["friends"]) # => ["Alice", "Bob", "Carol"]
  5. Run the Replit CLI

    master

    The Replit CLI can be invoked directly using the replit command. If the command is not found in your system's PATH, you can run it as a Python module using python -m replit.

    # Standard invocation
    replit
    
    # Fallback if 'replit' is not in PATH
    python -m replit
  6. Implement a JSON feed API route

    master

    To create an API endpoint that returns data (like a list of tweets) in JSON format, define a route using @app.route. When iterating through data to prepare it for a client, you can use dictionary unpacking ({**original, **new_fields}) to add metadata (like an author field) to objects without modifying the underlying database records.

    @app.route("/api/feed")
    def feed():
        tweets = []
        for name in users.keys():
            for tweet in users[name].get("tweets", []):
                # Use unpacking to add 'author' without mutating the original tweet in the DB
                tweets.append({**tweet, "author": name})
    
        # Sort by timestamp (ts), newest first
        tweets = sorted(tweets, key=(lambda t: t.get("ts", 0)), reverse=True)
    
        return {"tweets": tweets}
  7. Get started with replit web and Flask

    master

    The replit.web library provides utilities for running web servers on Replit, specifically designed to work with the Flask framework. You can start a server using web.run(app), which automatically handles host and port configurations suitable for the Replit environment.

    To run in debug mode, use web.debug(app).

    import flask
    from replit import web
    
    app = flask.Flask(__name__)
    
    @app.route("/")
    def index():
        return "Hello, world!"
    
    web.run(app)
  8. Async usage with `AsyncDatabase`

    master

    For asynchronous applications, use replit.database.AsyncDatabase. The API is similar to the synchronous version but requires await for most operations.

    Note: Dictionary-style access (e.g., db["key"]) and nested mutation (e.g., db["user"]["score"] += 1) are only available in the synchronous library. In the async library, you must use explicit await db.set() and await db.get() calls.

    from replit.database import AsyncDatabase
    
    db = AsyncDatabase()
    
    await db.set("a", "1")
    val = await db.get("a") # => "1"
    
    for i in await db.keys():
        print(i)
    
    await db.delete("a")
  9. How SigningAuthority prevents identity spoofing

    master

    The SigningAuthority implements a mechanism to prevent 'token forwarding' attacks. When you call .sign(audience), the resulting token is cryptographically bound to the specific audience (the target Repl ID).

    If a recipient attempts to forward this token to a different Repl, the verification will fail because the aud (audience) field in the signed identity will not match the new recipient's ID. This ensures that a token intended for Repl A cannot be used to impersonate you to Repl B.

  10. How ObservedDict and ObservedList work for nested mutations

    master

    When you retrieve a dictionary or list from the Database (sync) or AsyncDatabase (async) via get() or __getitem__, the library returns ObservedDict or ObservedList objects.

    These objects wrap the underlying data and trigger a mutation handler whenever the object is modified (e.g., via __setitem__, insert, or __delitem__). This allows for 'transparent' nested updates where modifying a nested field automatically synchronizes that change back to the Replit Database.

  11. Redirect users locally with web.local_redirect

    master

    Use web.local_redirect(path) to perform a redirect within your application. This is useful for routing users based on their authentication state (e.g., redirecting signed-in users away from a landing page to a home page).

    @app.route("/")
    def index():
        if web.auth.is_authenticated:
            return web.local_redirect("/home")
        return flask.render_template("index.html")