### Run a Basic HTTP Server with Flask and Replit Source: https://github.com/replit/replit-py/blob/master/docs/web_tutorial.rst This snippet demonstrates how to set up a simple HTTP server using Flask and the replit.web library. It defines a root route that returns 'Hello, world!' and uses web.run() to start the server, making it accessible via a web browser. ```Python import flask from replit import web app = flask.Flask(__name__) @app.route("/") def index(): return "Hello, world!" web.run(app) ``` -------------------------------- ### Python Flask Web App Setup with Replit Source: https://github.com/replit/replit-py/blob/master/docs/web_tutorial.rst Sets up a basic Flask web application on Replit, including static file paths and a UserStore. This serves as the foundation for a Twitter clone. ```Python import flask from replit import db, web # -- Create & configure Flask application. app = flask.Flask(__name__) app.static_url_path = "/static" users = web.UserStore() @app.route("/") def index(): return "Hello" web.run(app) ``` -------------------------------- ### Import Replit Package Source: https://github.com/replit/replit-py/blob/master/docs/index.rst Demonstrates how to import the replit Python package to access its functionalities. This is the initial step for using any feature provided by the library. ```Python import replit ``` -------------------------------- ### Install replit-py with Poetry Source: https://github.com/replit/replit-py/blob/master/README.md This command installs the replit-py package using Poetry, a dependency management tool for Python. Ensure Poetry is set up in your development environment before running this command. ```shell poetry install ``` -------------------------------- ### Async Replit DB Operations (Python) Source: https://github.com/replit/replit-py/blob/master/docs/db_tutorial.rst Provides examples of using the asynchronous Replit Database client for non-blocking data operations. ```python from replit.database import AsyncDatabase db = AsyncDatabase() await db.set("a", "1") await db.get("a") # => "1" for i in await db.keys(): print(i) await db.delete("a") ``` -------------------------------- ### Get Feed of Tweets API Endpoint Source: https://github.com/replit/replit-py/blob/master/docs/web_tutorial.rst This Python code implements a GET route '/api/feed' to retrieve all tweets from all users. It iterates through users and their tweets, adding an 'author' field to each tweet. The tweets are then sorted by their timestamp in descending order (newest first) and returned as a JSON object. It relies on the 'users' dictionary and Replit's 'app' object. ```Python @app.route("/api/feed") def feed(): # The username is only stored as the key name, but the client # doesn't know the key name so add an author field to each tweet tweets = [] for name in users.keys(): for tweet in users[name].get("tweets", []): tweets.append({**tweet, "author": "name"}) # Sort by time, newest first tweets = sorted(tweets, key=(lambda t: t.get("ts", 0)), reverse=True) return {"tweets": tweets} ``` -------------------------------- ### Basic Replit DB Operations (Python) Source: https://github.com/replit/replit-py/blob/master/docs/db_tutorial.rst Demonstrates basic key-value storage, retrieval, listing, and deletion using the Replit Database client, mimicking Python dictionary behavior. ```python from replit import db db["key"] = 12 print(db["key"]) # => 12 db["a"] = 1 db["b"] = 2 print(db.keys()) # => {"a", "b"} del db["b"] print(db.keys()) # => {"a"} print(db.get("a")) # => 1 print(db.get("a key that does not exist", 57)) # => 57 print(db.pop("a")) # => 1 ``` -------------------------------- ### Async Bulk Set Operations (Python) Source: https://github.com/replit/replit-py/blob/master/docs/db_tutorial.rst Illustrates performing bulk set operations asynchronously with the Replit Database client using `set_bulk` and `set_bulk_raw`. ```python await db.set_bulk({"a": 1, "b": 2, "c": 3}) await db.get("c") # => 3 await db.set_bulk_raw({"d": '"abc"'}) await db.get("d") # => "abc" ``` -------------------------------- ### Prefix Key Search with Replit DB (Python) Source: https://github.com/replit/replit-py/blob/master/docs/db_tutorial.rst Shows how to retrieve keys from the Replit Database that match a specified prefix. ```python db["key1"] = 1 db["key2"] = 2 db["something else"] = 3 print(db.keys()) # => {"key1", "key2", "something else"} print(db.prefix("key")) # => ("key1", "key2") ``` -------------------------------- ### Bulk Set Operations with Replit DB (Python) Source: https://github.com/replit/replit-py/blob/master/docs/db_tutorial.rst Demonstrates efficient methods for setting multiple key-value pairs in the Replit Database using `set_bulk` and `set_bulk_raw`. ```python db.set_bulk({"a": 1, "b": 2}) print(db["a"]) # => 1 print(db["b"]) # => 2 db.set_bulk_raw({"c": '"c"', "d": '"d"'}) print(db["c"]) # => "c" print(db["d"]) # => "d" ``` -------------------------------- ### Async Raw Data Handling with Replit DB (Python) Source: https://github.com/replit/replit-py/blob/master/docs/db_tutorial.rst Demonstrates using `get_raw` and `set_raw` with the asynchronous Replit Database client to bypass JSON encoding/decoding. ```python await db.set("a", "val") await db.get_raw("a") # => '"val"' await db.set_raw("b", '"abc"') await db.get("b") # => "abc" ``` -------------------------------- ### Python Replit Authentication Decorator Source: https://github.com/replit/replit-py/blob/master/docs/web_tutorial.rst Demonstrates using the @web.authenticated decorator to enforce user sign-in for routes. Shows how to customize the login page message. ```Python @app.route("/") @web.authenticated def index(): return f"You are {web.auth.name}" ``` ```Python @app.route("/") # This step is optional, it is to demonstrate how the login page can be customized @web.authenticated(login_res = f"You are not signed in! {web.sign_in_snippet}") def index(): return f"You are {web.auth.name}" ``` -------------------------------- ### Handling Mutated Data with Replit DB (Python) Source: https://github.com/replit/replit-py/blob/master/docs/db_tutorial.rst Details methods like `dump` and `to_primitive` for handling mutated lists and dictionaries from the Replit Database, and the alternative of using `get_raw`/`set_raw`. ```python # Example usage of dump and to_primitive would go here, # but the provided text only describes their purpose. # To avoid this behavior entirely, use the get_raw and set_raw methods instead. ``` -------------------------------- ### Advanced Raw Data Handling (Python) Source: https://github.com/replit/replit-py/blob/master/docs/db_tutorial.rst Explains how to use `get_raw` and `set_raw` to bypass JSON encoding for specific use cases in the Replit Database client. ```python db["a"] = "string" db.get_raw("a") # => '"a"' db.set_raw("a", '"b"') db["a"] # => "b" ``` -------------------------------- ### Replit Web Framework & Utilities API Reference Source: https://github.com/replit/replit-py/blob/master/docs/api.rst Details the Replit Web Framework and its utilities. This includes references for the 'replit.web' module, 'replit.web.app', 'replit.web.user', and 'replit.web.utils', covering their members and inheritance. ```Python .. automodule:: replit.web :members: :undoc-members: :show-inheritance: ``` ```Python .. automodule:: replit.web.app :members: :undoc-members: :show-inheritance: ``` ```Python .. automodule:: replit.web.user :members: :undoc-members: :show-inheritance: ``` ```Python .. automodule:: replit.web.utils :members: :undoc-members: :show-inheritance: ``` -------------------------------- ### Mutating Data in Replit DB (Python) Source: https://github.com/replit/replit-py/blob/master/docs/db_tutorial.rst Illustrates how changes made to lists and dictionaries retrieved from the Replit Database are persisted. ```python db["user"] = {"score": 100} db["user"]["score"] += 100 print(db["user"]["score"]) # => 200 db["friends"] = ["Alice", "Bob"] db["friends"].append("Carol") print(db["friends"]) # => ["Alice", "Bob", "Carol"] ``` -------------------------------- ### Storing Various Data Types with Replit DB (Python) Source: https://github.com/replit/replit-py/blob/master/docs/db_tutorial.rst Shows how to store different JSON-compatible data types like numbers, null, lists, and dictionaries using the Replit Database client. ```python db["a number"] = 42 db["nothing"] = None db["a list"] = [1, 2, 3] db["a dictionary"] = {"a": 1} ``` -------------------------------- ### Replit Database API Reference Source: https://github.com/replit/replit-py/blob/master/docs/api.rst Provides reference for the Replit Database functionalities. This section covers the 'replit.database' and 'replit.database.server' modules, detailing their members and inheritance. ```Python .. automodule:: replit.database :members: :undoc-members: :show-inheritance: ``` ```Python .. automodule:: replit.database.server :members: :undoc-members: :show-inheritance: ``` -------------------------------- ### Upgrade Protobuf Definitions (Shell) Source: https://github.com/replit/replit-py/blob/master/DEVELOPMENT.md This script automates the upgrade of protobuf definitions. It downloads the latest protoc compiler, synchronizes API files from a specified directory, and then uses protoc to generate Python code from .proto files. It includes error handling and cleanup. ```shell #!/bin/bash set -e GOVAL_DIR="${GOVAL_DIR:-${HOME}/goval}" WORK_DIR="$(mktemp -d)" function cleanup { rm -rf "${WORK_DIR}" } trap cleanup EXIT # Download the latest protobuf binaries. curl -sSL https://github.com/protocolbuffers/protobuf/releases/download/v24.2/protoc-24.2-linux-x86_64.zip -o "${WORK_DIR}/protoc.zip" (cd "${WORK_DIR}" && unzip protoc.zip) mkdir -p "${WORK_DIR}/replit/goval" rsync \ -Lazr \ --exclude='api/npm' \ --include='*/' \ --include='*.proto' \ --exclude='*' \ "${GOVAL_DIR}/api" \ "${WORK_DIR}/replit/goval" find "${WORK_DIR}" -name '*.proto' | xargs sed -i 's@import "api/@import "replit/goval/api/@g' "${WORK_DIR}/bin/protoc" \ -I="${WORK_DIR}" \ --python_out=src/ \ "${WORK_DIR}/replit/goval/api/signing.proto" \ "${WORK_DIR}/replit/goval/api/client.proto" \ "${WORK_DIR}/replit/goval/api/repl/repl.proto" \ "${WORK_DIR}/replit/goval/api/features/features.proto" ``` -------------------------------- ### Run replit-py Unit Tests Source: https://github.com/replit/replit-py/blob/master/README.md This command executes the unit tests for the replit-py package using Python's unittest module. It requires specific environment variables to be set, which are dependent on a Replit internal testing environment. ```shell poetry run python -m unittest ``` -------------------------------- ### Python Replit Database User Visit Counter Source: https://github.com/replit/replit-py/blob/master/docs/web_tutorial.rst Implements a counter for user page visits using Replit's database. It retrieves the visit count, increments it, and stores it back. ```Python from replit import db, web @app.route("/") @web.authenticated def index(): hits = db.get(web.auth.name, 0) + 1 db[web.auth.name] = hits return f"You have visited this page {hits} times" ``` -------------------------------- ### Python Replit UserStore for User Data Source: https://github.com/replit/replit-py/blob/master/docs/web_tutorial.rst Utilizes Replit's UserStore to manage user-specific data, such as visit counts. Allows storing multiple values per user in a dictionary-like structure. ```Python users = web.UserStore() @app.route("/") @web.authenticated def index(): hits = users.current.get("hits", 0) + 1 users.current["hits"] = hits return f"You have visited this page {hits} times" ``` -------------------------------- ### Python Flask Replit Route Handling for Authentication Source: https://github.com/replit/replit-py/blob/master/docs/web_tutorial.rst Configures routes for signed-in and signed-out users in a Flask application on Replit. Includes a helper function to check moderator status. ```Python def is_mod(username): # Check whether a user has moderator priveleges return web.auth.name in ("Scoder12", "Your_username_here") # Landing page, only for signed out users @app.route("/") def index(): if web.auth.is_authenticated: return web.local_redirect("/home") return flask.render_template("index.html") # Home page, only for signed in users @app.route("/home") def home(): if not web.auth.is_authenticated: return web.local_redirect("/") return flask.render_template("home.html", name=web.auth.name, MOD=is_mod(web.auth.name)) ``` -------------------------------- ### Replit Info Module API Reference Source: https://github.com/replit/replit-py/blob/master/docs/api.rst Details the 'replit.info' module, providing reference for its members, undocumented members, and inheritance. This module likely contains information about the Replit environment. ```Python .. automodule:: replit.info :members: :undoc-members: :show-inheritance: ``` -------------------------------- ### Implement User-Specific Rate Limiting with replit-py Source: https://github.com/replit/replit-py/blob/master/docs/web_tutorial.rst This snippet demonstrates how to configure and apply a user-specific rate limiter using the `web.per_user_ratelimit` decorator from the replit-py library. It sets a limit of 60 requests per 60 seconds and defines custom JSON responses for unauthenticated users and users exceeding the limit. ```Python import json ratelimit = web.per_user_ratelimit( max_requests=60, period=60, login_res=json.dumps({"error": "Not signed in"}), get_ratelimited_res=( lambda time_left: json.dumps( {"error": f"Wait {time_left:.2f} sec before trying again."} ) ), ) @app.route("/api/tweet", methods=["POST"]) @ratelimit @web.params("body") def api_tweet(body): pass ``` -------------------------------- ### Add Replit Sign-In Button to HTML Source: https://github.com/replit/replit-py/blob/master/docs/web_tutorial.rst This snippet shows how to embed a 'Login With Replit' button into your HTML page by including the web.sign_in_snippet. This allows users to authenticate with their Replit account directly on your website. ```HTML else: return f"You are not signed in! {web.sign_in_snippet}" ``` -------------------------------- ### Replit Core API Reference Source: https://github.com/replit/replit-py/blob/master/docs/api.rst Provides reference for the core functionalities of the Replit-py API. This section details the members, undocumented members, and inheritance of the main 'replit' module. ```Python .. automodule:: replit :members: :undoc-members: :show-inheritance: ``` -------------------------------- ### Create Tweet API Endpoint Source: https://github.com/replit/replit-py/blob/master/docs/web_tutorial.rst This Python code defines a POST route '/api/tweet' to create a new tweet. It validates that the tweet body is not empty, creates a tweet dictionary with a timestamp and an empty likes list, and appends it to the current user's tweets. It requires the 'time' module and Replit's 'web' and 'app' objects. ```Python # add to imports: import time @app.route("/api/tweet", methods=["POST"]) @web.params("body") def api_tweet(body): if len(body) == 0: return {"error": "Cannot submit a blank tweet"}, 400 newtweet = dict(body=body, ts=int(time.time() * 1000), likes=[]) # Use .get() to handle missing keys users.current.get("tweets", []).append(newtweet) print(f"{web.auth.name} tweeted: {body!r}") return {"success": True} ``` -------------------------------- ### Replit API: Like Tweet Endpoint Source: https://github.com/replit/replit-py/blob/master/docs/web_tutorial.rst Handles POST requests to like or unlike a tweet. It validates the author and timestamp, finds the matching tweet, and updates the likes set. Handles adding and removing likes, ensuring uniqueness and preventing errors on unliking non-liked tweets. ```Python @app.route("/api/like", methods=["POST"]) @web.params("author", "ts", "action") def like(author, ts, action): # validate arguments if not ts.isdigit(): return {"error": "Bad ts"}, 400 ts = int(ts) if action not in ["like", "unlike"]: return {"error": "Invalid action"}, 400 tweet = find_matching_tweet(author, ts) if tweet is None: return {"error": "Tweet not found"}, 404 me = web.auth.name # Convert to a unique set so we can add and remove and prevent double liking likes = set(tweet.get("likes", [])) if action == "like": likes.add(me) else: likes.discard(me) tweet["likes"] = list(likes) verb = "liked" if action == "like" else "unliked" print(f"{me} {verb} {author}'s tweet, it now has {len(likes)} likes") return {"success": True} ``` -------------------------------- ### Python Project Dependencies (pip-compile) Source: https://github.com/replit/replit-py/blob/master/docs/requirements.txt This snippet details the Python package dependencies for a Replit project as generated by pip-compile. It lists packages like aiohttp, Flask, and Sphinx, along with their specific versions and transitive dependencies. ```Python # This file is autogenerated by pip-compile with Python 3.12 # by the following command: # # pip-compile # aiohappyeyeballs==2.4.6 # via aiohttp aiohttp==3.11.12 # via # -r requirements.in # aiohttp-retry aiohttp-retry==2.9.1 # via -r requirements.in aiosignal==1.3.2 # via aiohttp alabaster==1.0.0 # via sphinx argon2-cffi==23.1.0 # via pyseto argon2-cffi-bindings==21.2.0 # via argon2-cffi attrs==25.1.0 # via aiohttp babel==2.17.0 # via sphinx blinker==1.9.0 # via flask certifi==2025.1.31 # via requests cffi==1.17.1 # via # argon2-cffi-bindings # cryptography charset-normalizer==3.4.1 # via requests click==8.1.8 # via # flask # sphinx-click cryptography==44.0.1 # via pyseto docutils==0.21.2 # via # sphinx # sphinx-click flask==3.1.0 # via -r requirements.in frozenlist==1.5.0 # via # aiohttp # aiosignal idna==3.10 # via # requests # yarl imagesize==1.4.1 # via sphinx iso8601==2.1.0 # via pyseto itsdangerous==2.2.0 # via flask jinja2==3.1.6 # via # flask # sphinx markupsafe==3.0.2 # via # jinja2 # werkzeug multidict==6.1.0 # via # aiohttp # yarl packaging==24.2 # via sphinx propcache==0.3.0 # via # aiohttp # yarl protobuf==6.30.0rc1 # via -r requirements.in pycparser==2.22 # via cffi pycryptodomex==3.21.0 # via pyseto pygments==2.19.1 # via sphinx pyseto==1.8.2 # via -r requirements.in requests==2.32.4 # via # -r requirements.in # sphinx roman-numerals-py==3.0.0 # via sphinx snowballstemmer==2.2.0 # via sphinx sphinx==8.2.0 # via # sphinx-autodoc-typehints # sphinx-click sphinx-autodoc-typehints==3.1.0 # via -r requirements.in sphinx-click==6.0.0 # via -r requirements.in sphinxcontrib-applehelp==2.0.0 # via sphinx sphinxcontrib-devhelp==2.0.0 # via sphinx sphinxcontrib-htmlhelp==2.1.0 # via sphinx sphinxcontrib-jsmath==1.0.1 # via sphinx sphinxcontrib-qthelp==2.0.0 # via sphinx sphinxcontrib-serializinghtml==2.0.0 # via sphinx typing-extensions==4.12.2 # via -r requirements.in urllib3==2.5.0 # via # -r requirements.in # requests werkzeug==3.1.3 # via # -r requirements.in # flask yarl==1.18.3 # via aiohttp zipp==3.21.0 # via -r requirements.in ``` -------------------------------- ### Display User's Replit Auth Name Source: https://github.com/replit/replit-py/blob/master/docs/web_tutorial.rst This Python code snippet modifies the index route to check if a user is signed in using Repl Auth. If authenticated, it displays the user's name; otherwise, it indicates that the user is not signed in. ```Python @app.route("/") def index(): if web.auth.name: return f"You are {web.auth.name}" else: return "You are not signed in!" ``` -------------------------------- ### Find Tweet by Author and Timestamp Source: https://github.com/replit/replit-py/blob/master/docs/web_tutorial.rst This Python function, `find_matching_tweet`, searches for a specific tweet within a given author's tweets based on a provided timestamp. It returns the matching tweet if exactly one is found, otherwise, it returns None. This function is a helper for managing tweet likes. ```Python def find_matching_tweet(author, ts): matches = [t for t in users[author].get("tweets", []) if t.get("ts") == ts] if len(matches) == 1: return matches[0] else: return None ``` -------------------------------- ### Replit API: Delete Tweet Endpoint Source: https://github.com/replit/replit-py/blob/master/docs/web_tutorial.rst Handles POST requests to delete a tweet. It validates the author and timestamp, finds the tweet, and checks user permissions. Users can delete their own tweets, or any tweet if they are a moderator. ```Python @app.route("/api/delete", methods=["POST"]) @web.params("author", "ts") def delete(author, ts): if not ts.isdigit(): return {"error": "Bad ts"}, 400 ts = int(ts) tweet = find_matching_tweet(author, ts) if tweet is None: return {"error": "Tweet not found"}, 404 # Moderators bypass this check, they can delete anything if not is_mod() and author != web.auth.name: print( f"{web.auth.name!r} tried to delete tweet by {author!r}: Permission denied" ) return {"error": "Permission denied. This incident has been reported."}, 401 print(web.auth.name, "deleted a tweet by", author) users[author]["tweets"] = [ t for t in users[author].get("tweets", []) if t != tweet ] return {"success": True} ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.