Full API Documentation

This full API documentation is provided for those who want to understand the internals of Drafter and potentially contribute to the project. If you are looking for user documentation, please refer to the Student Documentation.

class Server(_custom_name=None, **kwargs)

Represents a server capable of managing routes, states, configurations, and error handling while supporting application setup and runtime logic.

This class allows the definition of web routes, manages application states, handles errors gracefully, and provides a framework for deploying a web application with a structured configuration and support for image serving. It integrates with the Bottle framework to handle HTTP requests and responses.

Variables:
  • routes – A dictionary mapping URLs to their respective handler functions.

  • _handle_route – Internal mapping for handler functions and their respective URLs.

  • configuration – The configuration object representing server settings.

  • _state – Current state of the application.

  • _initial_state – Serialized representation of the initial application state.

  • _initial_state_type – Type of the initial state.

  • _state_history – List tracking historical states of the application.

  • _state_frozen_history – List storing serialized snapshots of historical states.

  • _page_history – History of visited pages.

  • _conversion_record – Internal record tracking parameter conversion processes.

  • original_routes – List containing tuples of original route URLs and their handlers.

  • app – The Bottle application instance for handling HTTP requests.

  • _custom_name – Custom name for the server instance, used in string representations.

add_route(url, func)

Adds a route to the routing table for URL handling, ensuring the URL is unique and maps a function to the given route. Prepares the URL, processes the function into a valid callable, and stores the mapping for later resolution when the URL is accessed.

Parameters:
  • url (str) – The URL string to be added as a route. It must be unique.

  • func (Callable) – The function to be associated with the provided URL. This function will be called when the route is accessed.

Raises:

ValueError – If the URL is already registered for another function.

Returns:

None

clear_routes()

Clears all stored routes from the routes attribute.

This method removes all data within the routes attribute, resetting it back to its empty state. Use this when you want to remove all previous route configurations or stored paths within the object.

convert_parameter(param, val, expected_types)

Converts a given parameter value to a specified target type if possible, based on the expected types provided. Records successful conversions, unchanged parameters, and failed conversion attempts with detailed information.

Parameters:
  • param (str) – The name of the parameter to be converted.

  • val (Any) – The value of the parameter to be converted.

  • expected_types (dict) – A dictionary containing the expected types for all parameters. The key is the parameter name, and the value is its expected type. If a parameter does not require conversion, its value is set to inspect.Parameter.empty.

Returns:

The converted value of the parameter if a conversion is successful; otherwise, the original value of the parameter.

Return type:

Any

Raises:

ValueError – If the value cannot be converted to its specified expected type, providing detailed information about the attempted conversion.

dump_state()

Converts the current internal state of the State object into a JSON-encoded string. The internal state must be dehydratable using the provided utility function dehydrate_json.

Raises:
  • TypeError – If any part of the internal state cannot be serialized into JSON due to invalid types.

  • ValueError – If serialization encounters unexpected value constraints or data inconsistencies.

Returns:

A JSON string capturing the serialized format of the object’s state.

Return type:

str

flash_warning(message)

This method displays a warning message. It is intended for immediate output to notify the user of a specific warning or issue.

TODO: This should actually append to a list that gets shown in the debug area.

Parameters:

message (str) – The warning message to be displayed to the user.

Returns:

None

handle_images()

Handles the serving of images when the deploy_image_path is configured. This method maps a dynamic route to serve image files by their paths, allowing them to be accessed through the defined route.

Raises:

AttributeError – If self.configuration.deploy_image_path or its attributes are not properly configured.

Returns:

None

load_from_state(state, state_type)

Loads a specific State object from a serialized state based on the given state type. This method takes a serialized JSON string representation of a state and rehydrates it into the corresponding Python object according to the given state type.

Parameters:
  • state (str) – The serialized JSON string representation of the object state.

  • state_type (Type) – The class or data type to rehydrate the JSON state into.

Returns:

The rehydrated Python object based on the state and state_type.

Return type:

Any

make_bottle_page(original_function)

A decorator that wraps a given function to create and manage a Bottle web page environment. This includes processing request parameters, building the page, verifying its content, and rendering it to the client. It also maintains state and history for the page creation and execution process.

Parameters:

original_function – The original callable function to be wrapped and executed to construct the page.

Returns:

A wrapped function that, when called, executes the original function within the Bottle page handling logic.

make_debug_page()

Generates a debug page by gathering and processing various internal states and informational data.

