API Reference¶
This section of the documentation serves to provide a reference guide for developers, tinkerers, engieneers, and explorers for the Replit-py API, and showcases the function and method calls available within the library.
Core¶
The Replit Python module.
- replit.clear()¶
Clear the terminal.
- Return type:
None
Replit Web Framework & Utilities¶
Make apps quickly using Python.
- class replit.web.app.ReplitAuthContext(user_id, name, roles)¶
Bases:
object
A dataclass defining a Replit Auth state.
- classmethod from_headers(headers)¶
Initialize an instance using the Replit identification headers.
- Parameters:
headers (dict) – A dictionary of headers received
- Returns:
An initialized class instance
- Return type:
Any
- property is_authed: bool¶
Check whether the user is authenticated in with Replit Auth.
- Returns:
whether or not the authentication is activated.
- Return type:
bool
- property is_authenticated: bool¶
Check whether the user is authenticated in with Replit Auth.
- Returns:
whether or not the authentication is activated.
- Return type:
bool
-
name:
str
¶
-
roles:
str
¶
-
user_id:
int
¶
- replit.web.app.debug(app, watch_dirs=None, watch_files=None, **kwargs)¶
Run the app in debug mode. :type watch_dirs:
List
[str
] :param watch_dirs: Directories whose files will be added towatch_files. Defaults to [].
- Parameters:
watch_files (List[str]) – Files to watch, and if changes are detected the server will be restarted. Defaults to [].
**kwargs (Any) – Extra keyword arguments to be passed to the flask app’s run method.
- Return type:
None
- replit.web.app.run(app, host='0.0.0.0', port=8080, change_encoder=True, **kwargs)¶
A simple wrapper around app.run() with replit compatible defaults.
- Return type:
None
Utilities for working with user mappings.
- class replit.web.user.User(username, prefix='')¶
Bases:
MutableMapping
A user in the database, usually initialized by UserStore.
- db_key()¶
Returns the database key for this user.
- Return type:
str
- get(key, default=None)¶
Gets a value from the database if it exists, otherwise returns default.
- Parameters:
key (str) – The key to retrieve
default (Any) – The value to return if the key does not exist
- Returns:
The value of the key or default
- Return type:
Any
- prefix¶
- set(key, val)¶
Sets a key to a value for this user’s entry in the database.
- Parameters:
key (str) – The key to set
val (Any) – The value to set it to
- Return type:
None
- set_value(value)¶
Sets the raw value of this user in the database.
See set() and get() for a simpler dict based API. Will set the key prefix + username.
- Parameters:
value (str) – The value to set in the database
- Raises:
RuntimeError – Raised if the database is not configured.
- Return type:
None
- username¶
- class replit.web.user.UserStore(prefix='')¶
Bases:
Mapping
A mapping of username to keys in the replit database.
- prefix¶
Utilities to make development easier.
- replit.web.utils.authenticated(func=None, login_res='<!DOCTYPE html><html><head><title>Please Sign In</title></head><body><script authed="location.reload()" src="https://replit.com/public/js/repl-auth.js"></script></body></html>')¶
A decorator that enforces that the user is signed in before accessing the page.
- Parameters:
func (Callable) – The function passed in if used as a decorator. Defaults to None.
login_res (str) – The HTML to show when the user needs to sign in. Defaults to sign_in_snippet.
- Returns:
The new handler.
- Return type:
Callable
- replit.web.utils.authenticated_template(template, **context)¶
A decorator that renders a template if the user is not signed in.
- Parameters:
template (str) – The template filename to render.
**context (Any) – The context to pass to the template.
- Returns:
A decorator to apply to your route.
- Return type:
Callable
- replit.web.utils.find(data, cond, allow_multiple=False)¶
Find an item in an iterable.
- Parameters:
data (Iterable) – The iterable to search through.
cond (Callable[[Any], bool]) – The function to call for each item to check if it is a match.
allow_multiple (bool) – If multiple result are found, return the first one if allow_multiple is True, otherwise return None.
- Returns:
The item if exactly one match was found, otherwise None.
- Return type:
Optional[Any]
- replit.web.utils.local_redirect(location, code=302)¶
Perform a redirection to a local path without downgrading to HTTP.
- Parameters:
location (str) – The path to redirect to.
code (int) – The code to use for the redirect. Defaults to 302.
- Returns:
The redirect response.
- Return type:
flask.Response
- replit.web.utils.needs_sign_in(func=None, login_res='<!DOCTYPE html><html><head><title>Please Sign In</title></head><body><script authed="location.reload()" src="https://replit.com/public/js/repl-auth.js"></script></body></html>')¶
A decorator that enforces that the user is signed in before accessing the page.
- Parameters:
func (Callable) – The function passed in if used as a decorator. Defaults to None.
login_res (str) – The HTML to show when the user needs to sign in. Defaults to sign_in_snippet.
- Returns:
The new handler.
- Return type:
Callable
- replit.web.utils.params(*param_names, src='form', onerror=None)¶
Require paramaters before a handler can be activated.
- Parameters:
param_names (str) – The paramaters that must be in the request.
src (Union[str, dict]) – The source to get the paramaters from. Can be “form” to use flask.request.form (POST requests), “query” for flask.request.query (GET requests), or a custom dictionary.
onerror (Callable) – A function to handle when a paramater is missing. It will be passed the parameter that is missing. If no function is specified a handler that returns a descriptive error and 400 Bad Request status code will be used.
- Raises:
TypeError – No paramaters were provided or an invalid one was provided.
- Returns:
The new handler.
- Return type:
Callable
- replit.web.utils.per_user_ratelimit(max_requests, period, login_res='<!DOCTYPE html><html><head><title>Please Sign In</title></head><body><script authed="location.reload()" src="https://replit.com/public/js/repl-auth.js"></script></body></html>', get_ratelimited_res=<function <lambda>>)¶
Require sign in and limit the amount of requests each signed in user can perform.
- This decorator also calls needs_signin for you and passes the login_res kwarg
directly to it.
- Parameters:
max_requests (int) – The maximum amount of requests allowed in the period.
period (float) – The length of the period.
login_res (str) – The response to be shown if the user is not signed in, passed to needs_sign_in.
get_ratelimited_res (Callable[[float], str]) – A callable which is passed the amount of time remaining before the user can request again and returns the response that should be sent to the user.
- Returns:
A function which decorates the handler.
- Return type:
Callable[[Callable], flask.Response]
- replit.web.utils.sign_in(title='Please Sign In')¶
Return a sign-in page.
- Parameters:
title (str) – The title of the sign in page. Defaults to “Please Sign In”.
- Returns:
The sign-in page HTML.
- Return type:
str
- replit.web.utils.whoami()¶
Returns the username of the authenticated Replit user, else None.
- Return type:
Request
Replit DB¶
Interface with the Replit Database.
- class replit.database.AsyncDatabase(db_url, retry_count=5, get_db_url=None, unbind=None)¶
Bases:
object
Async interface for Replit Database.
- Parameters:
db_url (str) – The Database URL to connect to
retry_count (int) – How many retry attempts we should make
Callable (unbind) – A callback that returns the current db_url
Callable – Permit additional behavior after Database close
- client¶
- async close()¶
Closes the database client connection.
- Return type:
None
- db_url¶
- async delete(key)¶
Delete a key from the database.
- Parameters:
key (str) – The key to delete
- Raises:
KeyError – Key does not exist
- Return type:
None
- async get(key)¶
Return the value for key if key is in the database.
This method will JSON decode the value. To disable this behavior, use the get_raw method instead.
- Parameters:
key (str) – The key to retreive
- Returns:
The value for key if key is in the database.
- Return type:
str
- async get_raw(key)¶
Get the value of an item from the database.
- Parameters:
key (str) – The key to retreive
- Raises:
KeyError – Key is not set
- Returns:
The value of the key
- Return type:
str
- async items()¶
Convert the database to a dict and return the dict’s items method.
- Returns:
The items
- Return type:
Tuple[Tuple[str]]
- async keys()¶
Get all keys in the database.
- Returns:
The keys in the database.
- Return type:
Tuple[str]
- async list(prefix)¶
List keys in the database which start with prefix.
- Parameters:
prefix (str) – The prefix keys must start with, blank not not check.
- Returns:
The keys found.
- Return type:
Tuple[str]
- sess¶
- async set(key, value)¶
Set a key in the database to the result of JSON encoding value.
- Parameters:
key (str) – The key to set
value (Any) – The value to set it to. Must be JSON-serializable.
- Return type:
None
- async set_bulk(values)¶
Set multiple values in the database, JSON encoding them.
- Parameters:
values (Dict[str, Any]) – A dictionary of values to put into the dictionary. Values must be JSON serializeable.
- Return type:
None
- async set_bulk_raw(values)¶
Set multiple values in the database.
- Parameters:
values (Dict[str, str]) – The key-value pairs to set.
- Return type:
None
- async set_raw(key, value)¶
Set a key in the database to value.
- Parameters:
key (str) – The key to set
value (str) – The value to set it to
- Return type:
None
- async to_dict(prefix='')¶
Dump all data in the database into a dictionary.
- Parameters:
prefix (str) – The prefix the keys must start with, blank means anything. Defaults to “”.
- Returns:
All keys in the database.
- Return type:
Dict[str, str]
- update_db_url(db_url)¶
Update the database url.
- Parameters:
db_url (str) – Database url to use.
- Return type:
None
- async values()¶
Get every value in the database.
- Returns:
The values in the database.
- Return type:
Tuple[str]
- class replit.database.DBJSONEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)¶
Bases:
JSONEncoder
A JSON encoder that uses to_primitive on passed objects.
- default(o)¶
Runs to_primitive on the passed object.
- Return type:
Any
- class replit.database.Database(db_url, retry_count=5, get_db_url=None, unbind=None)¶
Bases:
MutableMapping
Dictionary-like interface for Replit Database.
This interface will coerce all values everything to and from JSON. If you don’t want this, use AsyncDatabase instead.
- Parameters:
db_url (str) – The Database URL to connect to
retry_count (int) – How many retry attempts we should make
Callable (unbind) – A callback that returns the current db_url
Callable – Permit additional behavior after Database close
- close()¶
Closes the database client connection.
- Return type:
None
- db_url¶
- dumps(val)¶
JSON encodes a value that can be a special DB object.
- Return type:
str
- get(key, default=None)¶
Return the value for key if key is in the database, else default.
Will replace the mutable JSON types of dict and list with subclasses that enable nested setting. These classes will block to request the DB on every mutation, which can have performance implications. To disable this, use the get_raw method instead.
This method will JSON decode the value. To disable this behavior, use the get_raw method instead.
- Parameters:
key (str) – The key to retreive
default (Any) – The default to return if the key is not the database. Defaults to None.
- Returns:
The the value for key if key is in the database, else default.
- Return type:
Any
- get_raw(key)¶
Look up the given key in the database and return the corresponding value.
- Parameters:
key (str) – The key to look up
- Raises:
KeyError – The key is not in the database.
- Returns:
The value of the key in the database.
- Return type:
str
- keys()¶
Returns all of the keys in the database.
- Returns:
The keys.
- Return type:
List[str]
- prefix(prefix)¶
Return all of the keys in the database that begin with the prefix.
- Parameters:
prefix (str) – The prefix the keys must start with, blank means anything.
- Returns:
The keys found.
- Return type:
Tuple[str]
- sess¶
- set(key, value)¶
Set a key in the database to value, JSON encoding it.
- Parameters:
key (str) – The key to set
value (Any) – The value to set.
- Return type:
None
- set_bulk(values)¶
Set multiple values in the database, JSON encoding them.
- Parameters:
values (Dict[str, Any]) – A dictionary of values to put into the dictionary. Values must be JSON serializeable.
- Return type:
None
- set_bulk_raw(values)¶
Set multiple values in the database.
- Parameters:
values (Dict[str, str]) – The key-value pairs to set.
- Return type:
None
- set_raw(key, value)¶
Set a key in the database to value.
- Parameters:
key (str) – The key to set
value (str) – The value to set.
- Return type:
None
- update_db_url(db_url)¶
Update the database url.
- Parameters:
db_url (str) – Database url to use.
- Return type:
None
- replit.database.dumps(val)¶
JSON encode a value in the smallest way possible.
Also handles ObservedList and ObservedDict by using a custom encoder.
- Parameters:
val (Any) – The value to be encoded.
- Returns:
The JSON string.
- Return type:
str
- replit.database.make_database_proxy_blueprint(view_only, prefix='')¶
Generates a blueprint for a database proxy.
- Parameters:
view_only (
bool
) – If False, database writing and deletion is enabled.prefix (
str
) – A prefix that all keys interacted with using this proxy will use.
- Returns:
A flask blueprint with the proxy logic.
- Return type:
Blueprint
- replit.database.start_database_proxy(view_only, prefix='', host='0.0.0.0', port=8080)¶
Starts the database proxy.
- Return type:
None
- replit.database.to_primitive(o)¶
If object is an observed object, converts to primitve, otherwise returns it.
- Parameters:
o (Any) – Any object.
- Returns:
- The primitive equivalent if o is an ObservedList or ObservedDict,
otherwise o.
- Return type:
Any
A module containing a database proxy implementation.
- replit.database.server.make_database_proxy_blueprint(view_only, prefix='')¶
Generates a blueprint for a database proxy.
- Parameters:
view_only (
bool
) – If False, database writing and deletion is enabled.prefix (
str
) – A prefix that all keys interacted with using this proxy will use.
- Returns:
A flask blueprint with the proxy logic.
- Return type:
Blueprint
- replit.database.server.start_database_proxy(view_only, prefix='', host='0.0.0.0', port=8080)¶
Starts the database proxy.
- Return type:
None
replit.info module¶
Information about your repl.
- class replit.info.ReplInfo¶
Bases:
object
Represents info about the current repl.
- property co_url: str | None¶
The readable, hosted repl.co URL for this repl.
See id_url for the difference between the hosted URL types.
- Returns:
The vanity hosted URL or None if slug or owner is None.
- Return type:
Optional[str]
- property id: str | None¶
The id of the repl (REPL_ID environment variable).
- property id_co_url: str | None¶
//<id>.id.repl.co.
Less readable than the vanity URL but guaranteed to work (the vanity URL might be too long for a certificate to be issued for it, causing it to break).
- Returns:
The id URL or None if there is no ID.
- Return type:
Optional[str]
- Type:
The hosted URL of the repl in the form https
- property language: str | None¶
The language of the repl (REPL_LANGUAGE environment variable).
- property owner: str | None¶
The owner of the repl (REPL_OWNER environment variable).
- property replit_id_url: str | None¶
The URL of this repl on replit.com, based on the repl’s ID.
- property replit_url: str | None¶
The URL of this repl on replit.com.
- property slug: str | None¶
The slug of the repl (REPL_SLUG environement variable).
The slug is the url-safe version of the repl’s name.
- Returns:
The repl slug.
- Return type:
Optional[str]