繁体   English   中英

我们如何在 Flask 中使用参数从另一条路由调用一条路由?

[英]How can we call one route from another route with parameters in Flask?

我从一个表单发送一个 POST 请求,其中有两个输入到 Flask 路由。

  <form action = "http://localhost:5000/xyz" method = "POST">
     <p>x <input type = "text" name = "x" /></p>
     <p>y <input type = "text" name = "y" /></p>
     <p><input type = "submit" value = "submit" /></p>
  </form>

Flask 代码是这样的。

@app.route('/xyz', methods = ['POST', 'GET'])
def xyz():
    if request.method == 'POST':
       x = request.form["x"]
       y = request.form["y"]
       callonemethod(x,y)
    return render_template('index.html', var1=var1, var2=var2)
       #abc(x,y) #can i call abc() like this .i want to call abc() immediately, as it is streaming log of callonemethod(x,y) in console.

@app.route('/abc', methods = ['POST', 'GET'])       
def abc():
    callanothermethod(x,y)
    return render_template('index.html', var1=var3, var2=var4)
    #I want to use that x, y here. also want to call abc() whenever i call xyz()

如何使用 Flask 中的参数从另一条路由调用一条路由?

你有两个选择。

选项 1
使用从调用的路由中获得的参数进行重定向。

如果你有这条路线:

import os
from flask import Flask, redirect, url_for

@app.route('/abc/<x>/<y>')
def abc(x, y):
  callanothermethod(x,y)

您可以像这样重定向到上面的路由:

@app.route('/xyz', methods = ['POST', 'GET'])
def xyz():
    if request.method == 'POST':
       x = request.form["x"]
       y = request.form["y"]
       callonemethod(x,y)
       return redirect(url_for('abc', x=x, y=y))

另请参阅有关 Flask 中重定向的文档

选项 2:
似乎方法abc是从多个不同位置调用的。 这可能意味着从视图中重构它可能是一个好主意:

在 utils.py

from other_module import callanothermethod
def abc(x, y):
  callanothermethod(x,y)

在应用程序/视图代码中:

import os
from flask import Flask, redirect, url_for
from utils import abc

@app.route('/abc/<x>/<y>')
def abc_route(x, y):
  callanothermethod(x,y)
  abc(x, y)

@app.route('/xyz', methods = ['POST', 'GET'])
def xyz():
    if request.method == 'POST':
       x = request.form["x"]
       y = request.form["y"]
       callonemethod(x,y)
       abc(x, y)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM