pur*_*ram 4 html python flask python-2.7 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>
Run Code Online (Sandbox Code Playgroud)
python 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()
Run Code Online (Sandbox Code Playgroud)
如何使用python flask从另一个路由调用带有参数的路由?
您有两个选择:
选择1:使用从路由中获得的参数进行重定向:
import os
from flask import Flask, redirect, url_for
@app.route('/abc/<x>/<y>')
def abc(x, y):
callanothermethod(x,y)
Run Code Online (Sandbox Code Playgroud)
然后您可以将调用的网址重定向到上面的他的路由,如下所示:
@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))
Run Code Online (Sandbox Code Playgroud)
另请参阅有关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)
Run Code Online (Sandbox Code Playgroud)