DJango跨域中间键

Skip to main content

Search PyPISearch

Help Donate Log in Register

django-cors-middleware 1.3.1

pip install django-cors-middleware==1.3.1Copy PIP instructions

Latest version

Last released: Aug 20, 2016

django-cors-middleware is a Django application for handling the server headers required for Cross-Origin Resource Sharing (CORS). Fork of django-cors-headers.

Navigation

Project descriptionRelease historyDownload files

Project links

Homepage

Statistics

GitHub statistics:Stars: 98Forks: 30Open issues/PRs: 11

View statistics for this project via Libraries.io, or by using Google BigQuery

Meta

License: MIT License (MIT License)

Author: Zeste de Savoir

Tags:django, cors, middleware, rest,api

Maintainers

gustavi

Classifiers

Development Status
5 - Production/Stable
Environment
Web Environment
Framework
Django
Intended Audience
Developers
License
OSI Approved :: MIT License
Operating System
OS Independent
Programming Language
Python
Python :: 2
Python :: 2.7
Python :: 3
Python :: 3.3
Python :: 3.4
Python :: 3.5
Topic
Software Development :: Libraries :: Application Frameworks
Software Development :: Libraries :: Python Modules

Project description

 

django-cors-middleware

A Django App that adds CORS (Cross-Origin Resource Sharing) headers to responses.

Although JSON-P is useful, it is strictly limited to GET requests. CORS builds on top of XmlHttpRequest to allow developers to make cross-domain requests, similar to same-domain requests. Read more about it here:http://www.html5rocks.com/en/tutorials/cors/

This is a fork of https://github.com/ottoyiu/django-cors-headers/ because of inactivity.

Supported versions of Python and Django :

  Py 2.7 Py 3.3 Py 3.4 Py 3.5
Django 1.8 YES YES YES YES
Django 1.9 YES   YES YES
Django 1.10 YES   YES YES

Setup

Install by downloading the source and running:

python setup.py install

or

pip install django-cors-middleware

and then add it to your installed apps:

INSTALLED_APPS = (
    ...
    ‘corsheaders‘,
    ...
)

You will also need to add a middleware class to listen in on responses:

# Use `MIDDLEWARE_CLASSES` prior to Django 1.10
MIDDLEWARE = [
    ...
    ‘corsheaders.middleware.CorsMiddleware‘,
    ‘django.middleware.common.CommonMiddleware‘,
    ...
]

Note that CorsMiddleware needs to come before Django’s CommonMiddleware if you are using Django’s USE_ETAGS = True setting, otherwise the CORS headers will be lost from the 304 not-modified responses, causing errors in some browsers.

Signals

If you have a use-case that requires running Python code to check if a site exists, we provide a Django signal that covers this. We have a check_request_enabled signal that provides the request. Here is an example configuration:

from corsheaders import signals
from .models import Site

def handler(sender, request, **kwargs):
    for site in Site.objects.all():
        if request.host in site.domain:
            return True
    return False

signals.check_request_enabled.connect(handler)

If the signal returns True, then the request will have headers added to it.

Configuration

Add hosts that are allowed to do cross-site requests to CORS_ORIGIN_WHITELIST or set CORS_ORIGIN_ALLOW_ALL to True to allow all hosts.

CORS_ORIGIN_ALLOW_ALL

If True, the whitelist will not be used and all origins will be accepted

Default:

CORS_ORIGIN_ALLOW_ALL = False

CORS_ORIGIN_WHITELIST

Specify a list of origin hostnames that are authorized to make a cross-site HTTP request

Example:

CORS_ORIGIN_WHITELIST = (
    ‘google.com‘,
    ‘hostname.example.com‘
)

Default:

CORS_ORIGIN_WHITELIST = ()

CORS_ORIGIN_REGEX_WHITELIST

Specify a regex list of origin hostnames that are authorized to make a cross-site HTTP request; Useful when you have a large amount of subdomains for instance.

Example:

