### 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 '