pythonpython-3.xsanic

Faster way of redirecting all requests to sanic?


I'm attempting to redirect all requests in sanic web server. So, for example, if someone went to localhost:5595/example/hi it would forward to a website. I know how to normally do that in sanic, but it would be to slow to redirect 100 urls. Is there any faster way of doing this?


Solution

  • I am not 100% sure if this is the answer you are looking for. But, if you are asking about making a super crude proxy server in Sanic to redirect all requests, something like this would do (see server1.py).

    # server1.py
    from sanic import Sanic
    from sanic.response import redirect
    
    app = Sanic("server1")
    
    
    @app.route("/<path:path>")
    async def proxy(request, path):
        return redirect(f"http://localhost:9992/{path}")
    
    
    app.run(port=9991)
    

    And so we have a place for traffic to go:

    from sanic import Sanic
    from sanic.response import text
    
    app = Sanic("server1")
    
    
    @app.route("/<foo>/<bar>")
    async def endpoint(request, foo, bar):
        return text(f"Did you know {foo=} and {bar=}?")
    
    
    app.run(port=9992)
    

    Now, let's test it out:

    $ curl localhost:9991/hello/world -Li
    HTTP/1.1 302 Found
    Location: http://localhost:9992/hello/world
    content-length: 0
    connection: keep-alive
    content-type: text/html; charset=utf-8
    
    HTTP/1.1 200 OK
    content-length: 35
    connection: keep-alive
    content-type: text/plain; charset=utf-8
    
    Did you know foo='hello' and bar='world'?