This method collects the page history, current state, routes, configuration, and conversion record to create a representation of a debug page. It utilizes these components to generate a structured output that represents the debug information.

Returns:

Debug information page content generated based on the current internal state and history of the application.

Return type:

str

make_error_page(title, error, original_function, additional_details='')

Generates and displays a detailed error page upon encountering an issue in the application.

This function formats a detailed error message by including the title of the error, the original function’s name where the error occurred, the original error’s message, and any additional details if provided. It also escapes potentially unsafe HTML characters from the error details and traceback to improve security. The formatted message is then displayed with an HTTP 500 Internal Server Error status.

Parameters:
  • title (str) – A brief, descriptive title for the error (e.g., “Server Error”).

  • error (Exception) – The original error/exception that was encountered.

  • original_function (Callable) – The function object where the error originated.

  • additional_details (str) – Optional additional information or context about the error. Defaults to an empty string.

Returns:

Does not return any value as it raises an HTTP 500 error with the formatted message.

Return type:

None

prepare_args(original_function, args, kwargs)

Processes and prepares arguments for the route function call, ensuring compatibility with expected parameters, handling state insertion, remapping parameters, and performing type conversion when necessary.

Parameters:
  • original_function – The function whose parameters are being prepared.

  • args – The positional arguments to be passed to the function.

  • kwargs – The keyword arguments to be passed to the function.

Returns:

A tuple containing: - Processed positional arguments matching the expected parameters of the

function.

  • Processed keyword arguments matching the expected parameters of the function.

  • A string representation of the final arguments for logging or debugging.

  • The button pressed if detected and processed.

reset()

Resets the current State object to its initial configuration and clears all recorded histories. After resetting, the function returns the result of the route mapped to ‘/’ (the root index URL).

Returns:

The result of the ‘/’ route execution.

Return type:

Page

restore_state_if_available(original_function)

Restores the state if the necessary data is available in the parameters. This function checks for the presence of a specific key in the parameters and, when available, rehydrates the serialized state back to the appropriate type and assigns it to the current instance’s state.

Parameters:

original_function – The function whose state is being restored. This function must have a parameter named state with an associated type annotation.

Returns:

None

run(**kwargs)

Executes the server application using the provided configuration. The method will update the configuration with any additional keyword arguments provided and start the server application with the updated configuration.

Parameters:

kwargs – Arbitrary keyword arguments containing configuration updates. Only keys that match the ServerConfiguration fields will be applied.

Returns:

None. The server application is started with the updated configuration.

serve_image(path)

Serves an image file located in the specified directory with the MIME type image/png. The method retrieves the image from the path provided, using the configured source image folder as the root directory.

Parameters:

path (str) – The relative path to the image file within the source image folder.

Returns:

The static file object representing the requested image.

Return type:

static_file

setup(initial_state=None)

Initializes and configures the application. Sets up initial state, error pages, and application routes for handling requests.

Parameters:

initial_state (Any) – The initial state to set up the application.

test_deployment()

Bundles files necessary for deployment, including the source code identified by the “start_server” line in the student’s main file. This allows the server to “deploy” a local version of the application, as it would appear on a live server using Skulpt.

This function searches for the entry point of the student’s application and attempts to bundle it with all its associated files into a deployable format. If the main file cannot be located, it returns an error indicating the failure to find the required file. Otherwise, it creates a bundled JavaScript version of the required files and integrates them with the appropriate configurations for deployment.

Raises:
  • ValueError – If the student’s main file cannot be located.

  • IOError – If there are issues during the file bundling process.

Returns:

HTML template string formatted with bundled JavaScript and CDN configurations.

Return type:

str

try_special_conversions(value, target_type)

Attempts to convert the input value to the specified target type using various specialized conversion methods. This method is designed to handle specific types of input, such as bottle.FileUpload, supporting conversion to bytes, string, dictionary, and, if available, PIL.Image.

Parameters:
  • value (Any) – The input value to be converted. Typically, this is expected to be an instance of bottle.FileUpload.

  • target_type (type) – The desired type to convert the input value to. This can include types such as bytes, str, dict, or others, depending on the availability of appropriate conversion logic.

Returns:

The converted value as an instance of the specified target type. If no special conversion logic applies, the original value is passed to the target type directly for conversion.

Return type:

Any

Raises:

