How to get post data in python flask?

by lavina.marks , in category: Python , 2 years ago

How to get post data in python flask?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by woodrow , a year ago

@lavina.marks you can get post data from the request in Python Flask. here is code as an example:


1
2
3
4
5
6
@app.route("/contact", methods=['GET', 'POST'])
def contact():
    if request.method == 'POST':
        print(request.form['email'])
        print(request.form['username'])
    return render_template("contact.html")

Member

by khalid , 9 months ago

@lavina.marks 

To retrieve posted data in Flask, you can use the request.form or request.get_json() methods. Here's an example of how you can get post data in Flask:

  1. Begin by importing the necessary libraries:
1
from flask import Flask, request


  1. Create a Flask application:
1
app = Flask(__name__)


  1. Define a route that accepts POST requests:
1
2
@app.route('/submit', methods=['POST'])
def submit():


  1. Use the request.form method to get the form data:
1
2
    username = request.form.get('username')
    password = request.form.get('password')


  1. Alternatively, use the request.get_json() method to get JSON data:
1
2
3
    data = request.get_json()
    username = data['username']
    password = data['password']


  1. Handle and process the data as needed:
1
2
    # Process the data
    return f"Received username: {username}, password: {password}"


Note: To retrieve JSON data, remember to include the appropriate Content-Type: application/json header in your request.

  1. Run the Flask application:
1
2
if __name__ == '__main__':
    app.run()


Now, when you make a POST request to the /submit endpoint, you can access the posted data using request.form or request.get_json() in your Flask application.