CS50x threads to aide as a supplementary resource Forums CS50’s Introduction to Computer Science by Harvard University on Edx Week 9: Flask Are GET AND POST method only relevant for forms when it comes to web development using Flask?

  • This topic is empty.
Viewing 1 post (of 1 total)
  • Author
    Posts
  • #2252

    Are GET AND POST method only relevant for forms when it comes to web development using Flask?

    ChatGPT:

    In web development using Flask (a Python web framework), the GET and POST methods are commonly associated with form submissions, but they are not limited to forms. They are HTTP request methods that can be used in various contexts beyond form submissions.

    Here’s how they are typically used in Flask:

    1. GET Method: In Flask, you can define routes (URL endpoints) that handle GET requests using the @app.route decorator. When a client makes a GET request to a specific route, Flask executes the associated view function and returns a response. GET requests are commonly used for retrieving data or rendering HTML templates.

    Example:

    
    
    from flask import Flask
    
    app = Flask(__name__)
    
    @app.route('/')
    def index():
        return 'Hello, World!'
    
    @app.route('/user/<username>')
    def get_user(username):
        return f'Hello, {username}!'
    
    if __name__ == '__main__':
        app.run(debug=True)
    


    1. POST Method: Similarly, you can define routes that handle POST requests. These routes typically handle form submissions or any request where data needs to be sent to the server securely. In Flask, you can access the data sent via POST using the request.form object.

    Example:

    
    
    from flask import Flask, request
    
    app = Flask(__name__)
    
    @app.route('/login', methods=['POST'])
    def login():
        username = request.form['username']
        password = request.form['password']
        # Validate username and password
        return f'Logged in as {username}'
    
    if __name__ == '__main__':
        app.run(debug=True)
    


    So, while forms are a common use case for GET and POST requests in Flask, they can be used in any scenario where data needs to be sent to or retrieved from the server.

Viewing 1 post (of 1 total)
  • You must be logged in to reply to this topic.
Scroll to Top