Borislav Hadzhiev
Wed Apr 20 2022·1 min read
Photo by Raychan
The Python "NameError: name 'request' is not defined" occurs when we use the
request
object in Flask without importing it first. To solve the error import
request
before using it - from flask import request
.
# 👇️ import request from flask import Flask, request app = Flask(__name__) @app.route("/") def hello_world(): # 👇️ can use request here print(request.method) return "<p>Hello, World!</p>"
We had to import request
from flask
in order to use it.
request
global object in your request handler functions because the request
object is only populated in an active HTTP request.The global request
object is used to access incoming request data.
Flask parses the incoming request data for us and gives us access to it through
the request
object.
You will most often have to access the method
property on the request
object.
from flask import Flask, request app = Flask(__name__) @app.route("/") def hello_world(): print(request.method) if request.method == 'GET': return "<p>Request method is GET</p>" elif request.method == 'POST': return "<p>Request method is POST</p>" else: return "<p>Request method is not GET or POST</p>"
The method
property returns the method of the HTTP request, e.g. GET
or
POST
.
You can use the method
property on the request
to conditionally return a
different response depending on the HTTP verb.