Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get and Post methods in Python (Flask)

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:

  1. 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'])
    
  2. 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.

like image 236
codersun3 Avatar asked Jun 26 '15 19:06

codersun3


People also ask

What is get and POST method in Flask?

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.

How do I get a post request in Flask?

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.

What is get and POST method in Python?

GET : to request data from the server. POST : to submit data to be processed to the server.


2 Answers

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.

like image 102
Reut Sharabani Avatar answered Oct 06 '22 00:10

Reut Sharabani


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

like image 35
Subbdue Avatar answered Oct 05 '22 23:10

Subbdue