Python 如何在 Django REST Framework 上启用 CORS

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35760943/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 16:55:56  来源:igfitidea点击:

How can I enable CORS on Django REST Framework

pythondjangocorsdjango-rest-frameworkmiddleware

提问by Julio Marins

How can I enable CORS on my Django REST Framework? the referencedoesn't help much, it says that I can do by a middleware, but how can I do that?

如何在我的 Django REST Framework 上启用 CORS?该参考没有太大的帮助,它说,我可以通过一个中间件做,但我怎么能做到这一点?

回答by Chris

The link you referenced in your question recommends using django-cors-headers, whose documentationsays to install the library

您在问题中引用的链接建议使用django-cors-headers,其文档说要安装库

pip install django-cors-headers

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:

您还需要添加一个中间件类来监听响应:

MIDDLEWARE_CLASSES = (
    ...
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    ...
)

You might also want to browse the configuration sectionof its documentation, paying particular attention to the various CORS_ORIGIN_settings.

您可能还想浏览其文档的配置部分,特别注意各种CORS_ORIGIN_设置。

回答by likaiguo.happy

pip install django-cors-headers

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:

您还需要添加一个中间件类来监听响应:

MIDDLEWARE_CLASSES = (
    ...
    'corsheaders.middleware.CorsMiddleware',  
    'django.middleware.common.CommonMiddleware',  
    ...
)

CORS_ORIGIN_ALLOW_ALL = True # If this is used then `CORS_ORIGIN_WHITELIST` will not have any effect
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = [
    'http://localhost:3030',
] # If this is used, then not need to use `CORS_ORIGIN_ALLOW_ALL = True`
CORS_ORIGIN_REGEX_WHITELIST = [
    'http://localhost:3030',
]

more details: https://github.com/ottoyiu/django-cors-headers/#configuration

更多详情:https: //github.com/ottoyiu/django-cors-headers/#configuration

read the official documentation can resolve almost all problem

阅读官方文档几乎可以解决所有问题

回答by Julio Marins

You can do by using a custom middleware, even though knowing that the best option is using the tested approach of the package django-cors-headers. With that said, here is the solution:

您可以使用自定义中间件来完成,即使知道最好的选择是使用经过测试的包方法django-cors-headers。话虽如此,这是解决方案:

create the following structure and files:

创建以下结构和文件:

-- myapp/middleware/__init__.py

—— myapp/middleware/__init__.py

from corsMiddleware import corsMiddleware

-- myapp/middleware/corsMiddleware.py

—— myapp/middleware/corsMiddleware.py

class corsMiddleware(object):
    def process_response(self, req, resp):
        resp["Access-Control-Allow-Origin"] = "*"
        return resp

add to settings.pythe marked line:

添加到settings.py标记行:

MIDDLEWARE_CLASSES = (
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",

    # Now we add here our custom middleware
     'app_name.middleware.corsMiddleware' <---- this line
)

回答by masnun

In case anyone is getting back to this question and deciding to write their own middleware, this is a code sample for Django's new style middleware -

如果有人回到这个问题并决定编写自己的中间件,这是 Django 新型中间件的代码示例 -

class CORSMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        response["Access-Control-Allow-Origin"] = "*"

        return response

回答by Dhruv Batheja

For Django versions > 1.10, according to the documentation, a custom MIDDLEWARE can be written as a function, let's say in the file: yourproject/middleware.py(as a sibling of settings.py):

对于 Django 版本 > 1.10,根据文档,可以将自定义 MIDDLEWARE 编写为函数,让我们在文件中说:(yourproject/middleware.py作为 的兄弟settings.py):

def open_access_middleware(get_response):
    def middleware(request):
        response = get_response(request)
        response["Access-Control-Allow-Origin"] = "*"
        response["Access-Control-Allow-Headers"] = "*"
        return response
    return middleware

and finally, add the python path of this function (w.r.t. the root of your project) to the MIDDLEWARE list in your project's settings.py:

最后,将此函数的 python 路径(写入项目的根目录)添加到项目的 MIDDLEWARE 列表中settings.py

MIDDLEWARE = [
  .
  .
  'django.middleware.clickHymaning.XFrameOptionsMiddleware',
  'yourproject.middleware.open_access_middleware'
]

Easy peasy!

十分简单!

回答by jnowak

Well, I don't know guys but:

好吧,我不认识伙计们,但是:

using here python 3.6 and django 2.2

在这里使用 python 3.6 和 django 2.2

