Python, flask, methods variable not found. Does the variable no longer exist? - python

I am trying to send a form to a python server using flask as the framework, however the methods variable keeps giving me an error that no such variable exists. I have tried googling it but haven't found anything online.
from flask import Flask, request
#app.route('/form', methods=['GET', 'POST'])
def form():
# allow for both POST AND GET
if request.method == 'POST':
language = request.form.get('language')
framework = request.form.get('framework')
return '''
<h1>The language value is: {}</h1>
<h1>The framework value is: {}</h1>'''.format(language, framework)
# otherwise handle the get request
return '''
<form method="POST">
<div><label>Language: <input type="text" name="language"></label></div>
<div><label>Framework: <input type="text" name="framework"></label></div>
<input type="submit" value="Submit">
</form>'
'''

from flask import Flask, request
app = Flask(__name__)
#app.route('/form', methods=['GET', 'POST'])
def form():
# allow for both POST AND GET
if request.method == 'POST':
language = request.form.get('language')
framework = request.form.get('framework')
return '''
<h1>The language value is: {}</h1>
<h1>The framework value is: {}</h1>'''.format(language, framework)
# otherwise handle the get request
return '''
<form method="POST">
<div><label>Language: <input type="text" name="language"></label></div>
<div><label>Framework: <input type="text" name="framework"></label></div>
<input type="submit" value="Submit">
</form>'
'''
if __name__ == '__main__':
app.run(debug=True)
by adding these two code blocks in the code as shown in the above code, the app is working perfectly fine.
app = Flask(__name__)
if __name__=='__main__':
app.run(debug=True)

Related

How to receive HTTP POST requests in Python?

Task:
User types into a form a char e.g. "hello".
this should be send as an post requests to python, because it is later analyzed via a python script
here is my server side code:
from flask import Flask, request
app = Flask(__name__)
#app.route('/', methods=['POST'])
def result():
print(request.form['foo']) # should display 'bar'
return 'Received !' # response to your request.
if __name__ == '__main__':
app.run()
My html code:
<input class="input-text-input" type="text" placeholder="values" name="website">
How can i get the user input from the php form? What would be the best way? The examples in the internet etc. are overloaded. Maybe i have a general mistake.
To make a request from html form to your python flask API, you can do it this way,
HTML FORM
<form action="{{ url_for('addWebsiteUrl') }}" method="post">
<input class="input-text-input" type="text" placeholder="values" name="website">
<input type="submit" value="Submit">
</form>
FLASK API:
from flask import Flask, request
app = Flask(__name__)
#app.route('/', methods=['POST'])
def result():
print(request.form['website']) # should display 'website'
return 'Received !' # response to your request.
if __name__ == '__main__':
app.run()

How to keep same page in Flask

this is a very simple code with Flask. Every time I click submit I go to another page and I lose my input field and my button.
I wonder HOW I can keep the same page and have just a refresh of the page when I have the output. Or if there is any other solution. Thank you
from flask import Flask, render_template_string, request
app = Flask(__name__)
html = """
<div class="form">
<form action="{{url_for('sent')}}" method="POST">
<input title="Title" placeholder="Enter something" type="text" name="line" required> <br>
<button class="go-button" type="submit"> Submit </button>
</form>
</div>
"""
#app.route("/")
def index():
return render_template_string(html)
#app.route("/", methods=['GET', 'POST'])
def sent():
line = None
if request.method == 'POST':
line = request.form['line']
return line
if __name__ == "__main__":
app.run(debug=True)
You can redirect back to the original page after processing the input
Instead of
return line
You can
from flask import redirect, url_for
return redirect(url_for("index"))

404 not found "requested URL was not found"

I'm trying to make a button in sida2 take me to resultat and post the information named MJ from the input form but I get an error 404 The requested URL was not found on the server and I don't understand why. This is the html part:
<form action="/sida2/resultat.html" method="POST">
<input title="" placeholder="MJ/kq foder" type="text" name="MJ" required>
<br>
<button type="submit">Submit</button>
</form>
And this is the python part:
from flask import Flask, render_template, request
app=Flask(__name__)
#app.route('/')
def home():
return(render_template("hemsida.html"))
#app.route('/sida2/', methods=['POST', 'GET'])
def sida2():
return(render_template("andrasidan.html"))
#app.route('/sida2/resultat', methods=['POST'])
def resultat():
if request.method=='POST':
mj= request.form["MJ"]
return(render_template("resultat.html"))
if __name__ =="__main__":
app.run(debug=True)
I assume it's something obvious I'm missing but I just can't seem to find it.
Use url_for to generate URLs to Flask views. The view you want is resultat.
<form action="{{ url_for('resultat') }}" method="POST">
This will generate the appropriate URL for your resultat() function:
#app.route('/sida2/resultat', methods=['POST'])
def resultat():
The URL you currently have in your form action (/sida2/resultat.html) will not work as your code binds to the URL /sida2/resultat instead.
For a quick overview of the benefits of why you should use url_for over hardcoding your URLs, check out the Flask quickstart section on the topic.

