Fix - NameError: name 'request' is not defined in Python

avatar

Borislav Hadzhiev

Wed Apr 20 20221 min read

banner

Photo by Raychan

Fix - NameError: name 'request' is not defined in Python #

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.

main.py
# 👇️ 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.

Note that you should only use the 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.

main.py
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.

Use the search field on my Home Page to filter through my more than 1,000 articles.