### Python: Basic Application Setup and Hello World Route Source: https://github.com/klen/muffin/blob/develop/docs/usage.md Demonstrates how to create a basic Muffin application and define a simple 'Hello, World!' route. This is the starting point for any Muffin application. ```python from muffin import Application app = Application() @app.route("/") async def hello_world(request): return "

Hello, World!

" ``` -------------------------------- ### Install Muffin with standard dependencies Source: https://github.com/klen/muffin/blob/develop/docs/index.md Installs Muffin along with standard dependencies like gunicorn and uvicorn for a complete setup. ```console pip install muffin[standard] ``` -------------------------------- ### Python Muffin Application Example Source: https://github.com/klen/muffin/blob/develop/docs/deploy.md A simple 'Hello World' application written using the Muffin framework in Python. This code defines a basic Muffin application and a route that responds to requests with 'Hello World!'. ```python from muffin import Application app = Application() @app.route('/') async def index(request): return 'Hello World!' ``` -------------------------------- ### Install Muffin with pip Source: https://github.com/klen/muffin/blob/develop/docs/index.md Installs the Muffin framework using pip. This is the basic installation command. ```console pip install muffin ``` -------------------------------- ### Install Muffin Web Framework Source: https://context7.com/klen/muffin/llms.txt Installs the Muffin framework using pip. Basic installation includes core features, while the 'standard' extra installs additional dependencies for production servers like gunicorn and uvicorn. ```bash # Basic installation pip install muffin # Standard installation with gunicorn, uvicorn, uvloop, httptools pip install muffin[standard] ``` -------------------------------- ### Dockerfile for Muffin Application Source: https://github.com/klen/muffin/blob/develop/docs/deploy.md This Dockerfile sets up an environment to run a Muffin application. It starts from the official Muffin Docker image and copies the application code into the container. It's suitable for basic containerized deployments. ```dockerfile FROM horneds/muffin:latest # Copy your application code COPY . /app ``` -------------------------------- ### Test HTTP Requests with Muffin TestClient (Python) Source: https://github.com/klen/muffin/blob/develop/docs/testing.md Demonstrates how to use the TestClient to simulate HTTP GET requests to a Muffin application and assert the response. ```python from muffin import Application app = Application() @app.route('/') async def home(request): return "OK" ``` ```python from muffin import TestClient client = TestClient(app) response = await client.get('/') assert response.status_code == 200 assert await response.text() == 'OK' ``` -------------------------------- ### Install Muffin Web Framework Source: https://github.com/klen/muffin/blob/develop/README.rst Installs the Muffin web framework using pip. For a standard installation including gunicorn, uvicorn, uvloop, and httptools, use 'pip install muffin[standard]'. ```console pip install muffin ``` ```console pip install muffin[standard] ``` -------------------------------- ### Python: Mounting Nested Applications Source: https://github.com/klen/muffin/blob/develop/docs/usage.md Shows how to mount sub-applications within a main Muffin application for modular design and organization. ```python subapp = Application() @subapp.route('/route') async def subroute(request): return "From subapp" app.route('/sub')(subapp) ``` -------------------------------- ### Python: Configuring Static File Serving Source: https://github.com/klen/muffin/blob/develop/docs/usage.md Explains how to configure Muffin to serve static files from specified folders, including setting a URL prefix for assets. ```python app = Application(static_url_prefix='/assets', static_folders=['static']) ``` -------------------------------- ### Python: Using Regex for Routing Source: https://github.com/klen/muffin/blob/develop/docs/usage.md Shows how to define routes using regular expressions in Muffin, allowing for more complex URL matching patterns. ```python import re @app.route(re.compile(r'/item/(a|b|c)/')) async def item(request): return request.path ``` -------------------------------- ### Python: Integrating External ASGI Middleware Source: https://github.com/klen/muffin/blob/develop/docs/usage.md Illustrates how to integrate external ASGI middleware, like `SentryMiddleware`, into a Muffin application. ```python from sentry_asgi import SentryMiddleware app.middleware(SentryMiddleware) ``` -------------------------------- ### Install Dependencies with Dockerfile Source: https://context7.com/klen/muffin/llms.txt Installs Python dependencies from requirements.txt within a Docker image. This is a common step in containerizing Python applications. ```dockerfile RUN pip install -r requirements.txt ``` -------------------------------- ### Python: Defining Basic and Dynamic Routes Source: https://github.com/klen/muffin/blob/develop/docs/usage.md Illustrates how to define simple routes and dynamic routes with path parameters in Muffin. Dynamic routes allow capturing parts of the URL. ```python @app.route('/') async def index(request): return 'Index Page' @app.route('/user/{username}') async def user_profile(request): username = request.path_params['username'] return f"Hello, {username}" ``` -------------------------------- ### Python: Accessing Query Parameters Source: https://github.com/klen/muffin/blob/develop/docs/usage.md Demonstrates how to access query parameters from the request object in a Muffin view. It shows how to safely get a 'search' parameter with a default value. ```python search = request.query.get('search', '') ``` -------------------------------- ### Pytest Integration for Muffin Applications (Console) Source: https://github.com/klen/muffin/blob/develop/docs/testing.md Illustrates how to configure pytest to automatically discover and use Muffin application fixtures like 'app' and 'client'. ```console $ pytest -xs --muffin-app example ``` -------------------------------- ### GET /hello Source: https://github.com/klen/muffin/blob/develop/docs/api.md Handles GET requests to the /hello endpoint. It can respond with a general greeting or a personalized greeting if a name is provided in the path. ```APIDOC ## GET /hello ### Description Handles GET requests to the /hello endpoint. It can respond with a general greeting or a personalized greeting if a name is provided in the path. ### Method GET ### Endpoint /hello /hello/{name} ### Parameters #### Path Parameters - **name** (string) - Optional - The name to greet. ### Request Example ``` GET /hello GET /hello/john ``` ### Response #### Success Response (200) - **message** (string) - The greeting message. #### Response Example ```json { "message": "GET: Hello all" } ``` ```json { "message": "GET: Hello john" } ``` ``` -------------------------------- ### GET /hello/custom Source: https://github.com/klen/muffin/blob/develop/docs/api.md Handles GET requests to a custom /hello endpoint, returning a specific custom greeting. ```APIDOC ## GET /hello/custom ### Description Handles GET requests to a custom /hello endpoint, returning a specific custom greeting. ### Method GET ### Endpoint /hello/custom ### Response #### Success Response (200) - **message** (string) - The custom greeting message. #### Response Example ```json { "message": "Custom HELLO" } ``` ``` -------------------------------- ### Muffin Logging Configuration using dictConfig Source: https://github.com/klen/muffin/blob/develop/docs/configuration.md Provides an example of configuring logging in Muffin using Python's dictConfig format. This allows detailed control over formatters, handlers, and loggers. ```python LOG_CONFIG = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'default': { 'format': '%(asctime)s %(levelname)s %(name)s %(message)s' }, }, 'handlers': { 'logfile': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'filename': 'my_log.log', 'maxBytes': 50 * 1024 * 1024, 'backupCount': 10 }, }, 'loggers': { '': { 'handlers': ['logfile'], 'level': 'ERROR' }, 'project': { 'level': 'INFO', 'propagate': True, }, } } ``` -------------------------------- ### Test Muffin Application with TestClient Source: https://context7.com/klen/muffin/llms.txt Provides examples of using Muffin's `TestClient` to simulate HTTP requests and WebSocket connections for testing purposes. Includes pytest integration. ```python from muffin import Application, TestClient, ResponseWebSocket app = Application() @app.route('/') async def index(request): return {'message': 'Hello'} @app.route('/users', methods=['POST']) async def create_user(request): data = await request.json() return 201, {'id': 1, 'name': data['name']} @app.route('/ws') async def websocket(request): async with ResponseWebSocket(request) as ws: msg = await ws.receive() await ws.send(f'Echo: {msg}') # Test HTTP endpoints async def test_index(): client = TestClient(app) response = await client.get('/') assert response.status_code == 200 data = await response.json() assert data['message'] == 'Hello' async def test_create_user(): client = TestClient(app) response = await client.post('/users', json={'name': 'Alice'}) assert response.status_code == 201 data = await response.json() assert data['name'] == 'Alice' assert 'id' in data async def test_headers_and_cookies(): client = TestClient(app) response = await client.get( '/protected', headers={'Authorization': 'Bearer token123'}, cookies={'session': 'abc'} ) assert response.status_code == 200 # Test WebSocket async def test_websocket(): client = TestClient(app) async with client.websocket('/ws') as ws: await ws.send('Hello') response = await ws.receive() assert response == 'Echo: Hello' # Pytest integration (pytest.ini or pyproject.toml): # [tool.pytest.ini_options] # muffin_app = "myapp:app" # # Then use fixtures in tests: # async def test_with_fixtures(app, client): # response = await client.get('/') # assert response.status_code == 200 ``` -------------------------------- ### Timing Middleware (Python) Source: https://context7.com/klen/muffin/llms.txt An internal middleware example that measures the request processing time and adds it to the response headers as 'X-Response-Time'. ```python from muffin import Application, ResponseHTML import time app = Application() # Internal middleware using decorator @app.middleware async def timing_middleware(app, request, receive, send): start = time.time() response = await app(request, receive, send) duration = time.time() - start response.headers['X-Response-Time'] = f'{duration:.4f}s' return response ``` -------------------------------- ### WebSocket Chat Handler (Python) Source: https://context7.com/klen/muffin/llms.txt Provides an example of a WebSocket chat handler. It sends a welcome message, then echoes back user messages until the user types 'quit'. ```python @app.route('/ws/chat') async def chat_websocket(request): async with ResponseWebSocket(request) as ws: await ws.send('Welcome to the chat!') async for message in ws: if message == 'quit': await ws.send('Goodbye!') break await ws.send(f'You said: {message}') ``` -------------------------------- ### Test WebSocket Routes with Muffin TestClient (Python) Source: https://github.com/klen/muffin/blob/develop/docs/testing.md Shows how to test WebSocket endpoints in a Muffin application using the TestClient, including sending and receiving messages. ```python from muffin import Application, ResponseWebSocket app = Application() @app.route('/ws') async def socket(request): async with ResponseWebSocket(request) as ws: msg = await ws.receive() if msg == 'ping': await ws.send('pong') ``` ```python from muffin import TestClient client = TestClient(app) async with client.websocket('/ws') as ws: await ws.send('ping') msg = await ws.receive() assert msg == 'pong' ``` -------------------------------- ### Python: Enabling Debug Mode Source: https://github.com/klen/muffin/blob/develop/docs/usage.md Shows how to enable debug mode for a Muffin application, which provides more detailed error output during development. ```python app = Application(debug=True) ``` -------------------------------- ### Bash: Running a Muffin Application with Uvicorn Source: https://github.com/klen/muffin/blob/develop/docs/usage.md Shows the command to run a Muffin application using the Uvicorn ASGI server. This is essential for serving your web application. ```bash uvicorn hello:app ``` -------------------------------- ### Python: Implementing Redirects and HTTP Errors Source: https://github.com/klen/muffin/blob/develop/docs/usage.md Demonstrates how to raise redirects and HTTP errors within Muffin views. This includes using `ResponseRedirect` and `ResponseError`. ```python from muffin import ResponseRedirect, ResponseError @app.route('/') async def index(request): raise ResponseRedirect('/login') @app.route('/secure') async def secure(request): if not request.cookies.get('auth'): raise ResponseError.UNAUTHORIZED() return "Secret data" ``` -------------------------------- ### Python: Handling File Uploads Source: https://github.com/klen/muffin/blob/develop/docs/usage.md Explains how to process file uploads in Muffin by accessing the 'file' object from the request form and reading its content. ```python form = await request.form() file = form['file'] content = await file.read() ``` -------------------------------- ### Python: Custom Error Handling Source: https://github.com/klen/muffin/blob/develop/docs/usage.md Shows how to define custom error handlers for specific HTTP status codes, such as 404 Not Found, in Muffin. ```python @app.on_error(404) async def not_found(request, error): return "Custom 404 Page" ``` -------------------------------- ### Muffin CLI: Start Interactive Shell Source: https://github.com/klen/muffin/blob/develop/docs/cli.md Shows how to launch an interactive Muffin shell within the application context. It supports disabling IPython for a standard Python shell experience. ```console $ muffin your.module shell [--no-ipython] ``` -------------------------------- ### Python: Implementing Internal Muffin Middleware Source: https://github.com/klen/muffin/blob/develop/docs/usage.md Demonstrates how to create and apply custom internal middleware to a Muffin application. This middleware can modify requests or responses. ```python @app.middleware async def simple_md(app, request, receive, send): response = await app(request, receive, send) response.headers['x-custom-md'] = 'passed' return response ``` -------------------------------- ### Define Routes with Handlers Source: https://context7.com/klen/muffin/llms.txt Illustrates how to define routes using class-based handlers, which allows for organizing route logic by HTTP methods (GET, POST, PUT, DELETE). It also shows how to define custom routes within a handler. ```python from muffin import Application, Handler app = Application() @app.route('/users', '/users/{user_id:int}') class UserHandler(Handler): async def get(self, request): """Handle GET requests""" user_id = request.path_params.get('user_id') if user_id: return {'user_id': user_id, 'name': f'User {user_id}'} return {'users': [{'id': 1}, {'id': 2}, {'id': 3}]} async def post(self, request): """Handle POST requests - create user""" data = await request.json() return 201, {'id': 100, 'name': data.get('name')} async def put(self, request): """Handle PUT requests - update user""" user_id = request.path_params.get('user_id') data = await request.json() return {'id': user_id, 'updated': True, **data} async def delete(self, request): """Handle DELETE requests""" user_id = request.path_params.get('user_id') return {'deleted': user_id} # Custom route within handler @Handler.route('/users/search') async def search(self, request): query = request.query.get('q', '') return {'results': [], 'query': query} ``` -------------------------------- ### Authentication Middleware (Python) Source: https://context7.com/klen/muffin/llms.txt An internal middleware example that checks for an 'Authorization' header. It allows access to public routes without authentication but returns a 401 Unauthorized response otherwise. ```python @app.middleware async def auth_middleware(app, request, receive, send): # Skip auth for public routes if request.url.path.startswith('/public'): return await app(request, receive, send) # Check authentication token = request.headers.get('Authorization') if not token: return ResponseHTML('Unauthorized', status_code=401) return await app(request, receive, send) ``` -------------------------------- ### Python: Handling POST Requests and Form Data Source: https://github.com/klen/muffin/blob/develop/docs/usage.md Illustrates how to handle POST requests in Muffin, specifically focusing on retrieving form data submitted by the client. It shows how to access username and password from the form. ```python @app.route('/login', methods=['POST']) async def login(request): form = await request.form() username = form.get('username') password = form.get('password') if username == 'admin': return f"Welcome, {username}" return "Invalid credentials" ``` -------------------------------- ### Run Multiple Muffin Instances with Gunicorn Source: https://context7.com/klen/muffin/llms.txt Starts multiple Muffin application instances using Gunicorn with the Uvicorn worker class. Each instance is bound to a unique Unix socket, intended for use with a reverse proxy like NGINX. ```bash gunicorn app:app -w 4 -k uvicorn.workers.UvicornWorker \ --bind unix:/tmp/muffin_1.sock & gunicorn app:app -w 4 -k uvicorn.workers.UvicornWorker \ --bind unix:/tmp/muffin_2.sock & ``` -------------------------------- ### Python: Using Type Converters in Routes Source: https://github.com/klen/muffin/blob/develop/docs/usage.md Demonstrates how to use Muffin's built-in type converters (like 'int') in route definitions to automatically cast path parameters. This improves type safety. ```python @app.route('/post/{post_id:int}') async def post(request): post_id = request.path_params['post_id'] return f"Post #{post_id}" ``` -------------------------------- ### Register Middleware in Muffin Application Source: https://github.com/klen/muffin/blob/develop/docs/api.md Shows how to register middleware for a Muffin application. Middleware can be ASGI middleware or internal application-level middleware. The example includes registering SentryMiddleware and a custom logging middleware. ```python from muffin import Application from sentry_asgi import SentryMiddleware app = Application() app.middleware(SentryMiddleware) # or wrap directly app = SentryMiddleware(app) ``` ```python from muffin import Application, ResponseHTML app = Application() @app.middleware async def simple_md(app, request, receive, send): try: response = await app(request, receive, send) response.headers['x-simple-md'] = 'passed' return response except RuntimeError: return ResponseHTML('Middleware Exception') ``` -------------------------------- ### Test HTTP Endpoints with Muffin Client Source: https://github.com/klen/muffin/blob/develop/docs/api.md Demonstrates testing various HTTP methods (GET, POST, DELETE) against Muffin endpoints using the client. Asserts expected responses for different paths and methods. ```python async def test_my_endpoint(client): response = await client.get('/hello') assert await response.text() == 'GET: Hello all' response = await client.get('/hello/john') assert await response.text() == 'GET: Hello john' response = await client.post('/hello') assert await response.text() == 'POST: Hello all' response = await client.get('/hello/custom') assert await response.text() == 'Custom HELLO' response = await client.delete('/hello') assert response.status_code == 405 ``` -------------------------------- ### Creating an Application Source: https://context7.com/klen/muffin/llms.txt Demonstrates how to create a Muffin application instance and define basic routes using the `@app.route()` decorator. ```APIDOC ## POST /api/users ### Description This endpoint allows for the creation of new user resources. ### Method POST ### Endpoint /api/users ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **username** (string) - Required - The desired username for the new user. - **email** (string) - Required - The email address for the new user. - **password** (string) - Required - The password for the new user. ### Request Example ```json { "username": "johndoe", "email": "john.doe@example.com", "password": "securepassword123" } ``` ### Response #### Success Response (201 Created) - **id** (string) - The unique identifier for the newly created user. - **username** (string) - The username of the created user. - **email** (string) - The email address of the created user. #### Response Example ```json { "id": "a1b2c3d4-e5f6-7890-1234-567890abcdef", "username": "johndoe", "email": "john.doe@example.com" } ``` ``` -------------------------------- ### Initialize Muffin Application with Configuration Modules Source: https://github.com/klen/muffin/blob/develop/docs/configuration.md Demonstrates how to initialize a Muffin application by specifying configuration module names. The framework will use the first configuration module that exists. ```python # Pass configuration module names; the first existing will be used app = muffin.Application('config.local', 'config.production') ``` -------------------------------- ### Create a Basic Muffin Application Source: https://github.com/klen/muffin/blob/develop/README.rst A simple 'Hello User' application using Muffin. It defines a root route and a dynamic route for '/hello/{name}'. The application is run using uvicorn. ```python import muffin app = muffin.Application() @app.route('/', '/hello/{name}') async def hello(request): name = request.path_params.get('name', 'world') return f'Hello, {name.title()}!' ``` -------------------------------- ### NGINX Configuration for Muffin Source: https://github.com/klen/muffin/blob/develop/docs/deploy.md This NGINX configuration serves as a reverse proxy for Muffin applications. It handles incoming HTTP requests, forwards them to Muffin instances via Unix domain sockets (or TCP/IP sockets as an alternative), and serves static files directly. This setup improves security and allows for running multiple Muffin instances. ```nginx http { server { listen 80; client_max_body_size 4G; server_name example.com; location / { proxy_set_header Host $http_host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_redirect off; proxy_buffering off; proxy_pass http://muffin; } location /static { # Serve static files root /path/to/app/static; } } upstream muffin { # Unix domain sockets for high performance server unix:/tmp/example_1.sock fail_timeout=0; server unix:/tmp/example_2.sock fail_timeout=0; server unix:/tmp/example_3.sock fail_timeout=0; server unix:/tmp/example_4.sock fail_timeout=0; # Alternatively, use TCP/IP sockets: # server 127.0.0.1:8081 fail_timeout=0; # server 127.0.0.1:8082 fail_timeout=0; # server 127.0.0.1:8083 fail_timeout=0; # server 127.0.0.1:8084 fail_timeout=0; } } ``` -------------------------------- ### Create a basic Muffin application Source: https://github.com/klen/muffin/blob/develop/docs/index.md A simple 'Hello User' application using Muffin. It defines a route that responds with a personalized greeting. ```python import muffin app = muffin.Application() @app.route('/', '/hello/{name}') async def hello(request): name = request.path_params.get('name', 'world') return f'Hello, {name.title()}!' ``` -------------------------------- ### Create Muffin Application and Define Routes Source: https://context7.com/klen/muffin/llms.txt Demonstrates how to create a Muffin Application instance and define basic routes using the `@app.route()` decorator. Handlers are asynchronous functions that accept a Request object and return a response. ```python from muffin import Application # Create application with configuration app = Application( name='myapp', debug=True, static_url_prefix='/assets', static_folders=['static'] ) @app.route('/') async def index(request): return '

Welcome to Muffin!

' @app.route('/hello/{name}') async def hello(request): name = request.path_params.get('name', 'world') return f'Hello, {name.title()}!' # Run with: uvicorn app:app ``` -------------------------------- ### Configure Application Settings Source: https://context7.com/klen/muffin/llms.txt Demonstrates how to configure the Muffin application using Python modules, environment variables, and keyword arguments. It highlights the hierarchical precedence of these configuration sources. ```python # config/settings.py """ DEBUG = False DATABASE_URL = 'postgresql://localhost/myapp' SECRET_KEY = 'change-me-in-production' LOG_LEVEL = 'INFO' STATIC_FOLDERS = ['static'] """ # Create app with config module from muffin import Application app = Application( 'config.settings', # Primary config module 'config.local', # Override with local settings (if exists) DEBUG=True, # Override specific options NAME='myapp' ) # Access configuration print(app.cfg.DEBUG) # True (from kwargs) print(app.cfg.DATABASE_URL) # From config module print(app.cfg.LOG_LEVEL) # From config module ``` -------------------------------- ### Muffin CLI: List Available Commands Source: https://github.com/klen/muffin/blob/develop/docs/cli.md Demonstrates how to use the Muffin CLI to list all available commands for a given module or application object. This is useful for discovering the CLI's capabilities. ```console $ muffin path.to.your.module --help $ muffin path.to.your.module:app_object_name --help ``` -------------------------------- ### Python: Accessing Cookies Source: https://github.com/klen/muffin/blob/develop/docs/usage.md Shows how to retrieve cookie values from the request object in Muffin. This is commonly used for session management. ```python session = request.cookies.get('session') ``` -------------------------------- ### Insert Middleware at Beginning Source: https://context7.com/klen/muffin/llms.txt Shows how to define and insert a custom middleware function at the beginning of the middleware chain. This allows for pre-processing or early exit logic. ```python from some_package import CORSMiddleware app.middleware(CORSMiddleware) @app.middleware def first_middleware(app): async def middleware(scope, receive, send): # This runs first return await app(scope, receive, send) return middleware app.middleware(first_middleware, insert_first=True) ``` -------------------------------- ### Muffin CLI: Show Help for Custom Command Source: https://github.com/klen/muffin/blob/develop/docs/cli.md Explains how to display the help message for a custom Muffin command, showing its arguments, optional arguments, and description. ```console $ muffin example hello --help ``` -------------------------------- ### Register Startup and Shutdown Event Handlers Source: https://context7.com/klen/muffin/llms.txt Demonstrates how to register asynchronous functions to run during application startup and shutdown. This is useful for initializing and cleaning up resources like database connections. ```python from muffin import Application app = Application() db_pool = None @app.on_startup async def setup_database(): global db_pool print("Connecting to database...") # db_pool = await create_pool(app.cfg.DATABASE_URL) db_pool = {'connected': True} print("Database connected!") @app.on_startup async def setup_cache(): print("Initializing cache...") # Initialize Redis, Memcached, etc. @app.on_shutdown async def cleanup_database(): global db_pool print("Closing database connections...") # await db_pool.close() db_pool = None print("Database closed!") @app.on_shutdown async def cleanup_cache(): print("Clearing cache connections...") @app.route('/health') async def health_check(request): return { 'status': 'healthy', 'database': db_pool is not None } ``` -------------------------------- ### Python: Running Tasks in Background After Response Source: https://github.com/klen/muffin/blob/develop/docs/usage.md Explains how to schedule asynchronous tasks to run in the background after an HTTP response has been sent to the client using `run_after_response`. ```python import asyncio async def background_task(param): await asyncio.sleep(1) print(f"Done: {param}") @app.route('/bg') async def bg(request): app.run_after_response(background_task("task")) return "Scheduled" ``` -------------------------------- ### Routing with Path Parameters Source: https://context7.com/klen/muffin/llms.txt Illustrates how to define dynamic routes with path parameters, including type converters and regular expressions. ```APIDOC ## GET /user/{username} ### Description Retrieves the profile information for a specific user based on their username. ### Method GET ### Endpoint /user/{username} ### Parameters #### Path Parameters - **username** (string) - Required - The username of the user whose profile to retrieve. #### Query Parameters None #### Request Body None ### Request Example ``` GET /user/johndoe ``` ### Response #### Success Response (200 OK) - **username** (string) - The username of the user. - **profile_data** (object) - An object containing the user's profile details. #### Response Example ```json { "username": "johndoe", "profile_data": { "full_name": "John Doe", "bio": "Software developer and tech enthusiast." } } ``` ``` ```APIDOC ## GET /post/{post_id:int} ### Description Fetches a blog post by its integer ID. ### Method GET ### Endpoint /post/{post_id:int} ### Parameters #### Path Parameters - **post_id** (integer) - Required - The unique identifier of the blog post. #### Query Parameters None #### Request Body None ### Request Example ``` GET /post/123 ``` ### Response #### Success Response (200 OK) - **post_id** (integer) - The ID of the blog post. - **title** (string) - The title of the blog post. - **content** (string) - The content of the blog post. #### Response Example ```json { "post_id": 123, "title": "Understanding Muffin Routing", "content": "This post explains how to use path parameters in Muffin..." } ``` ``` ```APIDOC ## GET /api/v1/items, /api/v2/items ### Description Retrieves a list of items, supporting multiple API versions on a single handler. ### Method GET ### Endpoint /api/v1/items or /api/v2/items ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ``` GET /api/v1/items ``` ### Response #### Success Response (200 OK) - **items** (array) - A list of available items. #### Response Example ```json { "items": ["item1", "item2", "item3"] } ``` ``` ```APIDOC ## GET /category/{electronics|clothing|food}/ ### Description Retrieves items belonging to a specific category using a regex-based route. ### Method GET ### Endpoint /category/{category_name}/ ### Parameters #### Path Parameters - **category_name** (string) - Required - The name of the category (electronics, clothing, or food). #### Query Parameters None #### Request Body None ### Request Example ``` GET /category/electronics/ ``` ### Response #### Success Response (200 OK) - **message** (string) - A confirmation message indicating the category. #### Response Example ```json { "message": "Displaying items for the electronics category." } ``` ``` -------------------------------- ### Build and Run Muffin Application with Docker Source: https://context7.com/klen/muffin/llms.txt Builds a Docker image for the Muffin application and runs it as a detached container, exposing port 80. Assumes a Dockerfile is present. ```bash docker build -t myapp . docker run -d --name myapp -p 80:80 myapp ``` -------------------------------- ### File Download Response (Python) Source: https://context7.com/klen/muffin/llms.txt Demonstrates how to serve a file for download using `ResponseFile`. It extracts the filename from the URL path and specifies the filename for the download. ```python @app.route('/download/{filename}') async def download(request): filename = request.path_params['filename'] return ResponseFile(f'/files/{filename}', filename=filename) ``` -------------------------------- ### Configure Logging with Dictionary Source: https://context7.com/klen/muffin/llms.txt Sets up logging configuration for the Muffin application using a dictionary. This allows detailed control over log levels and handlers. ```python from muffin import Application app = Application( LOG_CONFIG={ 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'level': 'DEBUG', }, }, 'loggers': { 'myapp': { 'handlers': ['console'], 'level': 'DEBUG', }, }, } ) ``` -------------------------------- ### Mount Nested Applications Source: https://context7.com/klen/muffin/llms.txt Demonstrates how to mount sub-applications onto a main application, enabling modularity and API versioning. This allows for organizing different API versions or modules under distinct URL prefixes. ```python from muffin import Application # Main application app = Application() # API v1 sub-application api_v1 = Application() @api_v1.route('/users') async def v1_users(request): return {'version': 'v1', 'users': ['alice', 'bob']} @api_v1.route('/items') async def v1_items(request): return {'version': 'v1', 'items': [1, 2, 3]} # API v2 sub-application api_v2 = Application() @api_v2.route('/users') async def v2_users(request): return {'version': 'v2', 'users': [{'name': 'alice'}, {'name': 'bob'}]} # Mount sub-applications app.route('/api/v1')(api_v1) app.route('/api/v2')(api_v2) # Main app routes @app.route('/') async def home(request): return {'apis': ['/api/v1', '/api/v2']} # Access: /api/v1/users, /api/v2/users ``` -------------------------------- ### Nested Applications API Source: https://context7.com/klen/muffin/llms.txt Demonstrates mounting sub-applications for modularity and versioning. ```APIDOC ## Nested Applications API ### Description Provides access to different API versions (v1 and v2) through nested applications. ### Method GET ### Endpoint /api/v1/users, /api/v1/items, /api/v2/users, / ### Parameters #### Path Parameters None #### Query Parameters None ### Request Example None ### Response #### Success Response (200) - **version** (string) - The API version. - **users** (array) - List of users (v1) or user objects (v2). - **items** (array) - List of items (v1). - **apis** (array) - List of available API endpoints. #### Response Example #### GET /api/v1/users ```json { "version": "v1", "users": ["alice", "bob"] } ``` #### GET /api/v1/items ```json { "version": "v1", "items": [1, 2, 3] } ``` #### GET /api/v2/users ```json { "version": "v2", "users": [{"name": "alice"}, {"name": "bob"}] } ``` #### GET / ```json { "apis": ["/api/v1", "/api/v2"] } ``` ``` -------------------------------- ### Muffin CLI: Run Custom Command Source: https://github.com/klen/muffin/blob/develop/docs/cli.md Demonstrates how to execute a custom Muffin command from the CLI, passing arguments and options as defined in the Python function. ```console $ muffin example hello mike --upper ``` -------------------------------- ### Muffin Routing with Path Parameters Source: https://context7.com/klen/muffin/llms.txt Illustrates advanced routing capabilities in Muffin, including dynamic path parameters with type converters (int, str, uuid, path), handling multiple paths for a single handler, and using regular expressions for complex route matching. ```python from muffin import Application import re app = Application() # Basic dynamic route @app.route('/user/{username}') async def user_profile(request): username = request.path_params['username'] return f"Profile: {username}" # Typed parameter (int) @app.route('/post/{post_id:int}') async def get_post(request): post_id = request.path_params['post_id'] return {'post_id': post_id, 'title': f'Post #{post_id}'} # Multiple paths on one handler @app.route('/api/v1/items', '/api/v2/items') async def list_items(request): return {'items': ['item1', 'item2', 'item3']} # Regex-based routing @app.route(re.compile(r'/category/(electronics|clothing|food)/')) async def category(request): return f"Category: {request.path}" ``` -------------------------------- ### Override Muffin Configuration Options Directly Source: https://github.com/klen/muffin/blob/develop/docs/configuration.md Illustrates how to override individual configuration options directly when initializing a Muffin application by passing them as keyword arguments. Assertions verify that the options are set correctly. ```python app = muffin.Application(DEBUG=True, ANY_OPTION='value', ONE_MORE='value2') assert app.cfg.DEBUG is True assert app.cfg.ANY_OPTION == 'value' assert app.cfg.ONE_MORE == 'value2' ``` -------------------------------- ### Configuration API Source: https://context7.com/klen/muffin/llms.txt Details on how to configure the Muffin application using various methods. ```APIDOC ## Configuration API ### Description Explains the configuration system of Muffin, including precedence rules for different configuration sources. ### Method N/A (Configuration is set during application initialization) ### Endpoint N/A ### Parameters None ### Request Example None ### Response None (This section describes configuration methods, not an API endpoint) ### Configuration Sources 1. **Keyword Arguments**: Passed directly to the `Application` constructor (highest precedence). 2. **Configuration Modules**: Python files specified in the `Application` constructor. 3. **Environment Variables**: Can be used to override settings. ### Example Configuration Initialization ```python from muffin import Application app = Application( 'config.settings', # Primary config module 'config.local', # Override with local settings (if exists) DEBUG=True, # Override specific options NAME='myapp' ) ``` ### Accessing Configuration Configuration values can be accessed via `app.cfg`. ```python print(app.cfg.DEBUG) # True (from kwargs) print(app.cfg.DATABASE_URL) # From config module print(app.cfg.LOG_LEVEL) # From config module ``` ``` -------------------------------- ### Python: Automatic Response Type Conversion Source: https://github.com/klen/muffin/blob/develop/docs/usage.md Illustrates Muffin's automatic conversion of view return values into HTTP responses. It covers returning Response objects, strings, dictionaries, lists, tuples, and None. ```python @app.route('/json') async def json_view(request): return {'key': 'value'} @app.route('/html') async def html_view(request): return '

Hello

' @app.route('/tuple') async def tuple_view(request): return 201, 'Created' ``` -------------------------------- ### Create Custom CLI Commands Source: https://context7.com/klen/muffin/llms.txt Shows how to define custom command-line interface commands for a Muffin application using the `@app.manage.command` decorator. Supports arguments and type hints. ```python from muffin import Application app = Application(name='myapp') @app.manage.command async def hello(name: str, upper: bool = False): """Greet someone by name. :param name: The name to greet :param upper: Use uppercase output """ greeting = f"Hello, {name}!" if upper: greeting = greeting.upper() print(greeting) @app.manage.command async def create_user(username: str, email: str, admin: bool = False): """Create a new user in the database. :param username: User's username :param email: User's email address :param admin: Grant admin privileges """ print(f"Creating user: {username} ({email})") print(f"Admin: {admin}") # await db.users.create(username=username, email=email, is_admin=admin) print("User created!") @app.manage.command async def migrate(direction: str = 'up'): """Run database migrations. :param direction: Migration direction (up/down) """ print(f"Running migrations: {direction}") # Run migration logic # Usage: # $ muffin myapp hello John --upper # HELLO, JOHN! # # $ muffin myapp create-user alice alice@example.com --admin # Creating user: alice (alice@example.com) # Admin: True # User created! # # $ muffin myapp shell # Start interactive shell ``` -------------------------------- ### Override Muffin Configuration with Environment Variables Source: https://github.com/klen/muffin/blob/develop/docs/configuration.md Demonstrates how Muffin reads environment variables in the format {APP_NAME}_{OPTION_NAME} and parses them as JSON by default. It shows how to override settings like DEBUG, DB_PARAMS, and TOKEN. ```python import os os.environ['APP_TOKEN'] = 'value' # simple strings supported as well os.environ['APP_DEBUG'] = 'false' # json boolean value os.environ['APP_DB_PARAMS'] = '{"pool": 50}' # json too app = Muffin('app', 'settings') assert app.cfg.DEBUG is False assert app.cfg.DB_PARAMS == {'pool': 50} assert app.cfg.TOKEN == 'value' ``` -------------------------------- ### Register Startup and Shutdown Handlers in Muffin Source: https://github.com/klen/muffin/blob/develop/docs/api.md Explains how to register functions to be executed during the application's startup and shutdown phases using `on_startup` and `on_shutdown` decorators. These are useful for initializing resources or performing cleanup. ```python # Example usage within a Muffin application setup: # @app.on_startup def startup_handler(): # print("Application starting...") # # @app.on_shutdown # async def shutdown_handler(): # print("Application shutting down...") ``` -------------------------------- ### Redirect and Error Handling with Response Classes (Python) Source: https://context7.com/klen/muffin/llms.txt Demonstrates how to handle redirects using `ResponseRedirect` and various HTTP errors using `ResponseError`. It also shows custom error handlers for specific status codes and exceptions. ```python from muffin import Application, ResponseRedirect, ResponseError app = Application() @app.route('/old-page') async def old_page(request): # Redirect to new location raise ResponseRedirect('/new-page') @app.route('/secure') async def secure_endpoint(request): auth = request.cookies.get('auth_token') if not auth: raise ResponseError.UNAUTHORIZED('Authentication required') if auth != 'valid_token': raise ResponseError.FORBIDDEN('Invalid token') return {'secret': 'data'} @app.route('/items/{item_id:int}') async def get_item(request): item_id = request.path_params['item_id'] # Simulated database lookup items = {1: 'Item One', 2: 'Item Two'} if item_id not in items: raise ResponseError.NOT_FOUND(f'Item {item_id} not found') return {'id': item_id, 'name': items[item_id]} @app.route('/validate', methods=['POST']) async def validate(request): data = await request.json() if not data or 'email' not in data: raise ResponseError.BAD_REQUEST('Email is required') return {'valid': True} # Custom error handler for 404 @app.on_error(404) async def not_found_handler(request, error): return ResponseJSON({'error': 'Page not found', 'path': str(request.url.path)}, status_code=404) # Custom error handler for exceptions @app.on_error(TimeoutError) async def timeout_handler(request, error): return ResponseJSON({'error': 'Request timed out'}, status_code=504) ``` -------------------------------- ### POST /hello Source: https://github.com/klen/muffin/blob/develop/docs/api.md Handles POST requests to the /hello endpoint, typically for general greetings. ```APIDOC ## POST /hello ### Description Handles POST requests to the /hello endpoint, typically for general greetings. ### Method POST ### Endpoint /hello ### Request Example ``` POST /hello ``` ### Response #### Success Response (200) - **message** (string) - The greeting message. #### Response Example ```json { "message": "POST: Hello all" } ``` ``` -------------------------------- ### Run Muffin Application Directly with Uvicorn Source: https://context7.com/klen/muffin/llms.txt Runs the Muffin application using the Uvicorn ASGI server. This is suitable for development or simple deployments. It binds to all interfaces on port 8000 and uses 4 worker processes. ```bash uvicorn app:app --host 0.0.0.0 --port 8000 --workers 4 ``` -------------------------------- ### Tuple Return for Status Code and Headers (Python) Source: https://context7.com/klen/muffin/llms.txt Demonstrates returning a tuple for status code and headers directly from a route handler. This is a concise way to specify HTTP status and response headers. ```python @app.route('/created') async def created(request): return 201, {'id': 123, 'status': 'created'} @app.route('/custom-headers') async def custom_headers(request): return 200, 'OK', {'X-Custom-Header': 'value'} ``` -------------------------------- ### Streaming Response (Python) Source: https://context7.com/klen/muffin/llms.txt Shows how to implement a streaming response using `ResponseStream`. This is useful for sending data in chunks, such as large file uploads or real-time data feeds. ```python @app.route('/stream') async def stream(request): async def generate(): for i in range(10): await asyncio.sleep(0.5) yield f"chunk {i}\n" return ResponseStream(generate()) ``` -------------------------------- ### Basic Muffin Application Structure Source: https://context7.com/klen/muffin/llms.txt Defines a simple Muffin application with two routes: a root route returning application status and a health check route. Requires the 'muffin' library. ```python from muffin import Application app = Application(name='myapp', debug=False) @app.route('/') async def index(request): return {'status': 'running', 'app': 'myapp'} @app.route('/health') async def health(request): return {'healthy': True} ``` -------------------------------- ### Middleware Registration Source: https://github.com/klen/muffin/blob/develop/docs/api.md How to register both external ASGI middleware and internal application-level middleware. ```APIDOC ## Middleware Registration ### Description Register middleware to process requests and responses. ### External ASGI Middleware Register external ASGI middleware using the `middleware` method or by wrapping the application. **Example:** ```python from muffin import Application from sentry_asgi import SentryMiddleware app = Application() app.middleware(SentryMiddleware) # Alternatively: # app = SentryMiddleware(app) ``` ### Internal Application-Level Middleware Register internal middleware directly within the application. **Example:** ```python from muffin import Application, ResponseHTML app = Application() @app.middleware async def simple_md(app, request, receive, send): try: response = await app(request, receive, send) response.headers['x-simple-md'] = 'passed' return response except RuntimeError: return ResponseHTML('Middleware Exception') ``` ``` -------------------------------- ### Middleware API Source: https://context7.com/klen/muffin/llms.txt Allows registration of middleware for global request/response processing, supporting both internal and external ASGI middleware. ```APIDOC ## Middleware Registration ### Description Demonstrates the registration of internal middleware using decorators for request and response processing. ### Method N/A ### Endpoint N/A ### Parameters None ### Middleware Examples #### Timing Middleware - **Description**: Measures and adds the response time to the headers. - **Header Added**: `X-Response-Time` (string) - The duration of the request in seconds. #### Authentication Middleware - **Description**: Checks for an `Authorization` header on requests, denying access to non-public routes if missing. - **Behavior**: Allows requests to `/public` routes without authentication. - **Error Response (401)**: Returns `Unauthorized` HTML if the token is missing. ### Request Example (with Auth Header) ``` Authorization: Bearer your_token_here ``` ### Response Example (with Timing Header) ``` X-Response-Time: 0.1234s ``` ```