django Middleware to handle crossxhr requests is not working










1














I wrote a middleware for Django 2.1 to handle cross-domain XHR requests, but it's not working, in fact, it's not even getting called for requests or response and does n't print anything.



Settings.py



XS_SHARING_ALLOWED_METHODS = ['POST', 'GET', 'OPTIONS', 'PUT', 'DELETE']
XS_SHARING_ALLOWED_ORIGINS = "*"

MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'app_name.middleware.crossdomainxhr.XsSharing',
]


crossdomainxhr.py



import logging
from django import http
from django.conf import settings

try:
XS_SHARING_ALLOWED_ORIGINS = settings.XS_SHARING_ALLOWED_ORIGINS
except AttributeError:
XS_SHARING_ALLOWED_ORIGINS = '*'

try:
XS_SHARING_ALLOWED_METHODS = settings.XS_SHARING_ALLOWED_METHODS
except AttributeError:
XS_SHARING_ALLOWED_METHODS = ['POST', 'GET', 'OPTIONS', 'PUT', 'DELETE']

try:
XS_SHARING_ALLOWED_HEADERS = settings.XS_SHARING_ALLOWED_HEADERS
except:
XS_SHARING_ALLOWED_HEADERS = ['Content-Type', '*']

try:
XS_SHARING_ALLOWED_CREDENTIALS =
settings.XS_SHARING_ALLOWED_CREDENTIALS
except AttributeError:
XS_SHARING_ALLOWED_CREDENTIALS = 'true'


class XsSharing:
"""
This middleware allows cross-domain XHR using the html5 postMessage
API.
"""
**EDIT**
def __init__(self, get_response):
print('Hi, I am middleware')
self.get_response = get_response

def __call__(self, request):
print('hello')
self.process_request(request)
response = self.get_response(request)
response = self.process_response(request, response)
return response
def process_request(self, request):
print('calling request section')
if 'HTTP_ACCESS_CONTROL_REQUEST_METHOD' in request.META:
response = http.HttpResponse()
response['Access-Control-Allow-Origin'] =
XS_SHARING_ALLOWED_ORIGINS
response['Access-Control-Allow-Methods'] =
",".join(XS_SHARING_ALLOWED_METHODS)
response['Access-Control-Allow-Headers'] =
",".join(XS_SHARING_ALLOWED_HEADERS)
response['Access-Control-Allow-Credentials'] =
XS_SHARING_ALLOWED_CREDENTIALS
return response

return None

def process_response(self, request, response):
print('calling response')
response['Access-Control-Allow-Origin'] =
XS_SHARING_ALLOWED_ORIGINS
response['Access-Control-Allow-Methods'] =
",".join(XS_SHARING_ALLOWED_METHODS)
response['Access-Control-Allow-Headers'] =
",".join(XS_SHARING_ALLOWED_HEADERS)
response['Access-Control-Allow-Credentials'] =
XS_SHARING_ALLOWED_CREDENTIALS

return response


Problem is if I call some URL of my app from another Django app then the request get blocked, Does anyone have any idea where I'm going wrong in this?










