'Python requests library - POST requests takes too long

I have a problem with the python requests library. I try to send a simple POST request to my Keycloak server, to introspect an access token. I tested in in Postman and CURL and both requests are processed very fast (about 100ms). But the requests library somehow takes up to 45 seconds for this single request and I really don't know what causes the issue. In my opinion there seems to be no problem in the request code. And since Postman can handle the same request just fine, I guess there is no server issue as well?
Even with a locally deployed Keycloak server, the request takes way too long.

Any way, here is the code snippet for the request I send. I am processing it inside a django middleware:

  import requests
  
  class TokenMiddleware:
    # Initialization here
    ...

    def introspect_token(self, token):
      payload = {
         "token": token,
         "client_id": self.client_id,
         "client_secret": self.client_secret_key,
      }
      headers = {
        "Content-Type": "application/x-www-form-urlencoded",
        "Authorization": "Bearer " + token
      }
      response = requests.request(
         "POST", self.token_introspection_endpoint, data=payload, headers=headers
      )
      response.json()

Does anybody have a hint what could be causing the issue here?

UPDATE: The Problem seems to be the development server that comes with django. I deployed my app on a gunicorn server and then the requests to keycloak took way less time.



Solution 1:[1]

First, I think you should try run requests code just as a script to exclude the Problem of requests.

Then, maybe you use requests call your server by yourself. If your Django run in dev, just have a thread, then it fail

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 hstk