CS50x threads to aide as a supplementary resource Forums CS50’s Introduction to Computer Science by Harvard University on Edx Week 9: Flask POST method can be used to send data to the server as well retrieving data from the server to be displayed in an html page?

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

    POST method can be used to send data to the server as well retrieving data from the server to be displayed in an html page?

    ChatGPT:

    Yes, that’s correct! The POST method can be used for both sending data to the server (e.g., submitting a form) and retrieving data from the server to be displayed in an HTML page. Here’s a breakdown:

    1. Sending Data to the Server (Submitting a Form): When you submit a form using the POST method, the form data is sent to the server in the body of the HTTP request. In a Flask application, you can access this data in your route handler using request.form or request.json if the data is in JSON format. You can then process this data on the server, such as storing it in a database, processing it, or performing any necessary operations.

      Example:

    
    
    from flask import Flask, request
    
    app = Flask(__name__)
    
    @app.route('/submit', methods=['POST'])
    def submit():
        name = request.form['name']
        email = request.form['email']
        # Process the form data (e.g., store it in a database)
        return 'Form submitted successfully'
    
    if __name__ == '__main__':
        app.run(debug=True)
    

     

    Retrieving Data from the Server to Display in an HTML Page: After processing the form data on the server, you can render an HTML page to display the results. You can pass the processed data as variables to the HTML template using Flask’s render_template function. In the HTML template, you can then use Jinja2 templating to dynamically display the data.

    Example:

    
    
    from flask import Flask, render_template
    
    app = Flask(__name__)
    
    @app.route('/results', methods=['GET'])
    def results():
        # Retrieve data from the server (e.g., from a database)
        data = {'name': 'John', 'email': 'john@example.com'}
        return render_template('results.html', data=data)
    
    if __name__ == '__main__':
        app.run(debug=True)
    

     

    In the results.html template:

    
    
    <h1>Results</h1>
    <p>Name: {{ data.name }}</p>
    <p>Email: {{ data.email }}</p>
    

    So, with the POST method, you can handle both sending data to the server and retrieving data from the server to be displayed in an HTML page within a Flask application.

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