首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将url解析为flask中的方法或视图

问如何将url解析为flask中的方法或视图
EN

Stack Overflow用户
提问于 2021-06-21 13:00:40
回答 3查看 70关注 0票数 1

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

在django

代码语言:javascript
复制
from django.urls import resolve
resolve("/hello_world/") # returns view asssociated  /hello_world/

flask有没有类似的功能,可以针对url返回方法?

EN

回答 3

Stack Overflow用户

发布于 2021-06-21 13:08:28

您可能是在寻找redirect函数。

代码语言:javascript
复制
from flask import redirect

def your_function():
    return redirect('/hello_world/')
票数 0
EN

Stack Overflow用户

发布于 2021-06-21 13:15:50

您可以使用flask的redirect方法

代码语言:javascript
复制
from flask import redirect

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

或

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

代码语言:javascript
复制
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 /
票数 0
EN

Stack Overflow用户

发布于 2021-06-21 14:25:41

代码语言:javascript
复制
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模板中使用我们在上述代码中发送的上下文。你不需要使用上下文。

代码语言:javascript
复制
@app.route('/another_x/')
def another():

   # write code here
   return redirect(url_for('frontend')) # Redirects to /
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68062492

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档