【Python】django-cors-headers

什么是CORS ?

CORS(跨域资源共享,Cross-Origin Resource Sharing)是一种跨域访问的机制,可让Ajax实现跨域访问。

其实,在服务器的response header中,加入“Access-Control-Allow-Origin: *”便可支持CORS,很是的简单,apache/nginx等怎么配置,见参考文档。

django-cors-headers 的作用 ?

将跨源资源共享 (CORS) 标头添加到响应的 Django 应用程序。这允许从其他来源向您的 Django

应用程序发出浏览器内请求。

1. 安装django-cors-headers

pip install django-cors-headers

2. 添加到应用程序中

INSTALLED_APPS  =  [ 
    ... , 
    "corsheaders" , 
    ... , 
]

3. 在中间键中监听响应

CorsMiddleware 需要放在第一位,不放在第一位,可能会造成某些请求没有添加CORS。

MIDDLEWARE  =  [ 
    "corsheaders.middleware.CorsMiddleware" , 
    ... , 
]

4. 设置访问白名单

# CORS_ORIGIN_ALLOW_ALL为True, 指定所有域名(ip)都可以访问后端接口, 默认为False
CORS_ORIGIN_ALLOW_ALL = True

5. 设置允许携带cookie

CORS_ALLOW_CREDENTIALS = True

6. 默认请求头列表。

CORS_ALLOW_HEADERS  =  [ 
    "accept" , 
    "accept-encoding" , 
    "authorization" , 
    "content-type" , 
    "dnt" , 
    "origin" , 
    "user-agent" , 
    "x-csrftoken" , 
    "x-requested-with" , 
]

Python 中,"strict-origin-when-cross-origin" (简称 SOP) 不是一个直接的 Python 概念,它通常是指同源策略(Same-Origin Policy)的一个扩展概念,这个策略是 web 浏览器用来限制不同源之间数据交互的安全策略。在 JavaScript 中,SOP 原则确保了只有从同一个源(协议、域名和端口)发起的请求才能访问其他资源,如 cookies 和 API。 在讨论 Python 的上下文中,它可能是指 Flask 或 Django 等 Web 框架中用于处理跨域资源共享(Cross-Origin Resource Sharing, CORS)的配置选项。当你使用这些框架时,`strict-origin-when-cross-origin` 是一种 CORS 配置策略,它表示只有来自源站(`Access-Control-Allow-Origin`)的跨域请求才会应用更严格的策略,即只允许那些与原始请求来源相同的 origin。 具体设置例子: ```python from flask import Flask, jsonify, make_response app = Flask(__name__) app.config['CORS_HEADERS'] = 'Content-Type' app.config['CORS_ORIGINS'] = ['http://example.com', 'https://subdomain.example.com'] @app.after_request def after_request(response): if response.status_code == 200 and request.method == 'OPTIONS': response = make_response(jsonify({'allow_credentials': True, 'access_control_allow_credentials': True, 'access_control_allow_headers': '*', 'access_control_allow_methods': '*', 'access_control_allow_origin': '*'}), 204) response.headers['Access-Control-Max-Age'] = '1728000' # 20 days return response # 使用时确保在需要设置 CORS 的路由上应用此策略 @app.route('/api/data') @cross_origin(origins=['*'], allow_headers='*', strict_origin_when_cross_domain=True) def my_api(): # ... ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值