ValueError – If the method encounters an error during conversion, such as failure to decode file content as UTF-8, or if a file cannot be opened as an image using PIL.Image when HAS_PILLOW is True.

verify_page_result(page, original_function)

Verifies the result of a function execution to ensure it returns a valid Page object. The verification checks whether the returned result is of type Page and whether its structure adheres to the expected format. If the validation fails, an error message is generated and returned.

Parameters:
  • page (Union[None, str, list, Any]) – The object returned by the endpoint method to be verified.

  • original_function (Callable) – A reference to the function or method where the Page object is expected to be returned from.

Returns:

Returns either a valid Page object or an error page with diagnostic information when the verification process fails.

Return type:

Optional[Page]

verify_page_state_history(page, original_function)

Validates the consistency of the state object’s type in the provided page against the most recent state stored in the self._state_history. If any discrepancy is found in the type of the state object, it constructs an error message highlighting the inconsistency and generates an error page.

Parameters:
  • page – The page object containing the state to be verified.

  • original_function – The name of the function that created the page.

Returns:

Returns an error page if a validation issue arises, otherwise none.

wrap_page(content)

Wraps provided content in a styled HTML template, applying additional headers, scripts, styles, and any configuration-specific content.

Parameters:

content (str) – The content to be wrapped in the HTML template.

Raises:

ValueError – If the specified style in the configuration is not found in the list of included styles.

Returns:

A fully formatted HTML string, including necessary headers, styles, scripts, and the provided content wrapped according to the configuration and selected style.

Return type:

str

bundle_files_into_js(main_file, root_path, allowed_extensions=('py', 'js', 'css', 'txt', 'json', 'csv', 'html', 'md'))

Bundles all files from a specified directory into a JavaScript-compatible format for Skulpt, a Python-to-JavaScript transpiler. The function traverses through the given directory, reads files with extensions present in the allowed extensions list, and aggregates them into a JavaScript code snippet. It also identifies files to be skipped and keeps a record of successfully added files.

Parameters:
  • main_file (str) – The path to the main Python file. This file will be labeled as “main.py” in the JavaScript output.

  • root_path (str) – The root directory to search for files.

  • allowed_extensions (set[str]) – A collection of file extensions allowed for inclusion in the final JavaScript output. Defaults to a predefined set.

Returns:

A tuple containing: - The combined JavaScript output string with file contents. - A list of skipped files that do not match the allowed extensions. - A list of added files that were successfully bundled.

Return type:

tuple[str, list[str], list[str]]

get_all_routes(server: Server | None = None)

Get all routes available in the given server or the main server if none is provided.

If the server parameter is not specified, the function retrieves the main server using the get_main_server() function and returns its list of routes.

Parameters:

server (Optional[Server]) – An optional Server instance. If provided, the method will retrieve routes specific to this server. If omitted, it defaults to the main server.

Returns:

Returns a list of routes from the provided or default main server.

get_main_server() Server

Gets the main server. This is useful for testing purposes.

Returns:

The main server

get_server_setting(key, default=None, server=MAIN_SERVER)

Gets a setting from the server’s configuration. If the setting is not found, the default value is returned.

Parameters:
  • key – The key to look up in the configuration

  • default – The default value to return if the key is not found

  • server – The server to look up the setting in (defaults to the MAIN_SERVER)

Returns:

The value of the setting, or the default value if not found

set_main_server(server: Server)

Sets the main server to the given server. This is useful for testing purposes.

Parameters:

server – The server to set as the main server

Returns:

None

start_server(initial_state=None, server: Server = MAIN_SERVER, skip=False, **kwargs)

Starts the server with the given initial state and configuration. If the server is set to skip, it will not start. Additional keyword arguments will be passed to the server’s run method, and therefore to Bottle. This can be used to control things like the port.

Parameters:
  • initial_state – The initial state to start the server with

  • server – The server to run on, defaulting to MAIN_SERVER

  • skip – If True, the server will not start; this is useful for running tests headlessly

  • kwargs – Additional keyword arguments to pass to the server’s run method. See below.

Returns:

None

Keyword Arguments:
  • port (int) – The port to run the server on. Defaults to 8080

class BakeryTestCase(args: tuple, kwargs: dict, result: Any, line: int, caller: str)
assert_equal(*args, **kwargs)

Pointless definition of assert_equal to avoid errors

diff_tests(left, right, left_name, right_name)

Compare two strings and show the differences in a table.

route(url: Callable | str | None = None, server: Server | None = None)