CORS_ORIGIN_REGEX_WHITELIST = (‘^(https?://)?(\w+\.)?google\.com$‘, )

Default:

CORS_ORIGIN_REGEX_WHITELIST = ()


You may optionally specify these options in settings.py to override the defaults. Defaults are shown below:

CORS_URLS_REGEX

Specify a URL regex for which to enable the sending of CORS headers; Useful when you only want to enable CORS for specific URLs, e. g. for a REST API under /api/.

Example:

CORS_URLS_REGEX = r‘^/api/.*$‘

Default:

CORS_URLS_REGEX = ‘^.*$‘

CORS_ALLOW_METHODS

Specify the allowed HTTP methods that can be used when making the actual request

Default:

CORS_ALLOW_METHODS = (
    ‘GET‘,
    ‘POST‘,
    ‘PUT‘,
    ‘PATCH‘,
    ‘DELETE‘,
    ‘OPTIONS‘
)

CORS_ALLOW_HEADERS

Specify which non-standard HTTP headers can be used when making the actual request

Default:

CORS_ALLOW_HEADERS = (
    ‘x-requested-with‘,
    ‘content-type‘,
    ‘accept‘,
    ‘origin‘,
    ‘authorization‘,
    ‘x-csrftoken‘
)

CORS_EXPOSE_HEADERS

Specify which HTTP headers are to be exposed to the browser

Default:

CORS_EXPOSE_HEADERS = ()

CORS_PREFLIGHT_MAX_AGE

Specify the number of seconds a client/browser can cache the preflight response

Note: A preflight request is an extra request that is made when making a “not-so-simple” request (eg. content-type is not application/x-www-form-urlencoded) to determine what requests the server actually accepts. Read more about it here: http://www.html5rocks.com/en/tutorials/cors/

Default:

CORS_PREFLIGHT_MAX_AGE = 86400

CORS_ALLOW_CREDENTIALS

Specify whether or not cookies are allowed to be included in cross-site HTTP requests (CORS).

Default:

CORS_ALLOW_CREDENTIALS = False

CORS_REPLACE_HTTPS_REFERER

Specify whether to replace the HTTP_REFERER header if CORS checks pass so that CSRF django middleware checks will work with https

Note: With this feature enabled, you also need to add the corsheaders.middleware.CorsPostCsrfMiddleware after django.middleware.csrf.CsrfViewMiddleware to undo the header replacement

Default:

CORS_REPLACE_HTTPS_REFERER = False

CORS_URLS_ALLOW_ALL_REGEX

Specify a list of URL regex for which to allow all origins

Example:

CORS_URLS_ALLOW_ALL_REGEX = (r‘^/api/users$‘, )

Default:

CORS_URLS_ALLOW_ALL_REGEX = ()


Developed and maintained by the Python community, for the Python community. 
Donate today!

? 2018 Python Software Foundation

ElasticSearch PingdomMonitoring GoogleBigQuery SentryError logging CloudAMQPRabbitMQ AWSCloud computing DataDogMonitoring FastlyCDN DigiCertEV certificate StatusPageStatus page

原文地址:https://www.cnblogs.com/leigepython/p/9341206.html

时间: 2024-07-30 20:14:19

DJango跨域中间键的相关文章

python Django 跨域解决方案

django解决跨域请求的问题 解决方案 1.安装django-cors-headers pip install django-cors-headers 内容详见:https://github.com/ottoyiu/django-cors-headers 其他解决方 1.使用JSONP 使用Ajax获取json数据时,使用JSONP,JSONP只能用于GET请求,红色部分是注意事项 $.ajax({ url:'http://localhost:8000/hello/', data:data,

用CORS 解决vue.js django跨域调用

Cross-Origin Resource Sharing(CORS)跨域资源共享是一份浏览器技术的规范,提供了 Web 服务从不同域传来沙盒脚本的方法,以避开浏览器的同源策略,是 JSONP 模式的现代版.与 JSONP 不同,CORS 除了 GET 要求方法以外也支持其他的 HTTP 要求.用 CORS 可以让网页设计师用一般的 XMLHttpRequest,这种方式的错误处理比 JSONP 要来的好.另一方面,JSONP 可以在不支持 CORS 的老旧浏览器上运作.现代的浏览器都支持 CO

Django 跨域请求处理

参考https://blog.csdn.net/qq_27068845/article/details/73007155 http://blog.51cto.com/aaronsa/2071108 django处理Ajax跨域访问 使用javascript进行ajax访问的时候,出现如下错误 出错原因:javascript处于安全考虑,不允许跨域访问.下图是对跨域访问的解释: 概念: 这里说的js跨域是指通过js或python在不同的域之间进行数据传输或通信,比如用ajax向一个不同的域请求数据

Django跨域请求CSRF的方法示例

web跨域请求 1.为什么要有跨域限制 举个例子: 1.用户登录了自己的银行页面 http://mybank.com,http://mybank.com向用户的cookie中添加用户标识. 2.用户浏览了恶意页面 http://evil.com.执行了页面中的恶意AJAX请求代码. 3.http://evil.com向http://mybank.com发起AJAX HTTP请求,请求会默认把http://mybank.com对应cookie也同时发送过去. 4.银行页面从发送的cookie中提取

django 跨域

什么是跨域 跨域是指一个域下的文档或脚本试图去请求另一个域下的资源,这里跨域是广义的.其实我们通常所说的跨域是狭义的,是由浏览器同源策略限制的一类请求场景. 什么是同源策略? 同源策略/SOP(Same origin policy)是一种约定,由Netscape公司1995年引入浏览器,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,浏览器很容易受到XSS.CSFR等***.所谓同源是指"协议+域名+端口"三者相同,即便两个不同的域名指向同一个ip地址,也非同源. 同源策略限制

Vue+Django 跨域问题配置

跨域请求问题: 1.Django后端解决办法: # 后端下载模块: pip install django-cors-headers # settings配置: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', # 'dj

Django 跨域请求 解决 axios 未完待续

import django import os # os.environ.setdefault("DJANGO_SETTINGS_MODULE", "untitled5.settings") # project_name 项目名称 # django.setup() from django.utils.deprecation import MiddlewareMixin import importlib project_settings = os.environ['D

Django解决跨域

Django跨域问题 什么是跨域 ''' 通常情况下,A网页访问B服务器资源时,不满足以下三个条件其一就是跨域访问 1. 协议不同 2. 端口不同 3. 主机不同 ''' Django解决跨域 ''' 安装django-cors-headers模块 在settings.py中配置 # 注册app INSTALLED_APPS = [ ... 'corsheaders' ] # 添加中间件 MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddlew

Django 【第十九篇】JS实现的ajax、同源策略和前端jsonp解决跨域问题

一.回顾jQuery实现的ajax 首先说一下ajax的优缺点 优点: AJAX使用Javascript技术向服务器发送异步请求: AJAX无须刷新整个页面: 因为服务器响应内容不再是整个页面,而是页面中的局部,所以AJAX性能高: jquery 实现的ajax index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <t