Retrieve text from textarea in Flask [duplicate] - python

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'])

Related

cannot get html front end to pass input to python script using flask

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

How to run an HTML input as a python variable? [duplicate]

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.

Flask form not validating with HTML [duplicate]

This question already has answers here:
Post values from an HTML form and access them in a Flask view
(2 answers)
Form is never valid with WTForms
(1 answer)
Closed 2 years ago.
I've tried looking through the documentation and other posts on here, though I'm still having trouble.
views.py
#bp.route('/')
def index():
return render_template("index.html")
#bp.route('/newSearch', methods=['GET', 'POST'])
def newSearch():
form = NewSearchForm()
if form.validate_on_submit():
# DB code
return redirect(url_for('newPage.html'))
return render_template('newSearch.html', form=form)
Once the user enters a search query and clicks "submit" it should redirect to the results page. However, It's not validating the form correctly with my current form tag.
index.html
<form action="{{ url_for('newSearch') }}" enctype="multipart/form-data" method="post">
<input class="btn btn-primary" type="submit" value="Search"></input>
</form
The button lives in the index.html. It fails to redirect to newPage.html in the case above. What is missing that's causing it to fail validation? any help would be greatly appreciated!

Flask Post Error 500 (Internal Server Error) [duplicate]

This question already has answers here:
How to debug a Flask app
(14 answers)
Flask application traceback doesn't show up in server log
(4 answers)
Flask view raises TypeError: 'bool' object is not callable
(1 answer)
Closed 4 years ago.
I have a simple form that asks the user to input an email. My goal is to send that email back into Python so that I can append it to a text file.
HTML:
<form method="post" target="frame">
<input name="email" value="{{request.form.text}}" id="email">
<input type="submit" value="Sign Up">
</form>
Flask:
#app.route('/', methods=['GET', 'POST'])
def my_form():
if request.method == "POST":
inputed_email = request.form.get('email')
return inputed_email
return render_template("my-form.html")
Whenever I enter an email into the form, I get this error:
What is preventing the form data from being sent back into Python? Any help is appreciated. Thank you!

Flask POST request returning to main webpage instead of returning result

I want to write a view that asks for some input then returns it as uppercase. I followed the instructions in Send Data from a textbox into Flask?.
The app is hosted using Phusion Passenger via cPanel at example.com/form. When I click Submit, I am sent to example.com. Nothing happens to the text on example.com/form before I am redirected.
What am I doing wrong? Why am I being redirected?
templates/form.html
<form action="." method="POST">
<textarea name="text"></textarea>
<input type="submit">
</form>
form.py
from flask import Flask, request, render_template
app = Flask(__name__)
#app.route('/')
def form():
return render_template('form.html')
#app.route('/', methods=['POST'])
def form_post():
return request.form['text'].upper()
Both the answers you followed had an issue for apps that aren't hosted at the root. (They've been edited now.)
Your app is hosted at /form. A form's action should be an absolute path, not a relative path. Always use url_for to generate URLs and you'll avoid this issue.
<form action="{{ url_for('form_post') }}" method=post>
Since your two views share the same URL, the action can be omitted. A common pattern in this case is to use one view to handle GET and POST.
#app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
return request.form['text'].upper()
return render_template('index.html')

Categories