I made CORS custom middleware with Django

This article is the 24th day article of Iwate University Advent Calendar 2020.

Introduction

There was a time when I created an API using Django for personal development. At that time, I encountered a CORS problem in the implementation of the API and had to deal with CORS.

Django has something called django-cors-headers. However, I tried to implement it using django-cors-headers, but I couldn't specify Access-Control-Allow-Origin well, and I was able to send requests from other sites as well. It was. So, I've created Django middleware and made it compatible with CORS.

I'm new to Django, so if you have any mistakes, please let me know and I'll study.

Implementation

The implementation looks like this:

custom_middlewares/custom_cors_middleware.py


from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin


class CustomCorsMiddleware(MiddlewareMixin):
    def process_request(self, request):
        if request.method == 'OPTIONS':
            response = HttpResponse()
            response['Access-Control-Allow-Origin'] = 'http://localhost:3000' #Client origin
            response['Access-Control-Allow-Headers'] = ', '.join([ #Add Header to allow
                'Content-Type',
            ])
            response['Access-Control-Allow-Methods'] = ', '.join([ #Added request method to allow
                'DELETE',
                'GET',
                'OPTIONS',
                'PATCH',
                'POST',
                'PUT',
            ])
            return response
        else:
            return None

    def process_response(self, request, response):
        response['Access-Control-Allow-Origin'] = 'http://localhost:3000' #Origin that can read the response
        response['Content-Type'] = 'application/json' #Response type
        return response

The process_request method is executed when a request comes in, and if None is the return value, the routed view is executed.

request
↓
process_request is executed → If there is a return value, that return value is returned
↓
If the return value is None, it corresponds to request routing`view`Is executed

In the above code, in preparation for the preflight request, in the case of the OPTIONS method, the response with the allowed origin header request method attached to the header is returned.

Then the process_response method is executed at the end of the response.

run view
↓
process_request receives the response returned from view and processes the response
↓
response

In the above code, I often see it in CORS

Access to XMLHttpRequest at 'http://locahost:8000' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Specifies the origin from which the response can be read for, and also specifies application/json as the response type.

All you have to do is add this custom middleware to settings.py and you're done.

your_application_name/settings.py


MIDDLEWARE = [
    'custom_middlewares.custom_cors_middleware.CustomCorsMiddleware', #add to
    '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',
]

in conclusion

When I touched Django, I thought that there were few Japanese documents. If you can read English documents like Japanese, you may have less trouble.

Recommended Posts

I made CORS custom middleware with Django
I made a WEB application with Django
I made blackjack with python!
I made COVID19_simulator with JupyterLab
I made Word2Vec with Pytorch
I made blackjack with Python.
I made wordcloud with Python.
I made a fortune with Python.
Twitter posting application made with Django
I made a daemon with Python
I made a development environment for Django 3.0 with Docker, Docker-compose, Poetry
Your own Twitter client made with Django
A simple RSS reader made with Django
I made a Hex map with Python
I made a life game with Numpy
I made a stamp generator with GAN
I made a roguelike game with Python
I made a simple blackjack with Python
I made a configuration file with Python
I made a neuron simulator with Python
[Django] I made a field to enter the date with 4 digit numbers
I made a stamp substitute bot with line
Until you CI what you made with Django with Jenkins
I made a competitive programming glossary with Python
I made a weather forecast bot-like with Python.
I made a GUI application with Python + PyQt5
I made my dog "Monaka Bot" with LineBot
Internationalization with django
I made a Twitter fujoshi blocker with Python ①
[Python] I made a Youtube Downloader with Tkinter.
I made a simple Bitcoin wallet with pycoin
I made a LINE Bot with Serverless Framework!
I made a random number graph with Numpy
I tried Django
I made a bin picking game with Python
I made a Mattermost bot with Python (+ Flask)
I made a QR code image with CuteR
I made my own Django Middleware so that I can access request information from anywhere
[AWS] I made a reminder BOT with LINE WORKS
I made a Twitter BOT with GAE (python) (with a reference)
I tried to create a table only with Django
I made a household account book bot with LINE Bot
I made a ready-to-use syslog server with Play with Docker
I made a Christmas tree lighting game with Python
I made a vim learning game "PacVim" with Go
I made a window for Log output with Tkinter
I made a net news notification app with Python
I made a Python3 environment on Ubuntu with direnv.
I made a LINE BOT with Python and Heroku
Web application made with Python3.4 + Django (Part.1 Environment construction)
Deploy a Django app made with PTVS on Azure
I made a falling block game with Sense HAT
I made it with processing, "Sakanaction's live Othello guy".
Authenticate Google with Django
Django 1.11 started with Python3.6
Upload files with Django
Development digest with Django
Django Middleware Execution Order
Output PDF with Django
〇✕ I made a game
Container-like # 1 made with C