This question already has answers here:
Sending data from HTML form to a Python script in Flask
(2 answers)
Closed 1 year ago.
HTML Code
<!DOCTYPE html>
<html>
<head>
<h1>App</h1>
</head>
<body>
<form action="Test.py" method="GET">
<label for="search">Enter keyword here</label>
<input type="text" name="userInput" required></input>
<input type="submit" value="submit"></input>
</form>
</body>
</html>
Flask Code
from flask import Flask, url_for, request
app = Flask(__name__)
#app.route("extPage.html", methods=['POST', 'GET'])
userinput = request.form("userInput")
print(userinput)
Whenever I run the HTML and submit something, it just returns the python flask code on the webpage. Want I am trying to do is use the userInput tag to create a variable to use in a python program not related. I need the input returned as a string which is why I am testing it with "print(userinput). My goal is to print the submission.
Place the print statement within a function below the route decorator.
something like:
#Don't call html pages. Call routes that return html pages
#app.route("/extPage/", methods=['POST', 'GET'])
def index():
userinput = request.form("userInput")
print(userinput)
return render_template('return_page.html', ui=userinput)
You can find the official documentation's tutorial here. It's what helped me the most when I have gotten stuck.
Related
So, I am building a webapp which takes a link from a shopping website then runs it through a python script which interprets the data, stores it in a database and that populates a table for reference.
I am running into a couple issues:
if I put the link into the front end input (html) then submit it just takes me to "page isn't working HTTP error 405". I'm not sure what to do about that one.
the more pressing issue is that even though I believe I routed the input properly through flask I get this issue when I run the python script alongside the frontend
"RuntimeError: Working outside of request context."
I tried some of the advice mentioned in these existing posts to no avail:
Sending data from HTML form to a Python script in Flask
Connecting python script with html button and flask
I also tried changing the script itself to use getvalue() instead of getvalue when associating it as an input variable for the python script to work with.
this is my route code from app.py
#app.route("/", methods=['POST'])
def getvalue():
HTML_Info = request.form['data_bridge']
return HTML_Info
code for the HTML input
<form name="passdata" action="{{ url_for('getvalue') }}" method="POST">
<input type='text' name="data_bridge" placeholder="paste shoe link here">
<input type="submit">
</form>
and the python code just imports the app file and the getvalue function and then assigns it to a variable.
if you guys could help me sort this out I would greatly appreciate it.
I assume you want to take an input (e.g. shoe link) from the user and then do some operations based on the input.
To access the HTML form from / path you need to enable both GET and POST requests in that route. Otherwise, when you try to access the root path / from your browser, you will get the HTTP Method not allowed error.
app.py:
from flask import Flask, render_template, request
app = Flask(__name__)
def get_value_related_info(value):
return f"You have entered {value}"
#app.route('/', methods=['POST', 'GET'])
def getvalue():
if request.method == "POST":
HTML_Info = request.form['data_bridge']
return get_value_related_info(HTML_Info)
return render_template('form.html', text="")
if __name__ == "__main__":
app.run(debug=True)
Output:
Before form submission:
After form submission:
templates/form.html:
<html>
<head>
<title>Form example</title>
</head>
<body>
<form name="passdata" action="{{ url_for('getvalue') }}" method="POST">
<input type='text' name="data_bridge" placeholder="paste shoe link here">
<input type="submit">
</form>
</body>
</html>
Explanation:
I have mocked the functionality on the user input in get_value_related_info method.
References:
Flask documentation for request object
I am new to Flask. I want to run my Python project, when the start button is pressed from the HTML page and display the string which is returned from the Python code, on the HTML page. I am using Python flask.
This is the HTML file with the button.(The name of the HTML file is json.html)
<!DOCTYPE html>
<html>
<body>
<h1>Smart Job Interviewer</h1>
<button type="button">Start the Interview</button>
</body>
</html>
Following is the Python flask file. newexecutiontest is my python file and run() is the function that I need to run. This function returns a string and I want to display it on the HTML page.
from flask import Flask
from TextToSpeech import newexecutiontest
from flask import render_template
app = Flask(__name__)
#app.route('/')
def index():
return render_template('json.html')
def dynamic_page():
return newexecutiontest.run()
if __name__ == '__main__':
app.run(host='0.0.0.0', port='8000', debug=True)
When I run the code and load the web page it says that "This site can't be reached"
Can someone please help me to achieve the above task.
Thank you in advance.
Try changing the IP to localhost or 127.0.0.1
You should keep the html template under the folder /templates
You could make the button part of a form, so that it is routed back to your python module on click (just printing a string on button click could more easily be done with javascript, but I assume run() performs some logic as well). Also add some input field to the form so you can know it was submitted:
<form method="GET">
<input type="hidden" name="start">
<button type="submit">Start the Interview</button>
</form>
Now in the flask file, you can perform a basic check to see if "start", or whatever name you gave your input, exists in the get request arguments - which would mean the form was submitted. It is possible to pass arguments to an html file, so we will pass None if the form wasn't submitted or the desired string if it was:
from flask import request
#app.route('/')
def index():
return render_template('json.html', test_str=dynamic_page() if request.args.get("start") is not None else None)
And finally, you can check the value of test_str in the html file and print it accordingly, using the jinja templating engine. Logic is declared between {% and %}, while evaluations are declared between {{ and }}. Adding this to the html file where you want the string to be printed should work:
{% if test_str is not none %}
<p>{{ test_str }}</p>
{% endif %}
I just started learning Flask, and as a practice project I wanted to build a simple site that asks the user for their name, and greets them by their name on a new page. I have been unable to get a user's name through a form, and display it on a new page due to to a 'Bad Request' error. My code is below.
This is my index page with the form on it:
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
<h1>Practice index page</h1>
<h2>Welcome to my practice web page.</h2>
<form action = "/firstname">
<p>What's your name?</p>
<input type = "text" name = "yourname"><br>
<input type = "submit" value = "Submit">
</form>
</body>
</html>
This is my application.py file:
from flask import Flask
from flask import render_template, request, redirect
app = Flask(__name__)
#app.route('/')
def hello_world():
return render_template('index.html')
#app.route('/firstname')
def first_name():
yourname = request.form['yourname']
return render_template('firstname.html', name = yourname)
And this is my firstname.html file:
<!DOCTYPE html>
<head>
<title>My name is</title>
</head>
<body>
<h1>Hello</h1>
<h2>Your name is {{name}}.</h2>
</body>
The index page loads fine. The firstname.html template also loads fine when the user's name is hardcoded, it's only when I get it from the form that problems arise.
I have been at this for a few hours, watched YT videos, Googled like crazy, and still can't figure out what's wrong, so I would really appreciate some help!
By default, a Flask route only answers to GET requests. You can tell the first_name view to answer both GET and POST requests like so:
#app.route('/firstname', methods=['GET', 'POST'])
def first_name():
yourname = request.form['yourname']
return render_template('firstname.html', name = yourname)
You also need to set the form method to POST so that yourname is sent as form data (readable in request.form) and not as a URL parameter (readable in request.args).
<form action = "/firstname" method="POST">
<p>What's your name?</p>
<input type = "text" name = "yourname"><br>
<input type = "submit" value = "Submit">
</form>
Use request.args['yourname'] instead of request.form['yourname']
Your index.html form is calling /firstname url with get method and name argument as query string
GET /firstname?yourname=Sunny HTTP/1.1
so you need to access query parameters with request.args['yourname'] & not with request.form['yourname']
You need to pass variables as dict and not directly.
Like this
#app.route('/firstname')
def first_name():
yourname = request.form['yourname']
return render_template('firstname.html', **{"name": "yourname"})
This question already has answers here:
Get the data received in a Flask request
(23 answers)
Closed 5 years ago.
I would like to be able to write a multi-line text in a textarea (HTML), and retrieve this text in python for processing using Flask. Alternatively, I would like to be able to write a multi-line text in a form. I have no clue on using JS, so that won't help me.
How am I to go about doing that?
Render a template with the form and textarea. Use url_for to point the form at the view that will handle the data. Access the data from request.form.
templates/form.html:
<form action="{{ url_for('submit') }}" method="post">
<textarea name="text"></textarea>
<input type="submit">
</form>
app.py:
from flask import Flask, request, render_template
app = Flask(__name__)
#app.route('/')
def index():
return render_template('form.html')
#app.route('/submit', methods=['POST'])
def submit():
return 'You entered: {}'.format(request.form['text'])
Using Python 2.7 and Flask how do I automatically respond to forms? I'm new to using Flask. Specifically, I'd like to render a basic calender on a Flask server and once a date/week is selected print this in the console.
The screen shot below shows I can see this form with the server running and to illustrate I've only included a calender and text input field. On selecting a date/week nothing happens - I only see the dictionary output (highlighted in the red rectangle, bottom image) once I type and press enter within the text field. After which the data is printed in the console and cleared from the form; I'd like the data to remain once entered too.
Screen shot and code shown:
from flask import Flask, render_template, jsonify, request
app = Flask(__name__)
#app.route('/', methods=['GET', 'POST'])
def index():
print request.form
return render_template("index.html")
if __name__ == "__main__":
app.run(debug = True)
and form:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<form action="/", method="post">
Date:<br>
<input type="week" name="date" step="1" min="2015-W30" value="2015-W9">
<br>Name:<br>
<input type="text" name="name"><br>
</form>
</body>
</html>