Home >Backend Development >Python Tutorial >Sample code for Django cross-domain request handling

Sample code for Django cross-domain request handling

不言
不言Original
2018-05-02 14:18:561411browse

This article mainly introduces the sample code about Django cross-domain request processing, which has certain reference value. Now I share it with you. Friends in need can refer to it

django handles Ajax cross-domain requests Domain access

When using javascript for ajax access, the following error occurs

Cause of error: JavaScript is for security reasons and cross-domain access is not allowed . The following figure is an explanation of cross-domain access:

Concept:

The js cross-domain mentioned here refers to the js or Python performs data transmission or communication between different domains, such as using ajax to request data from a different domain, or using js to obtain data in the framework (Django) of different domains in the page. As long as the protocol, domain name, or port are any different, they are regarded as different domains.

Solution

1. Modify the views.py file

Modify the corresponding API implementation function in views.py, Allow other domains to request data through Ajax:

todo_list = [
  {"id": "1", "content": "吃饭"},
  {"id": "2", "content": "吃饭"},
]


class Query(View):
  @staticmethod
  def get(request):
    response = JsonResponse(todo_list, safe=False)
    response["Access-Control-Allow-Origin"] = "*"
    response["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS"
    response["Access-Control-Max-Age"] = "1000"
    response["Access-Control-Allow-Headers"] = "*"
    return response

  @staticmethod
  def post(request):
    print(request.POST)
    return HttpResponse()

2. Add middleware django-cors-headers

GitHub address: https:// github.com/ottoyiu/django-cors-headers

2.1. Install pip install django-cors-headers

2. 2 Add app

INSTALLED_APPS = (
  ...
  'corsheaders',
  ...
)

2.3 Add middleware

MIDDLEWARE = [ # Or MIDDLEWARE_CLASSES on Django < 1.10
  ...
  &#39;corsheaders.middleware.CorsMiddleware&#39;,
  &#39;django.middleware.common.CommonMiddleware&#39;,
  ...
]

2.4 Configure the address that allows cross-site access to this site

CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = (
   &#39;localhost:63343&#39;,
)

# 默认值是全部:
CORS_ORIGIN_WHITELIST = () # 或者定义允许的匹配路径正则表达式.
CORS_ORIGIN_REGEX_WHITELIST = (&#39;^(https?://)?(\w+.)?>google.com$&#39;, )  # 默认值:
CORS_ORIGIN_REGEX_WHITELIST = ()

2.5 Set the allowed access method

CORS_ALLOW_METHODS = (
&#39;GET&#39;,
&#39;POST&#39;,
&#39;PUT&#39;,
&#39;PATCH&#39;,
&#39;DELETE&#39;,
&#39;OPTIONS&#39;
)

2.6 Set the allowed header:

Default value:

CORS_ALLOW_HEADERS = (
&#39;x-requested-with&#39;,
&#39;content-type&#39;,
&#39;accept&#39;,
&#39;origin&#39;,
&#39;authorization&#39;,
&#39;x-csrftoken&#39;
)

Related recommendations:

Django examples of using logging to print logs

Django Project Practical User Avatar Uploading and Access

The above is the detailed content of Sample code for Django cross-domain request handling. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn