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()
Related
from flask import Flask, render_template,request
app = Flask(__name__)
#app.route('/',methods=['post'])
def main():
if (request.method=="POST"):
text=request.form('write')
if(text==None):
text=""
else:
text=""
return render_template('form.html',text=text)
if __name__ == "__main__":
app.run(debug=True)
I want to receive only POST method. So I set method option to methods=["post"]. But it always sends HTTP 405 Not Allowed Method error.
<html>
<head>
<title>Using Tag</title>
</head>
<body>
<form method="POST">
<input type="text" name="write">
<input type="submit">
</form>
{{ text }}
</body>
</html>
I want to know reason why this application only sends HTTP 405 response.
To access the HTML form from / path you need to enable both GET and POST request 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__)
#app.route('/', methods=['POST', 'GET'])
def main():
text = ""
if request.method == "POST":
text = request.form['username']
return render_template('form.html', text=text)
if __name__ == "__main__":
app.run(debug=True)
templates/form.html:
<html>
<head>
<title>Using Tag</title>
</head>
<body>
<form method="POST">
<input type="text" name="write">
<input type="submit">
</form>
{{ text }}
</body>
</html>
Output:
Explanation (Updated):
To access the form value use request.form['INPUT_FIELD_NAME'].
We are making GET and POST requests to the / route. So, we set GET and POST requests in the methods options of the / route. When we are viewing the page using the browser, we make GET request to that page. When we submit the form, we make POST request to that page. In this case, we are storing the form value in the text variable and pass the value to the template. For GET request we are showing the empty text value.
The above snippet is the same as the following snippet:
from flask import Flask, render_template, request
app = Flask(__name__)
#app.route('/', methods=['POST', 'GET'])
def main():
if request.method == "POST":
text = request.form['username']
return render_template('form.html', text=text)
elif request.method == "GET":
return render_template('form.html', text="")
if __name__ == "__main__":
app.run(debug=True)
References:
Flask documentation for request object
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)
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"))
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.
from flask import *
from twilio import twiml
from twilio.rest import TwilioRestClient
from flask import render_template
import os
#Pull in configuration from system environment variables
TWILIO_ACCOUNT_SID = os.environ.get('Axxxxxx')
TWILIO_AUTH_TOKEN = os.environ.get('Sxxxxxxxxx')
TWILIO_NUMBER = os.environ.get('xxxxxxx')
# create an authenticated client that can make requests to Twilio for your
# account.
#client = TwilioRestClient(account='Axxxxx', token'sxxxxxxxx')
#create a flask web app
app = Flask(__name__)
client = TwilioRestClient(account='Axxxxx', token='Sxxxxx')
#app.route('/')
def homepage():
return render_template('index.html')
#Handling a post request to send text messages.
#app.route('/message', methods=['POST', 'GET'])
def message():
# Send a text message to the number provided
if request.method == 'POST':
message = client.sms.messages.create(to=request.form['Phone_number'],
from_=TWILIO_NUMBER,
body=request.form['body'])
return render_template('message.html')
if __name__ == '__main__':
# Note that in production, you would want to disable debugging
app.run(debug=True)
I am using flask. When i input the number and the text message it gives me this error
Method Not Allowed
The method is not allowed for the requested URL.
You're posting to the wrong endpoint. Your form should look like this:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Send an SMS</title>
</head>
<body>
<form action="/message" method="POST">
Cell phone number: <input name="phone_number" type="text" />
Text in here: <input name="body" type="text" />
<button type="submit">Send Text</button>
</form>
</script>
</body>
</html>
(Above, action was changed from / to /message.)
Note: if this is a template run through flask.render_template, you should change
<form action="/message" method="POST">
to
<form action="{{ url_for('message') }}" method="POST">
This is a more sustainable way to use urls in flask, and it will reduce your overhead if you ever need to change the value.