- This topic is empty.
Viewing 1 post (of 1 total)
Viewing 1 post (of 1 total)
- You must be logged in to reply to this topic.
› Forums › CS50’s Introduction to Computer Science by Harvard University on Edx › Week 9: Flask › Do I need to import request object before using GET and POST methods in Flask?
ChaGPT:
Yes, you need to import the request object from the flask module in order to access data from incoming requests, including data sent via GET or POST methods. The request object provides access to information such as form data, request headers, and files uploaded via the request.
Here’s an example of how you would import and use the request object to access form data in a Flask route:
[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”markup” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]
from flask import Flask, request
app = Flask(__name__)
@app.route('/login', methods=['POST'])
def login():
username = request.form['username']
password = request.form['password']
# Do something with the username and password
return 'Login successful'
if __name__ == '__main__':
app.run()
[/dm_code_snippet]
In this example, the request.form attribute is used to access the form data sent with the POST request. Similarly, you can use request.args to access data sent via the query string in a GET request.
So, yes, you need to import the request object before using the GET and POST methods in Flask.
