我尝试了覆盖渲染到响应的方法,但我想要一个解决方案,我可以将整个 URL 块映射到多个视图,而不必处理在多个视图上覆盖相同的方法。
我制作了一个基于django-cors-headers的中间件类,因此我可以允许对我的 django 应用程序的一部分进行 iframe 处理。我在我的主项目目录中保留了一个 middleware.py 并保存了我在那里创建的几个随机中间件类,例如这里的这个和一个ForceResponse Exception。
import re
from django import http
from django.conf import settings
class XFrameAllowMiddleware(object):
def process_request(self, request):
"""
If CORS preflight header, then create an
empty body response (200 OK) and return it
Django won't bother calling any other request
view/exception middleware along with the requested view;
it will call any response middlewares
"""
if (self.is_enabled(request) and
request.method == 'OPTIONS' and
"HTTP_ACCESS_CONTROL_REQUEST_METHOD" in request.META):
response = http.HttpResponse()
return response
return None
def process_response(self, request, response):
if self.is_enabled(request):
response['X-Frame-Options'] = 'ALLOWALL'
return response
def is_enabled(self, request):
return re.match(settings.XFRAME_URLS_REGEX, request.path)
将其添加到您的 MIDDLEWARE_CLASSES 并在您的设置中配置正则表达式:
MIDDLEWARE_CLASSES = (
...
'your_django_app.middleware.XFrameAllowMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...
)
XFRAME_URLS_REGEX = r'^/iframe_this_url/.*$'
来自 django-cors-headers read.me:
CORS_URLS_REGEX:指定启用 CORS 标头发送的 URL 正则表达式;当您只想为特定 URL 启用 CORS 时很有用,例如 /api/ 下的 REST API。例子:
CORS_URLS_REGEX = r'^/api/.*$'
默认:
CORS_URLS_REGEX = '^.*$'