duration = time.time() - start_time successful = sum(results)
time.sleep(0.5)
COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt wsgiserver 0.2
class MultiProcessServer: """Fork multiple worker processes"""
response = requests.post('http://127.0.0.1:8889/', data=b'Test data') assert response.text == 'Test data' duration = time
def get_metrics(self): return 'total_requests': self.request_count, 'error_requests': self.error_count, 'error_rate': self.error_count / self.request_count if self.request_count else 0 class SecurityMiddleware: """Add security headers and protections""" def __init__(self, app): self.app = app def __call__(self, environ, start_response): def secure_start_response(status, headers, exc_info=None): # Add security headers headers.extend([ ('X-Content-Type-Options', 'nosniff'), ('X-Frame-Options', 'DENY'), ('X-XSS-Protection', '1; mode=block'), ]) return start_response(status, headers, exc_info) return self.app(environ, secure_start_response) Request size limiting MAX_REQUEST_SIZE = 10 * 1024 * 1024 # 10MB
def __init__(self, app): self.app = app def __call__(self, environ, start_response): import time start = time.time() response = self.app(environ, start_response) duration = time.time() - start print(f"Request took: duration:.4fs") return response app = hello_world_app app = LoggingMiddleware(app) app = TimingMiddleware(app) app): self.app = app def __call__(self
html = f""" <html> <body> <h1>Hello, World!</h1> <p>Method: environ['REQUEST_METHOD']</p> <p>Path: environ['PATH_INFO']</p> </body> </html> """ return [html.encode('utf-8')] if == ' main ': server = WSGIServer('0.0.0.0', 8000, hello_world_app) server.serve_forever() 6.2 Middleware Example ( examples/middleware_demo.py ) class LoggingMiddleware: """Log all requests""" def __init__(self, app): self.app = app def __call__(self, environ, start_response): print(f"environ['REQUEST_METHOD'] environ['PATH_INFO']") return self.app(environ, start_response) class TimingMiddleware: """Measure request duration"""