I'm new to Flask and web development, and I am trying to create a simple app where an array of integers is generated on the server and sent to the client. Here is some sample (working) code in app.py:
from flask import Flask, render_template, request, url_for
import random
app = Flask(__name__)
@app.route('/')
def form():
s_abc = [random.random() for _ in range(40)]
return render_template('abc.html', s_abc=s_abc)
if __name__ == '__main__':
app.run(debug=True)
And here is a (working) snippet of abc.html:
<div>
{{s_abc}}
</div>
My questions are:
How does this work even though there are no GET/POST HTTP methods? I thought that get/post http methods were required for communication between the server and the client (as described here: http://www.tutorialspoint.com/http/http_methods.htm). However, my code works even though I did not write something like this:
@app.route('/', methods=['GET'])
Is there a way to rewrite this so that it uses POST? Apparently, POST is better for dealing with sensitive data, as described here: http://blog.teamtreehouse.com/the-definitive-guide-to-get-vs-post
Thanks.
A GET message is send, and the server returns data. POST. Used to send HTML form data to the server. The data received by the POST method is not cached by the server.
Use request. form to get data when submitting a form with the POST method. Use request. args to get data passed in the query string of the URL, like when submitting a form with the GET method.
GET : to request data from the server. POST : to submit data to be processed to the server.
The default for flask is GET
. You can use methods
to change that:
@app.route('/', methods=['GET', 'POST'])
Read the docs: Flask 1.0.2 documentation
Web applications use different HTTP methods when accessing URLs. You should familiarize yourself with the HTTP methods as you work with Flask. By default, a route only answers to GET requests. You can use the methods argument of the route() decorator to handle different HTTP methods.
The default is GET
. POST
is applicable only if abc.html
has a form and the user submits the value of s_abc
. In your case, you're generating it and rendering the html out.
If you're new to flask, you should check out this complete tutorial. It will show you how to create forms and receive data:
http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world
http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-iii-web-forms
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With