如何将url解析为烧瓶中的方法或视图

  • 本文关键字:方法 视图 url python flask
  • 更新时间 :
  • 英文 :


来自django背景,我正在尝试获取烧瓶中特定url的方法。

在django,

from django.urls import resolve
resolve("/hello_world/") # returns view asssociated  /hello_world/

烧瓶是否有类似的功能可以针对url返回方法?

您可能在redirect函数之后。

from flask import redirect
def your_function():
return redirect('/hello_world/')

您可以使用烧瓶的重定向方法

from flask import redirect
@app.route('/hello_world/')
def home():
return redirect("/") # Redirects to /

您可以将flask的url_for函数与redirect函数结合使用,以使用视图的方法名称进行重定向。

from flask import redirect, url_for
@app.route('/')
def index():
return render_template('index.html') # Renders the template
@app.route('/hello_world/')
def hello():
return redirect(url_for('index')) # Redirects to /
from flask import redirect, url_for
@app.route('/')
def index():
contex_variable = 5 # as sample
return render_template('frontend.html', context = contex_variable) 
# return render_template('frontend.html') 

我们可以使用jinja在html模板中使用上面代码中发送的上下文。你不必使用上下文。

@app.route('/another_x/')
def another():
# write code here
return redirect(url_for('frontend')) # Redirects to /

最新更新