Beispiel #1
0
def modify_main_app(app: web.Application, config: Config) -> None:
    """
    Modify the app we're serving to make development easier, eg.
    * modify responses to add the livereload snippet
    * set ``static_root_url`` on the app
    """
    app._debug = True
    dft_logger.debug('livereload enabled: %s', '✓' if config.livereload else '✖')

    def get_host(request: web.Request) -> str:
        if config.infer_host:
            return request.headers.get('host', 'localhost').split(':', 1)[0]
        else:
            return config.host

    if config.livereload:
        async def on_prepare(request: web.Request, response: web.StreamResponse) -> None:
            if (not isinstance(response, web.Response)
                    or not isinstance(response.body, bytes)  # No support for Payload
                    or request.path.startswith("/_debugtoolbar")
                    or "text/html" not in response.content_type):
                return
            lr_snippet = LIVE_RELOAD_HOST_SNIPPET.format(get_host(request), config.aux_port)
            dft_logger.debug("appending live reload snippet '%s' to body", lr_snippet)
            response.body += lr_snippet.encode()
            response.headers[CONTENT_LENGTH] = str(len(response.body))
        app.on_response_prepare.append(on_prepare)

    static_path = config.static_url.strip('/')
    if config.infer_host and config.static_path is not None:
        # we set the app key even in middleware to make the switch to production easier and for backwards compat.
        @web.middleware
        async def static_middleware(request: web.Request, handler: Handler) -> web.StreamResponse:
            static_url = 'http://{}:{}/{}'.format(get_host(request), config.aux_port, static_path)
            dft_logger.debug('setting app static_root_url to "%s"', static_url)
            _change_static_url(request.app, static_url)
            return await handler(request)

        app.middlewares.insert(0, static_middleware)

    if config.static_path is not None:
        static_url = 'http://{}:{}/{}'.format(config.host, config.aux_port, static_path)
        dft_logger.debug('settings app static_root_url to "%s"', static_url)
        _set_static_url(app, static_url)