【问题标题】:Faster way of redirecting all requests to sanic?将所有请求重定向到 sanic 的更快方法?
【发布时间】:2021-02-22 18:15:05
【问题描述】:

我正在尝试重定向 sanic 网络服务器中的所有请求。因此,例如,如果有人转到localhost:5595/example/hi,它将转发到一个网站。我知道如何在sanic 中正常执行此操作,但是重定向 100 个网址会很慢。有没有更快的方法?

【问题讨论】:

  • 你是什么意思?你有例子吗?
  • 为什么你认为它会很慢?你真的试过了吗?或者你的意思是打字太多了?您可以自己进行路由管理,以避免拥有 100 个 @app.get 函数。

标签: python python-3.x sanic


【解决方案1】:

我不能 100% 确定这是否是您正在寻找的答案。但是,如果您想在 Sanic 中创建一个超级粗略的代理服务器来重定向所有请求,那么可以这样做(参见 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)

所以我们有一个交通去处:

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

【讨论】:

    猜你喜欢
    • 2013-02-15
    • 2016-10-23
    • 1970-01-01
    • 2017-12-19
    • 2012-12-17
    • 2013-11-26
    • 2016-11-30
    • 2012-11-16
    • 2014-06-30
    相关资源
    最近更新 更多