Proxy HTTP request to upstream IPython Notebook Tornado server.

def proxy_it(request, port):
    """Proxy HTTP request to upstream IPython Notebook Tornado server."""

    # Check if we have websocket proxy configured
    websocket_proxy = request.registry.settings.get("pyramid_notebook.websocket_proxy", "")
    if websocket_proxy.strip():
        r = DottedNameResolver()
        websocket_proxy = r.maybe_resolve(websocket_proxy)

    if "upgrade" in request.headers.get("connection", "").lower():
        if websocket_proxy:
            return websocket_proxy(request, port)
        else:
            # If we run on localhost on pserve, we should never hit here as requests go directly to IPython Notebook kernel, not us
            raise RuntimeError("Websocket proxy support is not configured.")

    proxy_app = WSGIProxyApplication(port)

    return request.get_response(proxy_app)