I have the code below in my Python script:
JavaScript
x
23
23
1
def cmd_wui(argv, path_to_tx):
2
"""Run a web UI."""
3
from flask import Flask, flash, jsonify, render_template, request
4
import webbrowser
5
app = Flask(__name__)
6
7
8
@app.route('/tx/index/')
9
def index():
10
"""Load start page where you select your project folder
11
or load history projects from local DB."""
12
from txclib import get_version
13
txc_version = get_version()
14
prj = project.Project(path_to_tx)
15
16
# Let's create a resource list from our config file
17
res_list = []
18
prev_proj = ''
19
for idx, res in enumerate(prj.get_resource_list()):
20
hostname = prj.get_resource_host(res)
21
username, password = prj.getset_host_credentials(hostname)
22
return render_template('init.html', txc_version=txc_version, username=username)
23
Also, I have an HTML form in init.html:
JavaScript
1
5
1
<form>
2
<input type="text" id="projectFilepath" size="40" placeholder="Spot your project files">
3
<input type="button" id="spotButton" value="Spot">
4
</form>
5
How can I pass the user input from “projectFilepath” when a user clicks “spotButton” on a variable in my python script?
I’m new in Python and Flask, so forgive me if I make any mistakes.
Advertisement
Answer
The form
tag needs some attributes set:
action
: The URL that the form data is sent to on submit. Generate it withurl_for
. It can be omitted if the same URL handles showing the form and processing the data.method="post"
: Submits the data as form data with the POST method. If not given, or explicitly set toget
, the data is submitted in the query string (request.args
) with the GET method instead.enctype="multipart/form-data"
: When the form contains file inputs, it must have this encoding set, otherwise the files will not be uploaded and Flask won’t see them.
The input
tag needs a name
parameter.
Add a view to handle the submitted data, which is in request.form
under the same key as the input’s name
. Any file inputs will be in request.files
.
JavaScript
1
6
1
@app.route('/handle_data', methods=['POST'])
2
def handle_data():
3
projectpath = request.form['projectFilepath']
4
# your code
5
# return a response
6
Set the form’s action
to that view’s URL using url_for
:
JavaScript
1
5
1
<form action="{{ url_for('handle_data') }}" method="post">
2
<input type="text" name="projectFilepath">
3
<input type="submit">
4
</form>
5