### Teyaotlani CLI for Fetching and Serving Files Source: https://github.com/alanbato/teyaotlani/blob/main/docs/tutorials/quick-start.md Provides examples of using the Teyaotlani command-line interface (CLI) to fetch Spartan pages and serve files from a directory. The `get` command fetches content, optionally saving it to a file with `-o`. The `serve` command starts a local Spartan server. ```bash # Fetch a page teyaotlani get spartan://example.com/ # Save output to a file teyaotlani get spartan://example.com/document.gmi -o document.gmi # Serve files from the current directory teyaotlani serve . # Serve from a specific directory on a custom port teyaotlani serve ./my-capsule --port 3000 ``` -------------------------------- ### Making a Simple Spartan Request with Python Source: https://github.com/alanbato/teyaotlani/blob/main/docs/tutorials/quick-start.md Demonstrates how to fetch content from a Spartan server using the `get()` function from the Teyaotlani library. This function handles client creation and closing automatically. It requires the `asyncio` and `teyaotlani` libraries. ```python import asyncio from teyaotlani import get async def main(): response = await get("spartan://example.com/") print(f"Status: {response.status}") print(f"Meta: {response.meta}") print(f"Body: {response.body}") asyncio.run(main()) ``` -------------------------------- ### Development Installation of Teyaotlani Source: https://github.com/alanbato/teyaotlani/blob/main/docs/tutorials/installation.md This set of commands clones the Teyaotlani repository and installs it in development mode using uv. This method is suitable for users who want to contribute to the project or run from source. ```bash git clone https://github.com/alanbato/teyaotlani.git cd teyaotlani uv sync --group dev ``` -------------------------------- ### Run Teyaotlani Server with Configuration Source: https://github.com/alanbato/teyaotlani/blob/main/docs/reference/configuration.md Demonstrates how to run the Teyaotlani server using a configuration file via the CLI or the Python API. The Python example shows loading configuration from a TOML file and starting the server. ```bash teyaotlani serve --config config.toml ``` ```python from teyaotlani import ServerConfig, run_server config = ServerConfig.from_toml("config.toml") await run_server(config) ``` -------------------------------- ### Python: Basic Server Setup Source: https://context7.com/alanbato/teyaotlani/llms.txt Starts a Spartan server to serve static files from a directory with minimal configuration. It supports specifying host, port, document root, and index files. Directory listing can be enabled or disabled. A synchronous wrapper is also provided for simpler use cases. ```python import asyncio from pathlib import Path from teyaotlani import ServerConfig, start_server async def run_basic_server(): config = ServerConfig( host="localhost", port=3000, document_root=Path("./capsule"), enable_directory_listing=False, index_files=["index.gmi", "index.gemini"] ) # Validate configuration config.validate() # Start server (runs until interrupted) await start_server(config) # Synchronous wrapper from teyaotlani import run_server run_server( document_root="./capsule", host="localhost", port=3000, enable_directory_listing=True, log_level="INFO" ) ``` -------------------------------- ### Using SpartanClient for Multiple Requests in Python Source: https://github.com/alanbato/teyaotlani/blob/main/docs/tutorials/quick-start.md Shows how to use `SpartanClient` as an asynchronous context manager for making multiple requests with a single client instance. This provides more control and efficiency when performing several operations. It requires the `asyncio` and `teyaotlani` libraries. ```python import asyncio from teyaotlani import SpartanClient async def main(): async with SpartanClient() as client: # Make multiple requests with the same client response1 = await client.get("spartan://example.com/") response2 = await client.get("spartan://example.com/about.gmi") print(response1.body) print(response2.body) asyncio.run(main()) ``` -------------------------------- ### Run Spartan Server (CLI) Source: https://github.com/alanbato/teyaotlani/blob/main/docs/tutorials/your-first-spartan-server.md Starts the Teyaotlani Spartan server using the command-line interface. It specifies the directory to serve and the port number. This is a quick way to get the server running. ```bash teyaotlani serve . --port 3000 ``` -------------------------------- ### Teyaotlani CLI Usage Examples Source: https://github.com/alanbato/teyaotlani/blob/main/README.md Demonstrates common command-line interface operations for Teyaotlani, including fetching, serving files, and uploading content. ```bash # Fetch a page teyaotlani get spartan://example.com/ # Serve files teyaotlani serve ./capsule --port 3000 # Upload content teyaotlani upload spartan://localhost:3000/file.txt -c "Hello!" ``` -------------------------------- ### Install Teyaotlani with uv Source: https://github.com/alanbato/teyaotlani/blob/main/docs/tutorials/installation.md This command installs the Teyaotlani package using the uv package manager. Ensure you have Python 3.10+ and uv installed. This is the recommended installation method. ```bash uv add teyaotlani ``` -------------------------------- ### Python Async Client GET Request Example Source: https://github.com/alanbato/teyaotlani/blob/main/docs/index.md Demonstrates how to make an asynchronous GET request using the Teyaotlani library to fetch content from a Spartan URI. This example requires the 'teyaotlani' Python package and the 'asyncio' module. ```python import asyncio from teyaotlani import get async def main(): response = await get("spartan://example.com/") print(response.body) asyncio.run(main()) ``` -------------------------------- ### TOML: Example Configuration File Source: https://context7.com/alanbato/teyaotlani/llms.txt An example TOML file demonstrating how to configure various aspects of the Teyaotlani server. It includes settings for the server itself, rate limiting, access control, uploads, and logging, showing the structure and parameters that can be defined. ```toml [server] host = "0.0.0.0" port = 300 document_root = "./capsule" max_file_size = 104857600 enable_directory_listing = true index_files = ["index.gmi", "index.gemini"] [rate_limit] enabled = true capacity = 10 refill_rate = 1.0 retry_after = 30 [access_control] enabled = false default_allow = true [upload] enabled = true upload_dir = "./uploads" max_upload_size = 10485760 enable_delete = false [logging] level = "INFO" hash_ips = true json = false ``` -------------------------------- ### Verify Teyaotlani Installation (CLI) Source: https://github.com/alanbato/teyaotlani/blob/main/docs/tutorials/installation.md This command checks the installed Teyaotlani version from the command line. It's used after installation to confirm the package is accessible and functioning. ```bash teyaotlani version ``` -------------------------------- ### Bash: Fetch Resources via CLI Source: https://context7.com/alanbato/teyaotlani/llms.txt Demonstrates using the Teyaotlani command-line interface to fetch Spartan resources. Examples include basic GET requests, verbose output with headers, setting custom timeouts, and accessing local servers. ```bash # Basic GET request teyaotlani get spartan://example.com/page.gmi # Verbose output with status and headers teyaotlani get -v spartan://example.com/page.gmi # Custom timeout (60 seconds) teyaotlani get --timeout 60 spartan://slow-server.com/ # Local server teyaotlani get spartan://localhost:3000/index.gmi ``` -------------------------------- ### Spartan GET Request Example Source: https://github.com/alanbato/teyaotlani/blob/main/docs/explanation/spartan-protocol.md An example of a simple GET request in the Spartan protocol. It specifies the host and path, with a content-length of 0 indicating no upload data. ```plaintext example.com / 0\r\n ``` -------------------------------- ### start_server Function Source: https://github.com/alanbato/teyaotlani/blob/main/docs/reference/api/server.md Initiates the Teyaotlani server, likely a synchronous or initial setup function. ```APIDOC ## start_server ### Description Initializes and starts the Teyaotlani server. Specific details on its operation and parameters are not provided in the source documentation. ### Method [Unknown - likely synchronous or asynchronous] ### Parameters [Not specified in source documentation] ### Request Example ```python # Example usage (details may vary) from teyaotlani import start_server # Assuming start_server takes configuration arguments or a config object # start_server(host="localhost", port=3000, document_root="./capsule") ``` ``` -------------------------------- ### Install Teyaotlani with pip Source: https://github.com/alanbato/teyaotlani/blob/main/docs/tutorials/installation.md This command installs the Teyaotlani package using the pip package manager. Ensure you have Python 3.10+ and pip installed. This is an alternative installation method. ```bash pip install teyaotlani ``` -------------------------------- ### TOML Configuration Examples for Teyaotlani Source: https://github.com/alanbato/teyaotlani/blob/main/docs/reference/configuration.md Provides example TOML configurations for different sections of the Teyaotlani server. Each snippet illustrates the available keys and their typical values for server settings, rate limiting, access control, uploads, and logging. ```toml [server] host = "0.0.0.0" port = 300 document_root = "./public" max_file_size = 52428800 # 50 MB enable_directory_listing = true index_files = ["index.gmi", "index.gemini", "index.txt"] ``` ```toml [rate_limit] enabled = true capacity = 20 refill_rate = 2.0 retry_after = 60 ``` ```toml [access_control] enabled = true allow_list = ["192.168.1.0/24", "10.0.0.0/8"] deny_list = ["192.168.1.100/32"] default_allow = false ``` ```toml [upload] enabled = true upload_dir = "./uploads" max_upload_size = 5242880 # 5 MB enable_delete = true ``` ```toml [logging] level = "DEBUG" hash_ips = false json = true ``` ```toml # Teyaotlani Spartan Server Configuration [server] host = "0.0.0.0" port = 300 document_root = "./capsule" max_file_size = 104857600 enable_directory_listing = true index_files = ["index.gmi", "index.gemini"] [rate_limit] enabled = true capacity = 10 refill_rate = 1.0 retry_after = 30 [access_control] enabled = false # allow_list = ["192.168.1.0/24"] # deny_list = ["192.168.1.100/32"] default_allow = true [upload] enabled = false # upload_dir = "./uploads" max_upload_size = 10485760 enable_delete = false [logging] level = "INFO" hash_ips = true json = false ``` -------------------------------- ### Verify Teyaotlani Installation (Python) Source: https://github.com/alanbato/teyaotlani/blob/main/docs/tutorials/installation.md This Python code snippet imports the Teyaotlani package and accesses its __version__ attribute to verify the installation. It's useful for programmatic checks. ```python import teyaotlani teyaotlani.__version__ ``` -------------------------------- ### Python Package Installation Source: https://github.com/alanbato/teyaotlani/blob/main/docs/index.md Provides instructions for installing the Teyaotlani Python package using either 'uv' (recommended) or 'pip'. These commands are executed in a terminal environment. ```bash # Using uv (recommended) uv add teyaotlani # Using pip pip install teyaotlani ``` -------------------------------- ### Install Teyaotlani CLI Source: https://github.com/alanbato/teyaotlani/blob/main/docs/reference/cli.md Installs the Teyaotlani CLI tool, which is necessary for using its command-line functionalities. This can be done using either 'uv' or 'pip'. ```bash uv add teyaotlani # or pip install teyaotlani ``` -------------------------------- ### Run Server with TOML Config (CLI) Source: https://github.com/alanbato/teyaotlani/blob/main/docs/tutorials/your-first-spartan-server.md Starts the Teyaotlani server using the command-line interface and specifies a TOML configuration file to load settings from. This is useful for deploying the server with pre-defined configurations. ```bash teyaotlani serve --config config.toml ``` -------------------------------- ### SpartanClient Context Manager Example in Python Source: https://github.com/alanbato/teyaotlani/blob/main/docs/explanation/architecture.md Shows how the SpartanClient is used as an asynchronous context manager in Python. This pattern ensures that the client is properly initialized before use and cleaned up afterwards, even if errors occur. ```python async with SpartanClient() as client: # Client is properly initialized response = await client.get(url) # Client is properly closed ``` -------------------------------- ### Serve Files with Teyaotlani CLI Source: https://github.com/alanbato/teyaotlani/blob/main/docs/reference/cli.md Starts a local Spartan server to serve files from a specified directory. Supports custom host, port, directory listing, logging levels, and configuration files. ```bash # Serve current directory teyaotlani serve . # Serve on a custom port teyaotlani serve ./capsule --port 3000 # Enable directory listings teyaotlani serve ./capsule -d -p 3000 # Use a configuration file teyaotlani serve --config config.toml # Debug logging teyaotlani serve . -p 3000 --log-level DEBUG ``` -------------------------------- ### Production-Ready Server Configuration Example Source: https://github.com/alanbato/teyaotlani/blob/main/docs/how-to/configure-server.md Provides a comprehensive TOML configuration for a production Teyaotlani server, including server settings, rate limiting, and logging. ```toml [server] host = "0.0.0.0" port = 300 document_root = "/var/spartan/capsule" max_file_size = 52428800 # 50 MB enable_directory_listing = false index_files = ["index.gmi"] [rate_limit] enabled = true capacity = 20 refill_rate = 2.0 retry_after = 60 [access_control] enabled = false # Using firewall instead [logging] level = "INFO" hash_ips = true json = true ``` -------------------------------- ### Run Spartan Server with Python Source: https://github.com/alanbato/teyaotlani/blob/main/docs/reference/api/server.md This Python snippet demonstrates how to quickly set up and run a Spartan protocol server using the teyaotlani library. It requires the asyncio library for asynchronous operations and the teyaotlani ServerConfig and run_server components. The function takes a ServerConfig object specifying host, port, and document root, then starts the server. ```python import asyncio from teyaotlani import ServerConfig, run_server async def main(): config = ServerConfig( host="localhost", port=3000, document_root="./capsule", ) await run_server(config) asyncio.run(main()) ``` -------------------------------- ### Checking Spartan Response Status in Python Source: https://github.com/alanbato/teyaotlani/blob/main/docs/tutorials/quick-start.md Illustrates how to check the status of a Spartan server response using helper functions like `is_success`, `is_redirect`, and `is_error`. This allows for conditional handling of different response types. It requires the `teyaotlani` library. ```python from teyaotlani import get, is_success, is_redirect, is_error async def main(): response = await get("spartan://example.com/") if is_success(response.status): print(f"Got content: {response.body[:100]}...") elif is_redirect(response.status): print(f"Redirected to: {response.meta}") elif is_error(response.status): print(f"Error: {response.meta}") ``` -------------------------------- ### Verify Configuration with Debug Logging Source: https://github.com/alanbato/teyaotlani/blob/main/docs/how-to/configure-server.md Starts the Teyaotlani server with debug logging enabled to verify that all configuration settings are applied correctly. ```bash teyaotlani serve --config config.toml --log-level DEBUG ``` -------------------------------- ### Middleware Example for Access Control and Rate Limiting in Python Source: https://github.com/alanbato/teyaotlani/blob/main/docs/explanation/architecture.md Provides a Python code example of middleware implementation for request handling. It showcases checks for rate limiting and access control before a request is passed to the main handlers. ```python # Rate limiting if rate_limiter.is_limited(client_ip): return Response(5, "Rate limited") # Access control if not access_control.is_allowed(client_ip): return Response(4, "Access denied") ``` -------------------------------- ### TOML Configuration File Source: https://github.com/alanbato/teyaotlani/blob/main/docs/tutorials/your-first-spartan-server.md An example TOML configuration file for the Teyaotlani server. It defines server settings like host, port, document root, index files, and logging level for production use. ```toml [server] host = "localhost" port = 3000 document_root = "./my-capsule" enable_directory_listing = true index_files = ["index.gmi", "index.gemini"] [logging] level = "INFO" ``` -------------------------------- ### Upload Files using Teyaotlani CLI Source: https://github.com/alanbato/teyaotlani/blob/main/docs/how-to/handle-uploads.md Command-line interface commands for uploading files to a Spartan server. Supports uploading string content directly or by referencing a local file. ```bash # Upload string content teyaotlani upload spartan://localhost:3000/message.txt -c "Hello, world!" # Upload a file teyaotlani upload spartan://localhost:3000/document.gmi -f ./mydoc.gmi # Send zero-byte upload to delete teyaotlani upload spartan://localhost:3000/old-file.txt -c "" # These create files in subdirectories teyaotlani upload spartan://localhost:3000/posts/2024/entry.gmi -f entry.gmi teyaotlani upload spartan://localhost:3000/images/photo.png -f photo.png ``` -------------------------------- ### Spartan Upload Request Example Source: https://github.com/alanbato/teyaotlani/blob/main/docs/explanation/spartan-protocol.md An example of an upload request in the Spartan protocol. It includes the host, path, content-length specifying the size of the data, and the actual data payload. ```plaintext example.com /upload.txt 13\r\nHello, world! ``` -------------------------------- ### Async Client Usage in Python Source: https://github.com/alanbato/teyaotlani/blob/main/docs/explanation/architecture.md Demonstrates the asynchronous usage of the SpartanClient, a core component for making requests. It highlights the use of async with for proper resource management and making GET requests. ```python async with SpartanClient() as client: response = await client.get("spartan://example.com/") ``` -------------------------------- ### Serve files via CLI with Teyaotlani Source: https://context7.com/alanbato/teyaotlani/llms.txt This CLI command starts a Spartan server to serve a specified directory. It offers options for port customization, enabling directory listings, setting host and log levels, and using configuration files. ```bash # Serve current directory on default port (300) teyaotlani serve . # Serve specific directory on custom port teyaotlani serve ./capsule --port 3000 # Enable directory listings teyaotlani serve ./public --directory-listing # Serve with custom host and logging teyaotlani serve ./capsule --host 0.0.0.0 --port 8300 --log-level DEBUG # Use configuration file teyaotlani serve --config config.toml # Override config file settings teyaotlani serve --config config.toml --port 4000 --directory-listing # JSON formatted logs teyaotlani serve ./capsule --json-logs --log-level INFO ``` -------------------------------- ### Upload Files using Python SpartanClient Source: https://github.com/alanbato/teyaotlani/blob/main/docs/how-to/handle-uploads.md Python code demonstrating how to upload files and string content to a Teyaotlani server using the SpartanClient. Handles both text and binary uploads and checks response status. ```python import asyncio from teyaotlani import SpartanClient async def upload_file(): async with SpartanClient() as client: # Upload string content response = await client.upload( "spartan://localhost:3000/hello.txt", b"Hello, world!" ) print(f"Status: {response.status}") # Upload binary file with open("image.png", "rb") as f: data = f.read() response = await client.upload( "spartan://localhost:3000/image.png", data ) print(f"Upload status: {response.status}") asyncio.run(upload_file()) ``` ```python from teyaotlani import upload response = asyncio.run(upload( "spartan://localhost:3000/file.txt", b"File contents" )) ``` ```python response = await client.upload( "spartan://localhost:3000/old-file.txt", b"" # Zero bytes = delete ) ``` ```python from teyaotlani import SpartanClient, is_success, is_error async def upload_with_verification(): async with SpartanClient() as client: response = await client.upload( "spartan://localhost:3000/file.txt", b"content" ) if is_success(response.status): print(f"Upload successful: {response.meta}") elif is_error(response.status): print(f"Upload failed: {response.meta}") ``` -------------------------------- ### Gemtext Formatting Example Source: https://github.com/alanbato/teyaotlani/blob/main/docs/explanation/spartan-protocol.md Illustrates the basic syntax for Gemtext, a plain text markup format optimized for the Spartan protocol. It includes headings, paragraphs, links, lists, quotes, and preformatted text. ```gemtext # Heading ## Subheading Regular paragraph text. => /link Link text => spartan://example.com/ External link * List item 1 * List item 2 > Quoted text ```preformatted code block ``` ``` -------------------------------- ### Python: TOML Configuration Loading Source: https://context7.com/alanbato/teyaotlani/llms.txt Loads server configuration from a TOML file, suitable for production deployments with complex settings. Allows overriding specific settings loaded from the file before validation and starting the server. This promotes modularity and easier management of configurations. ```python import asyncio from pathlib import Path from teyaotlani import ServerConfig, start_server async def run_configured_server(): # Load from TOML file config = ServerConfig.from_toml(Path("config.toml")) # Override specific settings config.port = 8300 config.log_level = "DEBUG" # Validate before starting config.validate() await start_server(config) asyncio.run(run_configured_server()) ``` -------------------------------- ### Complete Teyaotlani Server Configuration (TOML) Source: https://github.com/alanbato/teyaotlani/blob/main/docs/how-to/handle-uploads.md A comprehensive TOML configuration for a Teyaotlani server, including settings for the server itself, file uploads, rate limiting, and access control. ```toml [server] host = "localhost" port = 3000 document_root = "./capsule" [upload] enabled = true upload_dir = "./uploads" max_upload_size = 10485760 enable_delete = true [rate_limit] enabled = true capacity = 5 refill_rate = 0.5 [access_control] enabled = true allow_list = ["127.0.0.1/32", "192.168.1.0/24"] default_allow = false ``` -------------------------------- ### Configure File Uploads (TOML) Source: https://github.com/alanbato/teyaotlani/blob/main/docs/how-to/handle-uploads.md This TOML configuration enables file uploads, specifies the directory for storing uploaded files, sets a maximum upload size, and optionally allows file deletion. ```toml [upload] enabled = true upload_dir = "./uploads" max_upload_size = 10485760 # 10 MB enable_delete = false ``` ```toml [upload] enabled = true upload_dir = "./uploads" max_upload_size = 5242880 # 5 MB ``` ```toml [upload] enabled = true upload_dir = "./uploads" enable_delete = true ``` -------------------------------- ### Combine Uploads with Access Control (TOML) Source: https://github.com/alanbato/teyaotlani/blob/main/docs/how-to/handle-uploads.md TOML configuration to enable file uploads and restrict access based on IP addresses. Uploads are enabled, a maximum size is set, and access control is configured to allow only specific IP ranges. ```toml [upload] enabled = true upload_dir = "./uploads" max_upload_size = 10485760 [access_control] enabled = true allow_list = ["192.168.1.0/24"] # Only local network default_allow = false ``` -------------------------------- ### SpartanClient Session Management with Teyaotlani Source: https://context7.com/alanbato/teyaotlani/llms.txt Manages multiple Spartan protocol requests within a single session using the `SpartanClient` class. This class allows for shared configuration, such as timeouts, and explicit connection management via an `async with` statement. It supports GET requests, uploads, and queries (which are treated as uploads). Response status can be checked for success. ```python import asyncio from teyaotlani import SpartanClient async def batch_requests(): async with SpartanClient(timeout=45.0) as client: # GET request response = await client.get("spartan://example.com/index.gmi") print(response.body) # Upload content upload_response = await client.upload( "spartan://example.com/data.txt", "Sample data" ) # Send query (treated as upload) search_response = await client.query( "spartan://example.com/search", "search terms" ) # Check response status if search_response.is_success(): print(f"Results: {search_response.body}") asyncio.run(batch_requests()) ``` -------------------------------- ### Fetch Spartan Resource with Teyaotlani Source: https://context7.com/alanbato/teyaotlani/llms.txt Retrieves content from a Spartan server using the `get()` function. It handles connection management and timeouts automatically. The function returns a response object from which MIME type, body, charset, redirect URL, status, and meta information can be extracted. Supports custom timeout values. ```python import asyncio from teyaotlani import get async def fetch_page(): # Simple GET request with default 30s timeout response = await get("spartan://example.com/page.gmi") if response.is_success(): print(f"MIME type: {response.mime_type}") print(f"Content: {response.body}") print(f"Charset: {response.charset}") elif response.is_redirect(): print(f"Redirect to: {response.redirect_url}") else: print(f"Error: {response.status} - {response.meta}") asyncio.run(fetch_page()) # Custom timeout response = await get("spartan://slow-server.com/", timeout=60.0) ``` -------------------------------- ### Enable Directory Listings (Python Configuration) Source: https://github.com/alanbato/teyaotlani/blob/main/docs/tutorials/your-first-spartan-server.md Demonstrates how to configure the Teyaotlani server in Python to allow directory listings. When set to `True`, visitors can browse the server's file structure if an index file is not present. ```python config = ServerConfig( host="localhost", port=3000, document_root="./my-capsule", enable_directory_listing=True, # Enable browsing ) ``` -------------------------------- ### Get Teyaotlani Version (Python) Source: https://github.com/alanbato/teyaotlani/blob/main/docs/reference/api/index.md Retrieves the currently installed version of the Teyaotlani library. This is useful for checking compatibility or reporting issues. ```python >>> import teyaotlani >>> teyaotlani.__version__ '0.1.0' ``` -------------------------------- ### Load Server Configuration Source: https://github.com/alanbato/teyaotlani/blob/main/docs/how-to/configure-server.md Demonstrates how to load server configuration from a TOML file using both the command-line interface and a Python script. ```bash teyaotlani serve --config config.toml ``` ```python from teyaotlani import ServerConfig, run_server import asyncio async def main(): config = ServerConfig.from_toml("config.toml") await run_server(config) asyncio.run(main()) ``` -------------------------------- ### Load Configuration from TOML (Python) Source: https://github.com/alanbato/teyaotlani/blob/main/docs/tutorials/your-first-spartan-server.md Shows how to load server configuration from a TOML file in a Python script using `ServerConfig.from_toml()`. This allows for managing server settings externally. ```python import asyncio from teyaotlani import run_server, ServerConfig async def main(): config = ServerConfig.from_toml("config.toml") await run_server(config) asyncio.run(main()) ``` -------------------------------- ### get Function Source: https://github.com/alanbato/teyaotlani/blob/main/docs/reference/api/client.md The 'get' function is a convenience function for making a single Spartan protocol GET request. ```APIDOC ## get ### Description Performs a single Spartan protocol GET request. ### Method `get(url: str, **kwargs)` ### Endpoint `spartan://` URI scheme ### Parameters - **url** (str) - Required - The URL to fetch. - **kwargs** - Optional - Additional keyword arguments to pass to the underlying request. ### Request Example ```python response = asyncio.run(get("spartan://example.com/")) ``` ### Response - **response** - The response object from the GET request. ``` -------------------------------- ### Create About Page (Gemtext) Source: https://github.com/alanbato/teyaotlani/blob/main/docs/tutorials/your-first-spartan-server.md Creates an 'about.gmi' file containing Gemtext content explaining what Teyaotlani is and briefly describing the Spartan protocol. It also includes a link back to the home page. ```gemtext # About This Capsule This capsule is powered by Teyaotlani, a Python implementation of the Spartan protocol. ## What is Spartan? Spartan is a simple, text-focused protocol similar to Gemini, but without TLS complexity. => / Back to home ``` -------------------------------- ### Spartan Deletion Request Example Source: https://github.com/alanbato/teyaotlani/blob/main/docs/explanation/spartan-protocol.md Demonstrates how to signal a deletion request in the Spartan protocol. This is achieved by sending a zero-byte upload to the target resource. ```plaintext example.com /old-file.txt 0\r\n ``` -------------------------------- ### Test Spartan Server (CLI) Source: https://github.com/alanbato/teyaotlani/blob/main/docs/tutorials/your-first-spartan-server.md Uses the Teyaotlani CLI to fetch content from the locally running Spartan server. This command retrieves the index page from the specified URL. ```bash teyaotlani get spartan://localhost:3000/ ``` -------------------------------- ### Create Capsule Directory Source: https://github.com/alanbato/teyaotlani/blob/main/docs/tutorials/your-first-spartan-server.md Creates a new directory named 'my-capsule' and changes the current directory to it. This is the first step in setting up the server's content. ```bash mkdir my-capsule cd my-capsule ``` -------------------------------- ### Run Spartan Server Programmatically (Python) Source: https://github.com/alanbato/teyaotlani/blob/main/docs/tutorials/your-first-spartan-server.md Launches the Teyaotlani Spartan server from a Python script. It configures the server's host, port, document root, and enables directory listings using the `run_server` function. ```python import asyncio from teyaotlani import run_server, ServerConfig async def main(): config = ServerConfig( host="localhost", port=3000, document_root="./my-capsule", enable_directory_listing=True, ) print(f"Starting server on {config.host}:{config.port}") await run_server(config) asyncio.run(main()) ``` -------------------------------- ### Spartan Protocol Response Format Source: https://github.com/alanbato/teyaotlani/blob/main/docs/explanation/spartan-protocol.md Defines the structure of a Spartan response, starting with a status line containing a single-digit status code and metadata, followed by an optional body. The status line must end with \r\n. ```plaintext status meta\r\n[body] ``` -------------------------------- ### Create TOML Configuration File Source: https://github.com/alanbato/teyaotlani/blob/main/docs/how-to/configure-server.md Defines the basic server settings, including host, port, document root, and directory listing preferences, along with logging level. ```toml [server] host = "localhost" port = 3000 document_root = "./capsule" enable_directory_listing = true [logging] level = "INFO" ``` -------------------------------- ### Spartan Protocol Request Format Source: https://github.com/alanbato/teyaotlani/blob/main/docs/explanation/spartan-protocol.md Defines the structure of a Spartan request, including the host, path, content-length, and optional data. Content-length is 0 for GET requests and indicates the size of upload data for uploads. The line must end with \r\n. ```plaintext host path content-length\r\n[data] ``` -------------------------------- ### Python asyncio Protocol Implementation Source: https://github.com/alanbato/teyaotlani/blob/main/docs/explanation/architecture.md Illustrates the implementation of a client protocol using Python's asyncio.Protocol. This snippet shows the basic structure for handling connections and received data, essential for network communication. ```python class SpartanClientProtocol(asyncio.Protocol): def connection_made(self, transport): # Send request ... def data_received(self, data): # Parse response ... ``` -------------------------------- ### Fetch Resource with Teyaotlani CLI Source: https://github.com/alanbato/teyaotlani/blob/main/docs/reference/cli.md Fetches a resource from a Spartan server using a specified URL. Supports optional timeout and verbose output flags. The URL is the primary argument, and the timeout can be set in seconds. ```bash # Basic fetch teyaotlani get spartan://example.com/ # With verbose output teyaotlani get -v spartan://example.com/page.gmi # With custom timeout teyaotlani get -t 60 spartan://slow-server.com/ ``` -------------------------------- ### Set Up Access Control Configuration Source: https://github.com/alanbato/teyaotlani/blob/main/docs/how-to/configure-server.md Implements access control by defining lists of allowed and denied IP addresses, with a default policy for unmatched IPs. ```toml [access_control] enabled = true allow_list = ["192.168.1.0/24", "10.0.0.0/8"] deny_list = ["192.168.1.100/32"] default_allow = false ``` -------------------------------- ### Make Spartan Protocol Requests using Python Source: https://github.com/alanbato/teyaotlani/blob/main/docs/reference/api/client.md Demonstrates how to make Spartan protocol requests using the teyaotlani client module in Python. It covers both single, one-off requests and multiple requests managed by a SpartanClient instance. Requires the asyncio library for asynchronous operations. ```python import asyncio from teyaotlani import SpartanClient, get # Simple one-off request response = asyncio.run(get("spartan://example.com/")) # Multiple requests with a client async def main(): async with SpartanClient() as client: response = await client.get("spartan://example.com/") print(response.body) asyncio.run(main()) ``` -------------------------------- ### Upload Content with Teyaotlani CLI Source: https://github.com/alanbato/teyaotlani/blob/main/docs/reference/cli.md Uploads content or a file to a Spartan server. Requires either the --content option for string data or the --file option for a file. Supports optional timeout and verbose output. ```bash # Upload string content teyaotlani upload spartan://example.com/file.txt -c "Hello, world!" # Upload a file teyaotlani upload spartan://example.com/doc.gmi -f document.gmi # Upload with verbose output teyaotlani upload -v spartan://example.com/data.txt -c "test data" ``` -------------------------------- ### Override Configuration with CLI Flags Source: https://github.com/alanbato/teyaotlani/blob/main/docs/how-to/configure-server.md Shows how to override specific configuration settings defined in the TOML file directly from the command line. ```bash # Use config file but override port teyaotlani serve --config config.toml --port 4000 # Use config file but override host teyaotlani serve --config config.toml --host 0.0.0.0 ``` -------------------------------- ### Implement Custom Request Handler (Python) Source: https://github.com/alanbato/teyaotlani/blob/main/docs/explanation/architecture.md Demonstrates how to create a custom handler by implementing the handler interface. This handler processes requests based on their path, returning a response or passing it to the next handler. It depends on `SpartanRequest` and `SpartanResponse`. ```python class MyHandler: async def handle(self, request: SpartanRequest) -> SpartanResponse | None: if request.path.startswith("/api/"): return SpartanResponse(2, "application/json", '{"ok": true}') return None # Pass to next handler ``` -------------------------------- ### Run Pytest Tests (Bash) Source: https://github.com/alanbato/teyaotlani/blob/main/docs/explanation/architecture.md Command to execute tests using the pytest framework within the project environment. Assumes the `uv` command is available for running development tasks. ```bash uv run pytest ``` -------------------------------- ### Run Ruff Checks and Formatting (Bash) Source: https://github.com/alanbato/teyaotlani/blob/main/docs/explanation/architecture.md Commands to run Ruff for code checking and formatting. Ensures code quality and consistency across the project. Assumes the `uv` command is available. ```bash uv run ruff check uv run ruff format ``` -------------------------------- ### Create Index Page (Gemtext) Source: https://github.com/alanbato/teyaotlani/blob/main/docs/tutorials/your-first-spartan-server.md Defines the content for the main page of the Spartan capsule using Gemtext format. It includes headings, paragraphs, and links to other pages or external resources. ```gemtext # Welcome to My Capsule This is my first Spartan capsule, served with Teyaotlani! ## About Teyaotlani is a modern Spartan protocol implementation. => about.gmi Learn more about this capsule => spartan://example.com/ Visit example.com ``` -------------------------------- ### Python: Server with Upload Support Source: https://context7.com/alanbato/teyaotlani/llms.txt Configures a server to accept file uploads with size limits and optional delete operations. Key settings include enabling uploads, specifying an upload directory, setting maximum upload and file sizes, and controlling whether zero-byte uploads can delete files. It also supports directory listing and various logging options. ```python import asyncio from pathlib import Path from teyaotlani import ServerConfig, start_server async def run_upload_server(): config = ServerConfig( host="0.0.0.0", port=300, document_root=Path("./public"), # Upload configuration enable_upload=True, upload_dir=Path("./uploads"), max_upload_size=10 * 1024 * 1024, # 10 MB enable_delete=True, # Allow zero-byte uploads to delete files # File serving max_file_size=100 * 1024 * 1024, # 100 MB max file size enable_directory_listing=True, # Logging log_level="INFO", hash_client_ips=True, json_logs=False ) await start_server(config) asyncio.run(run_upload_server()) ``` -------------------------------- ### Upload files and content via CLI with Teyaotlani Source: https://context7.com/alanbato/teyaotlani/llms.txt This CLI command allows uploading files or string content to a Spartan server. It supports specifying the target URL, content, file paths, and verbose output or custom timeouts. ```bash # Upload string content teyaotlani upload spartan://localhost:3000/hello.txt -c "Hello, world!" # Upload file teyaotlani upload spartan://localhost:3000/doc.gmi -f document.gmi # Upload with verbose output teyaotlani upload -v spartan://localhost:3000/data.json -f data.json # Custom timeout teyaotlani upload --timeout 60 spartan://example.com/large.bin -f large.bin ``` -------------------------------- ### Configure Static File Handler in Python Source: https://context7.com/alanbato/teyaotlani/llms.txt Configures the built-in static file handler for serving files with security features like path traversal protection and directory listing. It takes a document root, default index files, directory listing enablement, and max file size as configuration options. ```python from pathlib import Path from teyaotlani.server import StaticFileHandler from teyaotlani.protocol import SpartanRequest # Configure handler handler = StaticFileHandler( document_root=Path("./public"), default_indices=["index.gmi", "index.gemini", "index.txt"], enable_directory_listing=True, max_file_size=50 * 1024 * 1024 # 50 MB limit ) # Handle request request = SpartanRequest( host="localhost", path="/docs/readme.gmi", content_length=0, content=b"" ) response = handler.handle(request) print(f"Status: {response.status}") print(f"Meta: {response.meta}") # Path traversal protection is automatic dangerous_request = SpartanRequest( host="localhost", path="/../../../etc/passwd", content_length=0, content=b"" ) response = handler.handle(dangerous_request) # Returns: SpartanResponse(status=4, meta="Not found") ``` -------------------------------- ### Build middleware pipelines in Python for Teyaotlani Source: https://context7.com/alanbato/teyaotlani/llms.txt This Python code illustrates how to build a middleware chain for request processing in Teyaotlani. It includes configuring and adding rate limiters and access control components to a `MiddlewareChain` for request filtering. ```python import asyncio from teyaotlani.server import ( RateLimiter, RateLimitConfig, AccessControl, AccessControlConfig, MiddlewareChain ) # Configure rate limiting rate_config = RateLimitConfig( capacity=5, refill_rate=0.5, retry_after=60 ) rate_limiter = RateLimiter(rate_config) rate_limiter.start() # Configure access control access_config = AccessControlConfig( allow_list=["192.168.1.0/24"], deny_list=["192.168.1.100/32"], default_allow=False ) access_control = AccessControl(access_config) # Build middleware chain middleware = MiddlewareChain() middleware.add(access_control) # Check access first middleware.add(rate_limiter) # Then rate limit # Process request through chain async def check_request(): allowed, error_response = await middleware.process_request( request_url="spartan://localhost:3000/test", client_ip="192.168.1.50" ) if not allowed: print(f"Rejected: {error_response}") else: print("Request allowed") asyncio.run(check_request()) ``` -------------------------------- ### Configure Upload Handler in Python Source: https://context7.com/alanbato/teyaotlani/llms.txt Sets up a handler for file uploads, including options for maximum upload size, enabling file deletion via zero-byte requests, and validating upload paths. It defines the target directory for uploads. ```python from pathlib import Path from teyaotlani.server import UploadHandler from teyaotlani.protocol import SpartanRequest # Configure upload handler handler = UploadHandler( upload_dir=Path("./uploads"), max_size=5 * 1024 * 1024, # 5 MB max enable_delete=True ) # Upload file upload_request = SpartanRequest( host="localhost", path="/documents/test.txt", content_length=13, content=b"Hello, world!" ) response = handler.handle(upload_request) print(response.body) # "# Upload Successful..." # Delete file (zero-byte upload) delete_request = SpartanRequest( host="localhost", path="/documents/test.txt", content_length=0, content=b"" ) if handler.enable_delete: response = handler.handle(delete_request) print(response.body) # "# Deleted..." ``` -------------------------------- ### ServerConfig Dataclass with TOML Loading in Python Source: https://github.com/alanbato/teyaotlani/blob/main/docs/explanation/architecture.md Shows the Python ServerConfig dataclass, which includes TOML file loading capabilities. This allows server configuration to be easily managed and parsed from a TOML file. ```python @dataclass class ServerConfig: host: str = "localhost" port: int = 300 document_root: Path = Path("./capsule") # ... more fields @classmethod def from_toml(cls, path: str) -> "ServerConfig": data = tomllib.load(open(path, "rb")) return cls(**data) ``` -------------------------------- ### run_server Function Source: https://github.com/alanbato/teyaotlani/blob/main/docs/reference/api/server.md Asynchronously runs the Teyaotlani server with the provided configuration. ```APIDOC ## run_server ### Description Starts and runs the Teyaotlani server asynchronously using the given configuration. ### Method `async` ### Parameters - **config** (ServerConfig) - Required - The server configuration object. ### Request Example ```python import asyncio from teyaotlani import ServerConfig, run_server async def main(): config = ServerConfig( host="localhost", port=3000, document_root="./capsule", ) await run_server(config) asyncio.run(main()) ``` ``` -------------------------------- ### Create Spartan protocol response objects in Python Source: https://context7.com/alanbato/teyaotlani/llms.txt This Python code demonstrates how to construct various Spartan protocol response objects using the `teyaotlani.SpartanResponse` class. It covers success, redirect, client error, and server error responses, as well as manual construction and property checks. ```python from teyaotlani import SpartanResponse # Success response (status 2) response = SpartanResponse.success( mime_type="text/gemini; charset=utf-8", body="# Welcome\n\nHello, Spartan!" ) print(response.to_bytes()) # b'2 text/gemini; charset=utf-8\r\n# Welcome...' # Redirect response (status 3) redirect = SpartanResponse.redirect("spartan://new-location.com/page.gmi") # Client error (status 4) error = SpartanResponse.client_error("Not found") # Server error (status 5) server_error = SpartanResponse.server_error("Internal error") # Manual construction custom_response = SpartanResponse( status=2, meta="text/plain", body="Custom content", url="spartan://example.com/" ) # Check response properties if custom_response.is_success(): print(f"MIME: {custom_response.mime_type}") print(f"Charset: {custom_response.charset}") ```