Reputation: 175
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.
Upvotes: 6
Views: 28415
Reputation: 31339
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.
Upvotes: 10
Reputation: 845
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
Upvotes: 6