Faster way of redirecting all requests to sanic?

Question:

localhost:5595/example/hi it would forward to a website

Asked By: BaneLeaks

||

Answers:

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'?
Answered By: Adam Hopkins
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.