Passing Variable from HTML to Python/Flask - python

Let me try this again. I want to enter a variable into my HTML form to submit, so far from reading the link here How to display a variable in HTML I've tried the following code, which is inside of main.html
<form>
Asset Tag:<br>
<input type="text" name="Asset Tag"><br>
<input type="submit" value="Submit">
<form action="{{ asset_tag }}" method="get">
</form>
I then have a python script that goes like this,
from flask import Flask, render_template
app = Flask('server')
#app.route('/py')
def server():
return render_template('main.html')
#API URL
JSS_API = 'https://apiresource.com'
#Pre-Defined username and password
username = 'username'
password = 'password'
#Ask User for the Asset tag
asset_tag = {{ }}
After the asset tag is entered it just searches through a JSON file for match, the rest doesn't matter so much so I didn't include the next piece of the script.
So Flask renders my HTML just fine and I can submit a value but it's not being passed back to the script, which makes sense as I'm doing the opposite of the link I provided, but I just can't not think of how it's done. Any suggestions?

You have a few issues that I've outlined below. Overall though, the frontend is passing the variable to the backend, it's just that the variables are only accessible via the request object from within the route to which the data is passed.
I am not sure why you have a <form> nested within a <form> here, but you'll want to remove the inner one since it's not doing anything.
You want to setup your form to POST the data to your backend when submitted. If you don't specify an action, then it will POST to the same page the same page that you're currently viewing.
<form method="POST">
Asset Tag:<br>
<input type="text" name="tag"><br>
<input type="submit" value="Submit">
</form>
You need to setup your route to accept a POST request so that it can receive data from the form on your page. See here for more information on HTTP methods.
#app.route('/py', methods=['GET', 'POST'])
Inside of your route, you'll want to check whether it was a GET request (and load a normal page) or whether it was a POST (form data was sent so we should use it)
from flask import request
#app.route('/py', methods=['GET', 'POST'])
def server():
if request.method == 'POST':
# Then get the data from the form
tag = request.form['tag']
# Get the username/password associated with this tag
user, password = tag_lookup(tag)
# Generate just a boring response
return 'The credentials for %s are %s and %s' % (tag, user, password)
# Or you could have a custom template for displaying the info
# return render_template('asset_information.html',
# username=user,
# password=password)
# Otherwise this was a normal GET request
else:
return render_template('main.html')

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>

Flask: Is it possible to Mask a URL with variables?

I want to pass variables from a site to another.
This is no problem, as there are many ways to do it.
I'm struggling though, in how I can 'hide' these variables in the URL, and yet be able to get the values.
Ex.:
If I use 'request.args.get':
#page.route('/users', methods=['GET', 'POST'])
def users():
user = request.args.get('user')
return render_template('users.html', user=user)
When I click in the link, the URL generated is:
http://localhost:5000/users?user=john
My goal is to access the 'users' page, in the 'John' section, but what the user will see in the URL path is only http://localhost:5000/users
I was able to achieve my goal using:
window.history.pushState({"html":response.html,"pageTitle":response.pageTitle},"", "/users/");
I'm no Web Dev'er, just a Python/Flask enthusiast and know that 'window.history.pushState()' is meant for other purposes. I'm also aware that it a HTML5 Feature and not all browsers are compatible. But hey, it did the trick ;) .
Unless someone point out reasons I shouldn't be using this approach, this is my solution.
Thanks all for your time
If you'd only want to hide the variable name then you could use converters to create a route like 'users/<str:username>'. Your url would be http://localhost:5000/users/john.
Your can find the documentation here: http://exploreflask.com/en/latest/views.html#built-in-converters
Note that hiding the variables completely would mean, that your users would lose the ability to bookmark the page they are on. Additionaly if they bookmark /users anyways, you would have to catch the case that your variable is not sent or run into errors.
Post method can hide data and variables from URL. So you need to integrate it in your project. Here is an example.
app.py:
from flask import Flask, render_template, request
app = Flask(__name__)
#app.route('/users', methods=['GET', 'POST'])
def show_users():
if request.method == 'POST':
username = request.form.get("username", None)
return render_template('post_example.html', username = username)
else:
return render_template('post_example.html')
if __name__ == '__main__':
app.run(debug = True)
post_example.html:
<html>
<head></head>
<body>
{% if username %}
Passed username: {{ username }}
{% endif %}
<form action="/users" method="post">
Username: <input type="text" name="username">
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
Output:
You can check the HTTP methods in Flask official documentation here

Flask add DB entry using a form

I'm a beginner learning FLASK. I'm making an app and for it I've created a DB model User, and an HTML/ JS form that takes input. What I want is to use the form information to create a new entry in the database but I am unsure on how to do it. I tried to do this
#app.route('/add_to_db')
def add_to_db():
email = request.form['email']
activated = 0;
user = models.User(email= email, activated = 0)
db.session.add(user)
db.session.commit()
HTML Code:
<form onsubmit="return validateEmail(document.getElementById('email').value)" action="{{ url_for("add_to_db") }}" method="post">
Please input your email adress: <input id="email">
<input type="submit">
</form>
<script>
function validateEmail(email) {
var re = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
return(re.test(email));
}
</script>
But this gave me a 405 Method not allowed error.
A 405 error means "method not allowed". As you are sending form data, you are using a POST request and need to allow POST requests. By default only GET requests are allowed. Change the line #app.route('/add_to_db') to #app.route('/add_to_db', methods=['POST']).

Categories