Flask get request using value - python

I have the following form:
<form action="{{ url_for('search') }}" method="get">
<input type="text" name="searchbar" placeholder="Search">
</form>
In
#app.route("/search/<string:searchtext>")
def search(searchtext):
...
how would I use the value of searchbar to generate <string:searchtext>? Is there anything I could put as *value* in {{ url_for('search', searchtext=*value*) }}?

A form using the method get sends the parameters values in the URL, such as: http://example.com/search?searchbar=foo
In Flask you can access this value using:
from flask import request
#app.route('/search')
def login():
searchbar = request.args.get('searchbar')
If you want to pass the value in the URL path (/search/<string:searchtext>), then you have to redirect the user (using Javascript or a a link).

Related

Getting user data from flask request method [duplicate]

I have the code below in my Python script:
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)
Also, I have an HTML form in init.html:
<form>
<input type="text" id="projectFilepath" size="40" placeholder="Spot your project files">
<input type="button" id="spotButton" value="Spot">
</form>
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.
The form tag needs some attributes set:
action: The URL that the form data is sent to on submit. Generate it with url_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 to get, 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.
#app.route('/handle_data', methods=['POST'])
def handle_data():
projectpath = request.form['projectFilepath']
# your code
# return a response
Set the form's action to that view's URL using url_for:
<form action="{{ url_for('handle_data') }}" method="post">
<input type="text" name="projectFilepath">
<input type="submit">
</form>
You need a Flask view that will receive POST data and an HTML form that will send it.
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>

How to grab html data from inside a python file in flask [duplicate]

I have the code below in my Python script:
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)
Also, I have an HTML form in init.html:
<form>
<input type="text" id="projectFilepath" size="40" placeholder="Spot your project files">
<input type="button" id="spotButton" value="Spot">
</form>
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.
The form tag needs some attributes set:
action: The URL that the form data is sent to on submit. Generate it with url_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 to get, 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.
#app.route('/handle_data', methods=['POST'])
def handle_data():
projectpath = request.form['projectFilepath']
# your code
# return a response
Set the form's action to that view's URL using url_for:
<form action="{{ url_for('handle_data') }}" method="post">
<input type="text" name="projectFilepath">
<input type="submit">
</form>
You need a Flask view that will receive POST data and an HTML form that will send it.
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>

How to access user Input as GET request and output the responce in HTML page using Flask Python [duplicate]

I have the code below in my Python script:
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)
Also, I have an HTML form in init.html:
<form>
<input type="text" id="projectFilepath" size="40" placeholder="Spot your project files">
<input type="button" id="spotButton" value="Spot">
</form>
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.
The form tag needs some attributes set:
action: The URL that the form data is sent to on submit. Generate it with url_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 to get, 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.
#app.route('/handle_data', methods=['POST'])
def handle_data():
projectpath = request.form['projectFilepath']
# your code
# return a response
Set the form's action to that view's URL using url_for:
<form action="{{ url_for('handle_data') }}" method="post">
<input type="text" name="projectFilepath">
<input type="submit">
</form>
You need a Flask view that will receive POST data and an HTML form that will send it.
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>

Trying to pass two parameters from an html form in flask (in url) to then run in a python program

I'm pretty new to this and I have a python algorithm which I want to run with two parameters that I get from an html form. Here is my html code:
<form action="result/">
<p><input class="w3-input w3-padding-16" method = "post" type="text" placeholder="Playlist URI" required name="URI"></p>
<p><input class="w3-input w3-padding-16" method = "post" type="text" placeholder="Spotify Username" required name="Username"></p>
<p>
<button class="w3-button w3-light-grey w3-padding-large" type="submit">
<i class="fa fa-paper-plane"></i> Submit
</button>
</p>
</form>
It redirects me to http://127.0.0.1:5000/result/?URI=b&Username=c, when I input b and c into the form.
I can't figure out how to accept them as parameters though, and it just returns this error:
404 Not Found
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
My python code looks like this:
#app.route('/result.html/<URI>&<username>')
def result(URI,username):
return render_template("result.html", uri=URI, username=username)
you can access parameters in get request using request in flask
example:
from flask import Flask, request
app = Flask(__name__)
#app.route("/result.html")
def result():
uri = request.args.get("uri")
username = request.args.get("username")

Flask - generate url with parameters in html

I am trying to find how I can pass a URL parameter (not request) into the url_for function, but I cant find it. In the following example, I need to pass the q_id through the form, as I do with incrRight. So, how can I have variables in url_for in this scenario ?
<form action="{{url_for('answer',q_id='5495eb77433f064294361ceb')}}" method="post">
<input type="text" name="incrRight" value="0">
<input type="submit"/>
</form>
This is what I have on my controller:
#app.route('/api/v1.0/question/<string:q_id>/answer', methods = ['POST'])
def answer(q_id):
incrRight = request.form.get('incrRight')
. . .
I need my html form to be able to communicate with the above function, by passing a q_id and the incrRight parameter.
You can add additional form parameters by adding more <input> tags. If the user of the form is not supposed to changed the items, use a <input type="hidden"> element:
<form action="{{ url_for('answer') }}" method="post">
<input type="text" name="incrRight" value="0" />
<input type="hidden" name="q_id" value="5495eb77433f064294361ceb" />
<input type="submit"/>
</form>
This does require that the answer() view can be invoked without the q_id parameter, of course:
#app.route('/api/v1.0/question/answer', methods=['POST'])
#app.route('/api/v1.0/question/<string:q_id>/answer', methods = ['POST'])
def answer(q_id=None):
if q_id is None:
q_id = request.form['q_id']
incrRight = request.form.get('incrRight')
Here a missing q_id parameter in the URL signals to the view that the browser included the question id in the POST body instead.
Another option is for you to write JavaScript code that'll adjust the form action parameter based on the q_id field in the form, but this then requires that your visitors have JavaScript enabled.

Categories