Main function to add a new route to the server. Recommended to use as a decorator. Once added, the route will be available at the given URL; the function name will be used if no URL is provided. When you go to the URL, the function will be called and its return value will be displayed.

Parameters:
  • url – The URL to add the route to. If None, the function name will be used.

  • server – The server to add the route to. Defaults to the main server.

Returns:

The modified route function.

class Page(state, content=None)

A page is a collection of content to be displayed to the user. This content has two critical parts:

  • The state, which is the current value of the backend server for this user’s session. This is used to restore the state of the page when the user navigates back to it. Typically, this will be a dataclass or a dictionary, but could also be a list, primitive value, or even None.

  • The content, which is a list of strings and components that will be rendered to the user.

The content of a page can be any combination of strings and components. Strings will be rendered as paragraphs, while components will be rendered as their respective HTML. Components should be classes that inherit from drafter.components.PageContent. If the content is not a list, a ValueError will be raised.

Parameters:
  • state – The state of the page. If only one argument is provided, this will default to be None.

  • content – The content of the page. Must always be provided as a list of strings and components.

make_reset_button() str

Creates a reset button that has the “reset” icon and title text that says “Resets the page to its original state.”. Simply links to the “–reset” URL.

Returns:

A string of HTML representing the reset button.

render_content(current_state, configuration: ServerConfiguration) str

Renders the content of the page to HTML. This will include the state of the page, if it is restorable. Users should not call this method directly; it will be called on their behalf by the server.

Parameters:
  • current_state – The current state of the server. This will be used to restore the page if needed.

  • configuration – The configuration of the server. This will be used to determine how the page is rendered.

Returns:

A string of HTML representing the content of the page.

verify_content(server) bool

Verifies that the content of the page is valid. This will check that all links are valid and that all components are valid. This is not meant to be called by the user; it will be called by the server.

Parameters:

server – The server to verify the content against.

Returns:

True if the content is valid, False otherwise.

class ConversionRecord(parameter: str, value: Any, expected_type: Any, converted_value: Any)
class UnchangedRecord(parameter: str, value: Any, expected_type: Any = None)
class VisitedPage(url: str, function: Callable, arguments: str, status: str, button_pressed: str, original_page_content: Optional[str] = None, old_state: Any = None, started: datetime.datetime = <factory>, stopped: Optional[datetime.datetime] = None)
add_website_css(selector: str, css: str | None = None)

Adds additional CSS content to the website. This is useful for adding custom CSS to the website, either for specific selectors or for general styles. If you only provide one parameter, it will be wrapped in <style> tags. If you provide both parameters, they will be used to create a CSS rule; the first parameter is the CSS selector, and the second parameter is the CSS content that will be wrapped in {}.

Parameters:
  • selector – The CSS selector to apply the CSS to, or the CSS content if the second parameter is None.

  • css – The CSS content to apply to the selector.

add_website_header(header: str)

Adds additional header content to the website. This is useful for adding custom CSS or JavaScript to the website, or other arbitrary header tags like meta tags.

Parameters:

header – The raw header content to add. This will not be wrapped in additional tags.

default_index(state) Page

The default index page for the website. This will show a simple “Hello world!” message. You should not modify or use this function; instead, create your own index page.

deploy_site(image_folder='images')

Deploys the website with the given image folder. This will set the production flag to True and turn off debug information, too.

Parameters:

image_folder – The folder where images are stored.

hide_debug_information()

Hides debug information from the website, so that it will not appear. Useful for deployed websites.

set_website_framed(framed: bool)

Sets whether the website should be framed or not. If you are deploying the website, then this would be a common thing to set to False.

Parameters:

framed – Whether the website should be framed or not.

set_website_style(style: str | None)

Sets the style of the website. This is a string that will be used to determine the CSS style of the website from the available styles (e.g., skeleton, bootstrap). This list will be expanded in the future.

Parameters:

style – The style of the website.

set_website_title(title: str)

Sets the title of the website, as it appears in the browser tab.

Parameters:

title – The title of the website.

show_debug_information()

Shows debug information on the website. Useful for development.

class DebugInformation(page_history: List[Tuple[drafter.history.VisitedPage, Any]], state: Any, routes: Dict[str, Callable], conversion_record: List[drafter.history.ConversionRecord], configuration: drafter.configuration.ServerConfiguration)

TODO: Custom Error pages Shareable link to get a link to the current page Download/upload state button

