1、中间件代码
[[email protected] mysite]# tree middlewares middlewares ├── base.py ├── base.pyc ├── cors.py ├── cors.pyc ├── __init__.py └── __init__.pyc 0 directories, 6 files [[email protected]-node01 mysite]#
2. 代码
middlewares/base.py
[[email protected] mysite]# cat middlewares/base.py #!/bin/env python # -*- coding: utf-8 -*- class MiddlewareMixin(object): def __init__(self, get_response=None): self.get_response = get_response super(MiddlewareMixin, self).__init__() def __call__(self, request): response = None if hasattr(self, ‘process_request‘): response = self.process_request(request) if not response: response = self.get_response(request) if hasattr(self, ‘process_response‘): response = self.process_response(request, response) return response [[email protected]-node01 mysite]#
核心文件middlewares/cors.py
[[email protected] mysite]# cat middlewares/cors.py #!/bin/env python # -*- coding: utf-8 -*- from .base import MiddlewareMixin class CORSMiddleware(MiddlewareMixin): """CORS中间件""" def process_response(self, request, response): if request.method == "OPTIONS": response[‘Access-Control-Allow-Origin‘] = ‘*‘ response[‘Access-Control-Allow-Headers‘] = ‘*‘ response[‘Access-Control-Allow-Methods‘] = ‘*‘ else: response[‘Access-Control-Allow-Origin‘] = ‘*‘ return response [[email protected]-node01 mysite]#
3. settings.py文件配置
MIDDLEWARE = [ ‘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‘, ‘mysite.middlewares.cors.CORSMiddleware‘ ]
原文地址:https://www.cnblogs.com/supery007/p/9093171.html
时间: 2024-10-13 03:10:00