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

2024-04-19 18:42:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在从一个表单向一个路由发送一个POST请求,其中包含两个输入

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

烧瓶代码是这样的

@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中的参数从另一个路由调用一个路由


Tags: totextform路由inputrequesttypecall
1条回答
网友
1楼 · 发布于 2024-04-19 18:42:04

你有两个选择

选项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))

另请参见documentation中关于重定向的部分

选项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)

相关问题 更多 >