用 Flask 重写一个 URL

Rewrite a URL with Flask

是否可以用 Flask 重写 URL 例如如果通过此路由收到 POST 请求:

@app.route('/', methods=['GET','POST'])
def main():
    if request.method == 'POST':
        #TODO: rewrite url to something like '/message'
        return render_template('message.html')
    else:
        return render_template('index.html')

我知道我可以使用重定向并设置另一条路线,但我更愿意尽可能简单地修改 url。

我认为您可能对重定向行为感兴趣

from flask import Flask,redirect

然后使用

redirect("http://www.example.com", code=302)

参见:Redirecting to URL in Flask

from flask import Flask, redirect, url_for


app = Flask(__name__)
@app.route("/")
def home():
    return "hello"

@app.route("/admin"):
def admin():
    return redirect(url_for("#name of function for page you want to go to"))

您可以从其他路由调用您的路由端点函数:

# The “target” route:
@route('/foo')
def foo():
    return render_template(...)

# The rewrited route:
@route('/bar')
def bar():
    return foo()

您甚至可以访问 g 等。当 Flask 的路由工具无法执行您想实现的操作时,也可以使用这种方法。

这是这个问题的实际解决方案(但可能是一个肮脏的 hack):

def rewrite(url):
    view_func, view_args = app.create_url_adapter(request).match(url)
    return app.view_functions[view_func](**view_args)

我们调用 URL 调度程序并调用视图函数。

用法:

@app.route('/bar')
def the_rewritten_one():
    return rewrite('/foo')