How do I access response content in WSGI middleware for Flask?

from flask import request

def modify_incoming():
    if {some test on request}:

    # can return app.make_response() to end the request early

def modify_outgoing(response):
    html = response.get_data(as_text=True) = {modify html}
    return response
class ModifyHTMLMiddleware:
    def __init__(self, app): = app

    def __call__(self, environ, start_response):
        # can modify environ to affect what the wrapped application sees
        app_iter =, start_response)
        # decode and encode need to use the appropriate codec
        html = b"".join(app_iter).decode("utf8")
        # modify html
        return [html.encode("utf8")]