Flask not activating function - python

I've been using python flask as well as html, in order to create a small website, (just as a hobby while I'm off school), I created a form in html, and saved it within the templates folder of the project. I also then added a function within the python script, so when a button is clicked of the webpage it would redirect the user back to the home page (index.html), however when I have tested the webpage and clicked on the button on the webpage (with the flask server running) a "400 bad request" page is shown
Python Code:
#Python code behind the website
import datetime
from flask import Flask, session, redirect, url_for, escape, request, render_template
print ("started")
def Log(prefix, LogMessage):
timeOfLog = datetime.datetime.now().strftime("%d-%m-%Y %H:%M:%S" + " : ")
logFile = open("Log.log", 'a')
logFile.write("[" + timeOfLog + "][" + prefix + "][" + LogMessage + "] \n")
logFile.close()
app = Flask(__name__)
#app.route('/')
def my_form():
print ("Acessed index")
return render_template("index.html")
#app.route('/', methods=['POST'])
def my_form_post():
text = request.form['text']#requests text from the text form
processed_text = text #does nothing
user = "" #use poss in future to determin user
logFile = open("MessageLog.msglog", 'a')#opens the message log file in append mode
logFile.write(text + "\n")#stores the inputted message in the message log file
logFile.close()
#print (text)
Log("User Message", (user + text))#uses the main log file to store messages aswell as errors
print ("Accessing index")
return render_template("test.html")
#app.route('/test', methods=['POST'])
def test():
#text = request.form['text']
print ("Test page function")
#return "hello"
return render_template("index.html")
if __name__ == '__main__':
app.debug = True
app.run(host='0.0.0.0')
HTML code:
-->
<body>
<h1>Test Page</h1>
<form method="POST">
<input type="submit" name="my-form" value="Send">
</form>
</body>
Stack Track:

