WSGI
- User
WSGI
Assistant
WSGI (Web Server Gateway Interface) is a specification that describes how a web server communicates with web applications in Python. Here's a comprehensive explanation:
- Basic Concept:
def simple_app(environ, start_response): """Simplest possible WSGI application""" status = '200 OK' headers = [('Content-type', 'text/plain')] start_response(status, headers) return [b"Hello, World!"]- Key Components:
a) Application/Framework Side:
class WSGIApp: def __init__(self): pass def __call__(self, environ, start_response): status = '200 OK' headers = [('Content-type', 'text/plain')] start_response(status, headers) return [b"Response from WSGIApp"]b) Server Side:
from wsgiref.simple_server import make_server def run_server(app): server = make_server('localhost', 8000, app) server.serve_forever()- More Complete Example:
def application(environ, start_response): # Parse request data path = environ.get('PATH_INFO', '') method = environ.get('REQUEST_METHOD', '') # Prepare response if path == '/': status = '200 OK' response = b"Welcome to homepage" else: status = '404 Not Found' response = b"Page not found" # Set headers headers = [ ('Content-type', 'text/plain'), ('Content-Length', str(len(response))) ] # Start response start_response(status, headers) return [response] # Run with built-in server if __name__ == '__main__': from wsgiref.simple_server import make_server server = make_server('localhost', 8000, application) print("Serving on port 8000...") server.serve_forever()- Using with Framework (Flask example):
from flask import Flask app = Flask(__name__) @app.route('/') def hello(): return "Hello from Flask!" if __name__ == '__main__': app.run()- Middleware Example:
class LoggingMiddleware: def __init__(self, app): self.app = app def __call__(self, environ, start_response): # Log request print(f"Request: {environ['REQUEST_METHOD']} {environ['PATH_INFO']}") # Call the wrapped application return self.app(environ, start_response) # Usage app = LoggingMiddleware(application)- Environment Dictionary Keys:
def show_environ(environ, start_response): response = [] for key, value in sorted(environ.items()): response.append(f'{key}: {value}'.encode()) status = '200 OK' headers = [('Content-type', 'text/plain')] start_response(status, headers) return response- Handling POST Data:
def handle_post(environ, start_response): # Get content length try: request_body_size = int(environ.get('CONTENT_LENGTH', 0)) except ValueError: request_body_size = 0 # Read request body request_body = environ['wsgi.input'].read(request_body_size) # Process data response = f"Received: {request_body.decode()}".encode() status = '200 OK' headers = [('Content-type', 'text/plain')] start_response(status, headers) return [response]- Error Handling:
def error_app(environ, start_response): try: # Some code that might raise an exception raise Exception("Something went wrong!") except Exception as e: status = '500 Internal Server Error' response = str(e).encode() headers = [('Content-type', 'text/plain')] start_response(status, headers) return [response]Key Points to Remember:
- WSGI applications must accept two parameters: environ and start_response
- start_response must be called with status and headers before returning
- The application must return an iterable of bytes
- environ contains CGI-style environment variables
- WSGI is synchronous by design
- Many Python web frameworks (Flask, Django) are WSGI-compatible
- Middleware can be used to add functionality between server and application
WSGI provides a standard interface between Python web applications and web servers, making it possible to write portable web applications that can run on any WSGI-compliant server.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.