Get and Post methods in Python (Flask)

25,035

Solution 1

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

Solution 2

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.

Share:
25,035
codersun3
Author by

codersun3

Updated on November 22, 2020

Comments

  • codersun3
    codersun3 over 3 years

    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.