You need to post your form to the correct URL:
<body>
<h1>Test Page</h1>
<form method="POST" action='/test'>
<input type="submit" name="my-form" value="Send">
</form>
</body>
By default if you don't add an action attribute to an HTML form it will just perform it's defined method to the URL you are currently on. You can add an action attribute to change that behavior.
You can also do this with the url_for() function. This is a bit safer as URL's tend to change more often than your view method names:
<body>
<h1>Test Page</h1>
<form method="POST" action="{{ url_for('test') }}">
<input type="submit" name="my-form" value="Send">
</form>
</body>
You pass the name of the view method (not it's URL) as a string to the function. Be careful to use the right quotes.
Note that it's slightly confusing to have 2 views for the same URL. Usually something like this is done although YMMV but consider it for your application:
#app.route('/someurl')
def some_view():
if request.method == "POST":
# handle POST
else:
# handle GET

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

Flask : Why does not the HTML submit button redirect the page to the target URL?

I'm new to Flask. This is the content of my login.html file:
<html>
<body>
<form action="localhost:5000/login" method="POST">
<p>Enter name : </p>
<p><input type = "text" name="nm"/></p>
<p><input type = "submit" value="submit"/></p>
</form>
</body>
</html>
This is app.py file:
from flask import Flask, redirect, url_for, request
app = Flask(__name__)
#app.route('/success/<name>')
def success(name):
return "Welcome %s" % name
#app.route('/login', methods = ['POST', 'GET'])
def login():
if request.method == 'POST' :
user = request.form['nm']
return redirect(url_for('success', name = user))
else :
user = request.args.get('nm')
return redirect(url_for('success', name = user))
if __name__ == "__main__":
app.run(debug = True)
When I entered a text in my HTML login form and click the submit it should have redirected to the desired URL but nothing happened.
Edit
After trying with changes suggested by Rogan Josh, i got this error:
File not found
Firefox can’t find the file at /home/hp/flask_practice/{{ url_for('login') }}.
Check the file name for capitalization or other typing errors.
Check to see if the file was moved, renamed or deleted.
Your code can't do anything because you haven't actually served the html from your flask application. You've just double-clicked it and opened the HTML in a browser.
Your html file needs to go in a subdirectory from app.py called "templates". Then change your code to:
from flask import Flask, redirect, url_for, request, render_template
app = Flask(__name__)
#app.route('/success/<name>')
def success(name):
return "Welcome %s" % name
#app.route('/login', methods = ['POST', 'GET'])
def login():
if request.method == 'POST' :
user = request.form['nm']
return redirect(url_for('success', name = user))
else :
user = request.args.get('nm') # THIS DOES NOTHING
return render_template('login.html') # CHANGED HERE
if __name__ == "__main__":
app.run(debug = True)
You should also update your HTML to:
<html>
<body>
<form action="{{ url_for('login') }}" method="POST">
<p>Enter name : </p>
<p><input type = "text" name="nm"/></p>
<p><input type = "submit" value="submit"/></p>
</form>
</body>
</html>
Now open the browser and go to 127.0.0.1:5000/login

Python Flask : url_for to pass the variable to function from form template

I tried this approach to pass the form input variable to function via url_for method. But its not working. can anyone check and let me know whats wrong in this code.
Function:
#app.route('/report_data/<year>/<week>', methods = ['POST'])
def report_data(year,week):
print year
print woy
HTML Code :
<html>
<body>
<form action="{{ url_for('report_data', year=n_year, week=n_woy) }}" method="post">
<h3> Enter the details </h3>
Year :
<input type="text" name="n_year"> <br>
<br>
Week :
<input type="text" name="n_woy"> <br>
<br>
<input type="submit" value="Submit"> <br>
</form>
</body>
</html>
Issue:
Getting "None" for both variable.
Firstly, How do you provide year, week values before submitting them in your HTML code ?
Did you render the HTML template in your function? If not, how does your flask function knows that you were seeking from that specific form?
If this is your Flask app code -
from flask import Flask, render_template, request
app = Flask(__name__)
#app.route('/report_data', methods = ['POST', 'GET'])
def report_data():
if request.method == 'POST':
result = request.form
query_year = result['n_year'].encode('ascii', 'ignore')
query_week = result['n_woy'].encode('ascii', 'ignore')
print(query_year, query_week)
return render_template('so_test.html')
if __name__ == '__main__':
app.run(debug=True)
And opened the URL -
http://127.0.0.1:5000/report_data
And I get this picture.
Once I post the data, I can see this data in my Flask app console.
('2018','08')

How to pass your POST to another URL using Flask

I am trying to get some phrase from the user, and when he/she will press "submit" i want to redirect him/her to another page with his/her name, using Flask. Here is my Python code:
from flask import Flask, redirect, render_template, request, session, url_for
app = Flask(__name__)
#app.route("/", methods = ["POST", "GET"])
def login():
if request.method == "POST":
user = request.form["name"]
return redirect(url_for("success", name=user))
else:
return render_template("login.html")
#app.route("/success", methods = ["POST", "GET"])
def success():
user = request.form.get('name')
return render_template("success.html", name=user)
if __name__ == "__main__":
app.run("0.0.0.0", 8080)
So when i go to my site i am going to "else" branch and do: "render_template("login.html")". Then if i press submit i go into "if" where i am trying to redirect the user to "success.html". Here is my login.html:
<html>
<body>
<form action = "http://ide50-zahar-zagrava.cs50.io:8080/" method = "post">
<p>Enter Name:</p>
<p><input type = "text" name = "name" /></p>
<p><input type = "submit" value = "submit" /></p>
</form>
</body>
</html>
And succes.html:
<html>
<body>
<h1>Hello {{ name }}!</h1>
</body>
</html>
But insted of saying: "Hello " it says: "Hello None".
My main question is how to pass data from one page to another?
I am completely new at Flask and Python, so i can't figure out what's going wrong.
your action from form is wrong.you are sending the form to the index page. you could edit it like:
<form action="{{ url_for('success') }}" method="post">
this way, your form will be sent to the success method.

Flask forms not working

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"})

Categories