更快地将所有请求重定向到sanic?

2024-05-15 18:53:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试重定向sanicweb服务器中的所有请求。例如,如果有人去localhost:5595/example/hi,它会转发到一个网站。我知道如何在sanic中正常地做到这一点,但是重定向100个URL会很慢。有没有更快的方法


Tags: 方法服务器localhosturl网站examplesanichi
1条回答
网友
1楼 · 发布于 2024-05-15 18:53:09

我不是100%确定这是否是你想要的答案。但是,如果您想在Sanic中创建一个超级粗糙的代理服务器来重定向所有请求,那么类似的方法就可以了(请参见^{

# 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)

因此,我们有一个交通的去处:

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)

现在,让我们测试一下:

$ 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'?

相关问题 更多 >