from flask import current_app import uuid app = current_app class UniqueIDMiddleware: def __init__(self, app): self.app = app def __call__(self, environ, start_response): # Generate a unique ID unique_id = str(uuid.uuid4()) # Add the unique ID to the request headers environ['HTTP_X_REQUEST_ID'] = unique_id # Call the next middleware or the Flask application return self.app(environ, start_response)