Renaming MIDDLEWARE_CLASSES to MIDDLEWARE in settings.py worked.

在 settings.py 中将 MIDDLEWARE_CLASSES 重命名为 MIDDLEWARE 工作。

回答by user3785966

Below are the working steps without the need for any external modules:

以下是不需要任何外部模块的工作步骤:

Step 1:Create a module in your app.

第 1 步:在您的应用中创建一个模块。

E.g, lets assume we have an app called user_registration_app. Explore user_registration_app and create a new file.

例如,假设我们有一个名为user_registration_app的应用程序。探索 user_registration_app 并创建一个新文件。

Lets call this as custom_cors_middleware.py

让我们称之为custom_cors_middleware.py

Paste the below Class definition:

粘贴以下类定义:

class CustomCorsMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        # One-time configuration and initialization.

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.

        response = self.get_response(request)
        response["Access-Control-Allow-Origin"] = "*"
        response["Access-Control-Allow-Headers"] = "*"

        # Code to be executed for each request/response after
        # the view is called.

        return response

Step 2:Register a middleware

第二步:注册一个中间件

In your projects settings.py file, add this line

在您的项目 settings.py 文件中,添加这一行

'user_registration_app.custom_cors_middleware.CustomCorsMiddleware'

'user_registration_app.custom_cors_middleware.CustomCorsMiddleware'

E.g:

例如:

  MIDDLEWARE = [
        'user_registration_app.custom_cors_middleware.CustomCorsMiddleware', # ADD THIS LINE BEFORE CommonMiddleware
         ...
        'django.middleware.common.CommonMiddleware',

    ]

Remember to replace user_registration_appwith the name of your app where you have created your custom_cors_middleware.py module.

请记住将user_registration_app替换为您在其中创建 custom_cors_middleware.py 模块的应用程序的名称。

You can now verify it will add the required response headers to all the views in the project!

您现在可以验证它会将所需的响应标头添加到项目中的所有视图!

回答by C.K.

Django=2.2.12 django-cors-headers=3.2.1 djangorestframework=3.11.0

django=2.2.12 django-cors-headers=3.2.1 djangorestframework=3.11.0

Follow the official instruction doesn't work

按照官方说明不行

Finally use the old way to figure it out.

最后用老方法算出来。

ADD:

添加:

# proj/middlewares.py
from rest_framework.authentication import SessionAuthentication


class CsrfExemptSessionAuthentication(SessionAuthentication):

    def enforce_csrf(self, request):
        return  # To not perform the csrf check previously happening

#proj/settings.py

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'proj.middlewares.CsrfExemptSessionAuthentication',
    ),
}

回答by Md. Tanvir Raihan

Use django-cors-headerslibrary to achieve this.

使用django-cors-headers库来实现这一点。

pip install django-cors-headers

pip install django-cors-headers

then in settings.py, add this to your installed apps list,

然后在settings.py 中,将其添加到已安装的应用程序列表中,

INSTALLED_APPS = [
     .....
     .....
     'corsheaders',
]

and then add this to the top of theMiddleware,

然后将其添加 中间件的顶部

MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'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.clickHymaning.XFrameOptionsMiddleware',
]

and then

进而

CORS_ORIGIN_ALLOW_ALL = True

CORS_ORIGIN_ALLOW_ALL = True

if you want to specify then use this instead of CORS_ORIGIN_ALLOW_ALL = True

如果要指定,请使用它而不是 CORS_ORIGIN_ALLOW_ALL = True

CORS_ORIGIN_WHITELIST = [ 'http://127.0.0.1:8000', ]

CORS_ORIGIN_WHITELIST = [ 'http://127.0.0.1:8000', ]

and also add,

并补充说,

CORS_ORIGIN_REGEX_WHITELIST = [ "r"^https://\w+\.ecommerce.herokuapp\.com$", ]

CORS_ORIGIN_REGEX_WHITELIST = [ "r"^https://\w+\.ecommerce.herokuapp\.com$", ]

回答by Rémi Héneault

After installing django-cors-headersand adding it to your middlewares, you may also need to migrate in order for the CorsModelmodel to be created in your DB. I was getting exceptions while trying to flush it otherwise.

安装django-cors-headers并将其添加到您的中间件后,您可能还需要进行迁移,以便在您的数据库中创建CorsModel模型。我在尝试以其他方式刷新时遇到异常。

python3 manage.py makemigrations corsheaders
python3 manage.py migrate