share|improve this question




























    1














    I wrote a middleware for Django 2.1 to handle cross-domain XHR requests, but it's not working, in fact, it's not even getting called for requests or response and does n't print anything.



    Settings.py



    XS_SHARING_ALLOWED_METHODS = ['POST', 'GET', 'OPTIONS', 'PUT', 'DELETE']
    XS_SHARING_ALLOWED_ORIGINS = "*"

    MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'app_name.middleware.crossdomainxhr.XsSharing',
    ]


    crossdomainxhr.py



    import logging
    from django import http
    from django.conf import settings

    try:
    XS_SHARING_ALLOWED_ORIGINS = settings.XS_SHARING_ALLOWED_ORIGINS
    except AttributeError:
    XS_SHARING_ALLOWED_ORIGINS = '*'

    try:
    XS_SHARING_ALLOWED_METHODS = settings.XS_SHARING_ALLOWED_METHODS
    except AttributeError:
    XS_SHARING_ALLOWED_METHODS = ['POST', 'GET', 'OPTIONS', 'PUT', 'DELETE']

    try:
    XS_SHARING_ALLOWED_HEADERS = settings.XS_SHARING_ALLOWED_HEADERS
    except:
    XS_SHARING_ALLOWED_HEADERS = ['Content-Type', '*']

    try:
    XS_SHARING_ALLOWED_CREDENTIALS =
    settings.XS_SHARING_ALLOWED_CREDENTIALS
    except AttributeError:
    XS_SHARING_ALLOWED_CREDENTIALS = 'true'


    class XsSharing:
    """
    This middleware allows cross-domain XHR using the html5 postMessage
    API.
    """
    **EDIT**
    def __init__(self, get_response):
    print('Hi, I am middleware')
    self.get_response = get_response

    def __call__(self, request):
    print('hello')
    self.process_request(request)
    response = self.get_response(request)
    response = self.process_response(request, response)
    return response
    def process_request(self, request):
    print('calling request section')
    if 'HTTP_ACCESS_CONTROL_REQUEST_METHOD' in request.META:
    response = http.HttpResponse()
    response['Access-Control-Allow-Origin'] =
    XS_SHARING_ALLOWED_ORIGINS
    response['Access-Control-Allow-Methods'] =
    ",".join(XS_SHARING_ALLOWED_METHODS)
    response['Access-Control-Allow-Headers'] =
    ",".join(XS_SHARING_ALLOWED_HEADERS)
    response['Access-Control-Allow-Credentials'] =
    XS_SHARING_ALLOWED_CREDENTIALS
    return response

    return None

    def process_response(self, request, response):
    print('calling response')
    response['Access-Control-Allow-Origin'] =
    XS_SHARING_ALLOWED_ORIGINS
    response['Access-Control-Allow-Methods'] =
    ",".join(XS_SHARING_ALLOWED_METHODS)
    response['Access-Control-Allow-Headers'] =
    ",".join(XS_SHARING_ALLOWED_HEADERS)
    response['Access-Control-Allow-Credentials'] =
    XS_SHARING_ALLOWED_CREDENTIALS

    return response


    Problem is if I call some URL of my app from another Django app then the request get blocked, Does anyone have any idea where I'm going wrong in this?










    share|improve this question


























      1












      1








      1







      I wrote a middleware for Django 2.1 to handle cross-domain XHR requests, but it's not working, in fact, it's not even getting called for requests or response and does n't print anything.



      Settings.py



      XS_SHARING_ALLOWED_METHODS = ['POST', 'GET', 'OPTIONS', 'PUT', 'DELETE']
      XS_SHARING_ALLOWED_ORIGINS = "*"

      MIDDLEWARE_CLASSES = [
      'django.middleware.security.SecurityMiddleware',
      'django.contrib.sessions.middleware.SessionMiddleware',
      'django.middleware.common.CommonMiddleware',
      'django.middleware.csrf.CsrfViewMiddleware',
      'django.contrib.auth.middleware.AuthenticationMiddleware',
      'django.contrib.messages.middleware.MessageMiddleware',
      'django.middleware.clickjacking.XFrameOptionsMiddleware',
      'app_name.middleware.crossdomainxhr.XsSharing',
      ]


      crossdomainxhr.py



      import logging
      from django import http
      from django.conf import settings

      try:
      XS_SHARING_ALLOWED_ORIGINS = settings.XS_SHARING_ALLOWED_ORIGINS
      except AttributeError:
      XS_SHARING_ALLOWED_ORIGINS = '*'

      try:
      XS_SHARING_ALLOWED_METHODS = settings.XS_SHARING_ALLOWED_METHODS
      except AttributeError:
      XS_SHARING_ALLOWED_METHODS = ['POST', 'GET', 'OPTIONS', 'PUT', 'DELETE']

      try:
      XS_SHARING_ALLOWED_HEADERS = settings.XS_SHARING_ALLOWED_HEADERS
      except:
      XS_SHARING_ALLOWED_HEADERS = ['Content-Type', '*']

      try:
      XS_SHARING_ALLOWED_CREDENTIALS =
      settings.XS_SHARING_ALLOWED_CREDENTIALS
      except AttributeError:
      XS_SHARING_ALLOWED_CREDENTIALS = 'true'


      class XsSharing:
      """
      This middleware allows cross-domain XHR using the html5 postMessage
      API.
      """
      **EDIT**
      def __init__(self, get_response):
      print('Hi, I am middleware')
      self.get_response = get_response

      def __call__(self, request):
      print('hello')
      self.process_request(request)
      response = self.get_response(request)
      response = self.process_response(request, response)
      return response
      def process_request(self, request):
      print('calling request section')
      if 'HTTP_ACCESS_CONTROL_REQUEST_METHOD' in request.META:
      response = http.HttpResponse()
      response['Access-Control-Allow-Origin'] =
      XS_SHARING_ALLOWED_ORIGINS
      response['Access-Control-Allow-Methods'] =
      ",".join(XS_SHARING_ALLOWED_METHODS)
      response['Access-Control-Allow-Headers'] =
      ",".join(XS_SHARING_ALLOWED_HEADERS)
      response['Access-Control-Allow-Credentials'] =
      XS_SHARING_ALLOWED_CREDENTIALS
      return response

      return None

      def process_response(self, request, response):
      print('calling response')
      response['Access-Control-Allow-Origin'] =
      XS_SHARING_ALLOWED_ORIGINS
      response['Access-Control-Allow-Methods'] =
      ",".join(XS_SHARING_ALLOWED_METHODS)
      response['Access-Control-Allow-Headers'] =
      ",".join(XS_SHARING_ALLOWED_HEADERS)
      response['Access-Control-Allow-Credentials'] =
      XS_SHARING_ALLOWED_CREDENTIALS

      return response


      Problem is if I call some URL of my app from another Django app then the request get blocked, Does anyone have any idea where I'm going wrong in this?










      share|improve this question















      I wrote a middleware for Django 2.1 to handle cross-domain XHR requests, but it's not working, in fact, it's not even getting called for requests or response and does n't print anything.



      Settings.py



      XS_SHARING_ALLOWED_METHODS = ['POST', 'GET', 'OPTIONS', 'PUT', 'DELETE']
      XS_SHARING_ALLOWED_ORIGINS = "*"

      MIDDLEWARE_CLASSES = [
      'django.middleware.security.SecurityMiddleware',
      'django.contrib.sessions.middleware.SessionMiddleware',
      'django.middleware.common.CommonMiddleware',
      'django.middleware.csrf.CsrfViewMiddleware',
      'django.contrib.auth.middleware.AuthenticationMiddleware',
      'django.contrib.messages.middleware.MessageMiddleware',
      'django.middleware.clickjacking.XFrameOptionsMiddleware',
      'app_name.middleware.crossdomainxhr.XsSharing',
      ]


      crossdomainxhr.py



      import logging
      from django import http
      from django.conf import settings

      try:
      XS_SHARING_ALLOWED_ORIGINS = settings.XS_SHARING_ALLOWED_ORIGINS
      except AttributeError:
      XS_SHARING_ALLOWED_ORIGINS = '*'

      try:
      XS_SHARING_ALLOWED_METHODS = settings.XS_SHARING_ALLOWED_METHODS
      except AttributeError:
      XS_SHARING_ALLOWED_METHODS = ['POST', 'GET', 'OPTIONS', 'PUT', 'DELETE']

      try:
      XS_SHARING_ALLOWED_HEADERS = settings.XS_SHARING_ALLOWED_HEADERS
      except:
      XS_SHARING_ALLOWED_HEADERS = ['Content-Type', '*']

      try:
      XS_SHARING_ALLOWED_CREDENTIALS =
      settings.XS_SHARING_ALLOWED_CREDENTIALS
      except AttributeError:
      XS_SHARING_ALLOWED_CREDENTIALS = 'true'


      class XsSharing:
      """
      This middleware allows cross-domain XHR using the html5 postMessage
      API.
      """
      **EDIT**
      def __init__(self, get_response):
      print('Hi, I am middleware')
      self.get_response = get_response

      def __call__(self, request):
      print('hello')
      self.process_request(request)
      response = self.get_response(request)
      response = self.process_response(request, response)
      return response
      def process_request(self, request):
      print('calling request section')
      if 'HTTP_ACCESS_CONTROL_REQUEST_METHOD' in request.META:
      response = http.HttpResponse()
      response['Access-Control-Allow-Origin'] =
      XS_SHARING_ALLOWED_ORIGINS
      response['Access-Control-Allow-Methods'] =
      ",".join(XS_SHARING_ALLOWED_METHODS)
      response['Access-Control-Allow-Headers'] =
      ",".join(XS_SHARING_ALLOWED_HEADERS)
      response['Access-Control-Allow-Credentials'] =
      XS_SHARING_ALLOWED_CREDENTIALS
      return response

      return None

      def process_response(self, request, response):
      print('calling response')
      response['Access-Control-Allow-Origin'] =
      XS_SHARING_ALLOWED_ORIGINS
      response['Access-Control-Allow-Methods'] =
      ",".join(XS_SHARING_ALLOWED_METHODS)
      response['Access-Control-Allow-Headers'] =
      ",".join(XS_SHARING_ALLOWED_HEADERS)
      response['Access-Control-Allow-Credentials'] =
      XS_SHARING_ALLOWED_CREDENTIALS

      return response


      Problem is if I call some URL of my app from another Django app then the request get blocked, Does anyone have any idea where I'm going wrong in this?







      python django






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 12 at 10:10

























      asked Nov 12 at 10:03









      parvez

      419214




      419214






















          1 Answer
          1






          active

          oldest

          votes


















          2














          MIDDLEWARE_CLASSES was deprecated in Django 1.10 and removed in Django 2.0. You should use the MIDDLEWARE setting and a new-style middleware class.






          share|improve this answer




















          • edited the question as per latest doc, but still not working can you again have a look please
            – parvez
            Nov 12 at 10:11











          • Did you update the setting name? Does it print any of your debugging messages?
            – Daniel Roseman
            Nov 12 at 10:14










          • No it did n't print anything, my setting name will be 'app_name.middleware.crossdomainxhr.XsSharing'. right? MIddleware is the directory name under my app folder
            – parvez
            Nov 12 at 10:16











          • I meant, did you change the name of the setting from MIDDLEWARE_CLASSES to MIDDLEWARE?
            – Daniel Roseman
            Nov 12 at 10:23










          • It worked, you saved my day, thanks
            – parvez
            Nov 12 at 10:28










          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53259812%2fdjango-middleware-to-handle-crossxhr-requests-is-not-working%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          2














          MIDDLEWARE_CLASSES was deprecated in Django 1.10 and removed in Django 2.0. You should use the MIDDLEWARE setting and a new-style middleware class.






          share|improve this answer




















          • edited the question as per latest doc, but still not working can you again have a look please
            – parvez
            Nov 12 at 10:11











          • Did you update the setting name? Does it print any of your debugging messages?
            – Daniel Roseman
            Nov 12 at 10:14










          • No it did n't print anything, my setting name will be 'app_name.middleware.crossdomainxhr.XsSharing'. right? MIddleware is the directory name under my app folder
            – parvez
            Nov 12 at 10:16











          • I meant, did you change the name of the setting from MIDDLEWARE_CLASSES to MIDDLEWARE?
            – Daniel Roseman
            Nov 12 at 10:23










          • It worked, you saved my day, thanks
            – parvez
            Nov 12 at 10:28















          2














          MIDDLEWARE_CLASSES was deprecated in Django 1.10 and removed in Django 2.0. You should use the MIDDLEWARE setting and a new-style middleware class.






          share|improve this answer




















          • edited the question as per latest doc, but still not working can you again have a look please
            – parvez
            Nov 12 at 10:11











          • Did you update the setting name? Does it print any of your debugging messages?
            – Daniel Roseman
            Nov 12 at 10:14










          • No it did n't print anything, my setting name will be 'app_name.middleware.crossdomainxhr.XsSharing'. right? MIddleware is the directory name under my app folder
            – parvez
            Nov 12 at 10:16











          • I meant, did you change the name of the setting from MIDDLEWARE_CLASSES to MIDDLEWARE?
            – Daniel Roseman
            Nov 12 at 10:23










          • It worked, you saved my day, thanks
            – parvez
            Nov 12 at 10:28













          2












          2








          2






          MIDDLEWARE_CLASSES was deprecated in Django 1.10 and removed in Django 2.0. You should use the MIDDLEWARE setting and a new-style middleware class.






          share|improve this answer












          MIDDLEWARE_CLASSES was deprecated in Django 1.10 and removed in Django 2.0. You should use the MIDDLEWARE setting and a new-style middleware class.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 12 at 10:07









          Daniel Roseman

          443k41574629




          443k41574629











          • edited the question as per latest doc, but still not working can you again have a look please
            – parvez
            Nov 12 at 10:11











          • Did you update the setting name? Does it print any of your debugging messages?
            – Daniel Roseman
            Nov 12 at 10:14










          • No it did n't print anything, my setting name will be 'app_name.middleware.crossdomainxhr.XsSharing'. right? MIddleware is the directory name under my app folder
            – parvez
            Nov 12 at 10:16











          • I meant, did you change the name of the setting from MIDDLEWARE_CLASSES to MIDDLEWARE?
            – Daniel Roseman
            Nov 12 at 10:23










          • It worked, you saved my day, thanks
            – parvez
            Nov 12 at 10:28
















          • edited the question as per latest doc, but still not working can you again have a look please
            – parvez
            Nov 12 at 10:11











          • Did you update the setting name? Does it print any of your debugging messages?
            – Daniel Roseman
            Nov 12 at 10:14










          • No it did n't print anything, my setting name will be 'app_name.middleware.crossdomainxhr.XsSharing'. right? MIddleware is the directory name under my app folder
            – parvez
            Nov 12 at 10:16











          • I meant, did you change the name of the setting from MIDDLEWARE_CLASSES to MIDDLEWARE?
            – Daniel Roseman
            Nov 12 at 10:23










          • It worked, you saved my day, thanks
            – parvez
            Nov 12 at 10:28















          edited the question as per latest doc, but still not working can you again have a look please
          – parvez
          Nov 12 at 10:11





          edited the question as per latest doc, but still not working can you again have a look please
          – parvez
          Nov 12 at 10:11













          Did you update the setting name? Does it print any of your debugging messages?
          – Daniel Roseman
          Nov 12 at 10:14




          Did you update the setting name? Does it print any of your debugging messages?
          – Daniel Roseman
          Nov 12 at 10:14












          No it did n't print anything, my setting name will be 'app_name.middleware.crossdomainxhr.XsSharing'. right? MIddleware is the directory name under my app folder
          – parvez
          Nov 12 at 10:16





          No it did n't print anything, my setting name will be 'app_name.middleware.crossdomainxhr.XsSharing'. right? MIddleware is the directory name under my app folder
          – parvez
          Nov 12 at 10:16













          I meant, did you change the name of the setting from MIDDLEWARE_CLASSES to MIDDLEWARE?
          – Daniel Roseman
          Nov 12 at 10:23




          I meant, did you change the name of the setting from MIDDLEWARE_CLASSES to MIDDLEWARE?
          – Daniel Roseman
          Nov 12 at 10:23












          It worked, you saved my day, thanks
          – parvez
          Nov 12 at 10:28




          It worked, you saved my day, thanks
          – parvez
          Nov 12 at 10:28

















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53259812%2fdjango-middleware-to-handle-crossxhr-requests-is-not-working%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          這個網誌中的熱門文章

          How to read a connectionString WITH PROVIDER in .NET Core?

          In R, how to develop a multiplot heatmap.2 figure showing key labels successfully

          Museum of Modern and Contemporary Art of Trento and Rovereto