1

Recently I started a new simple project in Django. I wrote some middleware. but in one of the middlewares, I want to know which URL is called because I have to make a decision which is related to URL.

I used this code:

import os

path = os.environ['PATH_INFO']

but it makes an error which is described below:

    raise KeyError(key) from None
KeyError: 'PATH_INFO'

so how I can know the URL in my middleware?

Saeed
  • 159
  • 3
  • 13

1 Answers1

1

You can obtain the path in the request by using the request.path attribute [Django-doc], or request.path_info attribute [Django-doc]. For example you can print the path with the following simple middleware:

from django.utils.deprecation import MiddlewareMixin

class MyMiddleware(MiddlewareMixin):

    def process_request(self, request):
        print(request.path)

You can make use of the request.schema attribute [Django-doc] to access the schema of the URL (http, https, etc.), and the request.method attribute [Django-doc] to access the method of the request (GET, POST, PUT, PATCH, DELETE, etc.).

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555