我的Python脚本中有以下代码:
def cmd_wui(argv, path_to_tx):
"""Run a web UI."""
from flask import Flask, flash, jsonify, render_template, request
import webbrowser
app = Flask(__name__)
@app.route('/tx/index/')
def index():
"""Load start page where you select your project folder
or load history projects from local DB."""
from txclib import get_version
txc_version = get_version()
prj = project.Project(path_to_tx)
# Let's create a resource list from our config file
res_list = []
prev_proj = ''
for idx, res in enumerate(prj.get_resource_list()):
hostname = prj.get_resource_host(res)
username, password = prj.getset_host_credentials(hostname)
return render_template('init.html', txc_version=txc_version, username=username)
另外,我在init.html中有一个HTML表单:
<form>
<input type="text" id="projectFilepath" size="40" placeholder="Spot your project files">
<input type="button" id="spotButton" value="Spot">
</form>
如何从&#34; projectFilepath&#34;传递用户输入?当用户点击&#34; spotButton&#34;在我的python脚本中的变量?
我是Python和Flask的新手,如果我犯了任何错误,请原谅我。
答案 0 :(得分:94)
form
代码需要设置两个属性:
action
:表单数据在提交时发送到的URL。使用url_for
生成它。如果相同的URL处理显示表单并处理数据,则可以省略它。method
:是将数据作为查询字符串(GET)还是表单数据(POST)提交。添加视图以处理表单数据:
@app.route('/handle_data', methods=['POST'])
def handle_data():
projectpath = request.form['projectFilepath']
# your code
# return a response
将表单的action
设置为该视图的网址:
<form action="{{ url_for('handle_data') }}" method="post">
<input type="text" name="projectFilepath">
<input type="submit">
</form>
答案 1 :(得分:55)
您需要一个Flask视图,它将接收POST数据和一个将发送它的HTML表单。
from flask import request
@app.route('/addRegion', methods=['POST'])
def addRegion():
...
return (request.form['projectFilePath'])
<form action="{{ url_for('addRegion') }}" method="post">
Project file path: <input type="text" name="projectFilePath"><br>
<input type="submit" value="Submit">
</form>