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

Solution
from flask import request

@app.before_request
def modify_incoming():
    if {some test on request}:
        ...

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

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

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