我们如何使用python flask从参数调用另一条路径。?

时间:2018-01-08 10:11:57

标签: python html python-2.7 flask python-requests

我发布了一个带有两个输入到python 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>

python烧瓶代码就像。

@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()

如何使用python flask从参数调用其他路径的一条路线?

1 个答案:

答案 0 :(得分:3)

您有两种选择:
选项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中重定向的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)