class ServerConfiguration(host: str = 'localhost', port: int = 8080, debug: bool = True, backend: str = 'bottle', reloader: bool = False, skip: bool = False, title: str = 'Drafter Website', framed: bool = True, skulpt: bool = False, style: str = 'skeleton', additional_header_content: ~typing.List[str] = <factory>, additional_css_content: ~typing.List[str] = <factory>, src_image_folder: str = '', save_uploaded_files: bool = True, deploy_image_path: str = 'images', cdn_skulpt: str = 'https://drafter-edu.github.io/drafter-cdn/skulpt/skulpt.js', cdn_skulpt_std: str = 'https://drafter-edu.github.io/drafter-cdn/skulpt/skulpt-stdlib.js', cdn_skulpt_drafter: str = 'https://drafter-edu.github.io/drafter-cdn/skulpt/skulpt-drafter.js', cdn_drafter_setup: str = 'https://drafter-edu.github.io/drafter-cdn/skulpt/drafter-setup.js')

Configuration for the server.

class Argument(name: str, value: Any, **kwargs)
Box

alias of Div

class BulletedList(items: List[Any], **kwargs)
class Button(text: str, url: str, arguments=None, **kwargs)
class CheckBox(name: str, default_value: bool = False, **kwargs)
class Div(*args, **kwargs)
Division

alias of Div

class Download(text: str, filename: str, content: str, content_type: str = 'text/plain')
class FileUpload(name: str, accept: str | List[str] | None = None, **kwargs)

A file upload component that allows users to upload files to the server.

This works by creating a hidden input field that stores the file data as a JSON string. That input is sent, but the file data is not sent directly.