Flask flash yields 404 error

I am trying to use Flask's flash functionality when a user click's a button on a form. The code correctly is identifying the button push as a POST request, yet the webpage yields a 404 error. I have narrowed it down to flash() because without it, there is no 404 error. What is the issue here?
init.py
from flask import Flask, render_template, flash, request
app = Flask(__name__)
#app.route('/', methods=["GET", "POST"])
def meter_input():
print request.method
if request.method == "POST":
print request.form['phone']
flash('test')
return render_template("input.html")
if __name__ == "__main__":
app.run()
input.html
<html>
<form method="post">
<fieldset>
<div class="form-group">
<input id="phone" name="phone" type="text" value="" placeholder="">
</div>
<div class="form-group">
<input type="submit" id="update" value="Update Data"/>
</div>
</fieldset>
</form>
<BR><BR>
</html>
flask.flash apparently uses the flask.session. But the flask.session cannot be used without having defined a secret key for your app. You could have found this out if you started your server in debug mode (which you only should not do in production).
To start your server in debug mode use:
app.run(debug=True)
To fix you actual problem define a secret key right after the creation of the Flask object
app = Flask(__name__)
app.secret_key = "Some secret string here"
I still don't know why you got a 404. You should have gotten a 500 for internal server error

Link Python script to HTML form

Ok I have checked some of the related questions and can't seem to find the exact one.
Basically I have pretty much hard-coded a website, there's a tiny bit of use of bootstrap.
I wanted to code a contact form, I've started to learn Python and therefore used Flask to code one.
Right now the form is separate to all of the html files because I coded a separate project.
I know that I could create a full Flask project and redefine all of my html files through the app and have the app generate URL's for it, but that would be a hell of a lot of work at this point for the sake of a contact form.
Is there any way that I can define the form in HTML and have it refer to the Python Flask script?
I have literally no idea how to do this and I can't find an answer anywhere on Google but then I might be searching the wrong thing.
So, here's my HTML:
<form action="routes.py" method="post" class="basic-grey">
<label>
<span>Your Name :</span>
<input id="name" type="text" name="name" placeholder="Your Full Name" />
</label>
<label>
<span>Your Email :</span>
<input id="email" type="email" name="email" placeholder="Valid Email Address" />
</label>
<label>
<span>Message :</span>
<textarea id="message" name="message" placeholder="Your Message to Us"></textarea>
</label>
<label>
<span> </span>
<input type="button" class="button" value="Send" />
</label>
</form>
And here is the Python Flask Script:
# Imported the Flask class and a function render_template
from flask import Flask, render_template, request, flash
from forms import ContactForm
from flask.ext.mail import Message, Mail
import os
mail = Mail()
# Created an instance/object of the Flask class
app = Flask(__name__)
app.secret_key = os.urandom(24)
# Mapped the URL '/' to the function home().
# Now when someone visits this URL, the function home() will execute.
# This uses a decorator to tell Flask which URL will cause the function below it to execute.
app.config['MAIL_SERVER']='smtp.gmail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USERNAME'] = 'fernindustrials#gmail.com'
app.config['MAIL_PASSWORD'] = 'l3d23pp3l1n'
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True
mail.init_app(app)
#app.route('/contact', methods=['GET','POST'])
def contact():
form = ContactForm()
if request.method == 'POST':
if form.validate() == False:
flash('All fields are required.')
return render_template('contact.html', form=form)
else:
msg = Message(form.subject.data, sender='contact#example.com')
msg.recipients = ["fernindustrials#gmail.com"]
msg.body="""
From: %s <%s>
%s
""" % (form.name.data, form.email.data, form.message.data)
mail.send(msg)
return render_template('posted.html')
elif request.method == 'GET':
return render_template('contact.html', form=form)
# Use run() to run our app on a local server.
if __name__ == '__main__':
app.run(debug = True)
In order to not breach the rules I wont post the Forms.py file that I have unless someone needs that to.
Is there anything I need to change or do differently?
Is it even possible?
Also where does the script go in reference to the index.html files, i.e what is the project structure?
The action field in your form tag should be set to an endpoint, not a script. This is unlike PHP, where you do specify the script.
So your form tag may look like:
<form action="/contact" method="POST" class="basic-grey">

Categories

Resources