The accept field can be used to specify the types of files that can be uploaded. It accepts either a literal string (e.g. “image/*”) or a list of strings (e.g. [“image/png”, “image/jpeg”]). You can either provide MIME types, extensions, or extensions without a period (e.g., “png”, “.jpg”).

To have multiple files uploaded, use the multiple attribute, which will cause the corresponding parameter to be a list of files.

class Header(body: str, level: int = 1)
class HorizontalRule
class Image(url: str, width=None, height=None, **kwargs)
render(current_state, configuration)

This method is called when the component is being rendered to a string. It should return the HTML representation of the component, using the current State and configuration to determine the final output.

Parameters:
  • current_state (Any) – The current state of the component

  • configuration (Configuration) – The configuration settings for the component

Returns:

The HTML representation of the component

class LineBreak
class LinkContent

Represents content for a hyperlink.

This class encapsulates the URL and display text of a link. It provides utility methods for verifying the URL, handling its structure, and processing associated arguments.

Variables:
  • url – The URL of the link.

  • text – The display text of the link.

class MatPlotLibPlot(extra_matplotlib_settings=None, close_automatically=True, **kwargs)
class NumberedList(items: List[Any], **kwargs)
class PageContent

Base class for all content that can be added to a page. This class is not meant to be used directly, but rather to be subclassed by other classes. Critically, each subclass must implement a __str__ method that returns the HTML representation.

Under most circumstances, a string value can be used in place of a PageContent object (in which case we say it is a Content type). However, the PageContent object allows for more customization and control over the content.

Ultimately, the PageContent object is converted to a string when it is rendered.

This class also has some helpful methods for verifying URLs and handling attributes/styles.

parse_extra_settings(**kwargs)

Parses and combines extra settings into valid attribute and style formats.

This method processes additional configuration settings provided via arguments or stored in the extra_settings property, converts them into valid HTML attributes and styles, and then consolidates the processed values into the appropriate output format. Attributes not explicitly defined in the baseline or extra attribute lists are converted into inline style declarations.

Parameters:

kwargs – Arbitrary keyword arguments containing extra configuration settings to be applied or overridden. The keys represent attribute or style names, and the values represent their corresponding values.

Returns:

A string containing formatted HTML attributes along with an inline style block if any styles are provided.

Return type:

str

render(current_state, configuration)

This method is called when the component is being rendered to a string. It should return the HTML representation of the component, using the current State and configuration to determine the final output.

Parameters:
  • current_state (Any) – The current state of the component

  • configuration (Configuration) – The configuration settings for the component

Returns:

The HTML representation of the component

update_attr(attr, value)

Updates a specific attribute with the given value in the extra_settings dictionary.

This method modifies the extra_settings dictionary by setting the specified attribute to the given value. It returns the instance of the object, allowing for method chaining. No validation is performed on the input values, so they should conform to the expected structure or constraints of the extra_settings.

Parameters:
  • attr (str) – The key of the attribute to be updated in the dictionary.

  • value (Any) – The value to set for the specified key in the dictionary.

Returns:

The instance of the object after the update.

Return type:

Self

update_style(style, value)

Updates the style of a specific setting and stores it in the extra_settings dictionary with a key formatted as “style_{style}”.

Parameters:
  • style (str) – The key representing the style to be updated

  • value (Any) – The value to associate with the given style key

Returns:

Returns the instance of the object after updating the style

Return type:

self

verify(server) bool

Verify the status of this component. This method is called before rendering the component to ensure that the component is in a valid state. If the component is not valid, this method should return False.

Default implementation returns True.

Parameters:

server – The server object that is rendering the component

Returns:

True if the component is valid, False otherwise

Picture

alias of Image

class Pre(*args, **kwargs)
PreformattedText

alias of Pre

class Row(*args, **kwargs)
class SelectBox(name: str, options: List[str], default_value: str | None = None, **kwargs)
class Span(*args, **kwargs)
SubmitButton

alias of Button

class Table(rows: List[List[str]], header=None, **kwargs)
class Text(body: str, **kwargs)
class TextArea(name: str, default_value: str | None = None, **kwargs)
class TextBox(name: str, default_value: str | None = None, kind: str = 'text', **kwargs)
make_safe_argument(value)

Encodes the given value into JSON format and escapes any special HTML characters to ensure the argument is safe for use in HTML contexts.

This function is particularly useful in scenarios where you need to serialize a Python object into JSON, while making sure that the output is safe to insert into an HTML document, protecting against potential HTML injection attacks.

Parameters:

value (Any) – Any Python object that needs to be converted to a JSON string and HTML escaped.

Returns:

A string containing the HTML-escaped and JSON-encoded representation of the input value.

Return type:

str

make_safe_json_argument(value)

Converts the given value to a JSON-compatible string and escapes special HTML characters, making it safe for inclusion in HTML contexts.

Parameters:

value – The input value to be converted and escaped. The value can be of any type that is serializable to JSON.

Returns:

An HTML-safe JSON string representation of the input value.

make_safe_name(value)

This function takes a value as input and generates a safe string version of it by escaping special characters to prevent injection attacks or unintended HTML rendering. It ensures that the provided input is safely transformed into an escaped HTML string.

Parameters:

value (Any) – The input value to be escaped. It is converted to a string if it is not already.

Returns:

The escaped HTML version of the input value as a string.

Return type:

str

validate_parameter_name(name: str, component_type: str)

Validates a parameter name to ensure it adheres to Python’s identifier naming rules. The function verifies if the given name is a string, non-empty, does not contain spaces, does not start with a digit, and is a valid Python identifier. Additionally, it ensures the name starts with a letter or an underscore. Raises a ValueError with a detailed error message if validation fails.

Parameters:
  • name (str) – The name to validate.

  • component_type (str) – Describes the type of component associated with the parameter.

Raises:

ValueError – If name is not a string, is empty, contains spaces, starts with a digit, does not start with a letter or underscore, or is not a valid identifier.

TODO: - [ ] indent - [ ] center - [ ] Superscript, subscript - [ ] border/margin/padding (all sides)

float_left(component: PageContent) PageContent

Floats the component to the left.

Parameters:

component – The component to float left

Returns:

Returns the original component (updated)

float_right(component: PageContent | str) PageContent

Floats the component to the right.

Parameters:

component – The component to float right

Returns:

Returns the original component (updated)

update_attr(component: PageContent | str, attr: str, value: str) PageContent

Updates the attribute of a component, returning the component (allowing you to chain calls). The attr property should match the HTML attribute name.

Example attributes include: - id - class - title

Parameters:
  • component – The component to update

  • attr – The name of the attribute to change

  • value – The value to set the attribute to (should be a string).

Returns:

Returns the original component (updates its values)

update_style(component: PageContent | str, style: str, value: str) PageContent

Updates the style of a component, returning the component (allowing you to chain calls). The style property should match the CSS property name. Remember to include units in the value if they are expected!

Example style properties include: - color - background-color - font-size

Parameters:
  • component – The component to update

  • style – The name of the style property to change

  • value – The value to set the style property to (should be a string).

Returns:

Returns the original component (updates its values)