Django quickly implements the login interface

Resource address:

https://download.csdn.net/download/qq_39208536/87642079

1. Create a Django project

https://blog.csdn.net/qq_39208536/article/details/129892480?csdn_share_tail=%7B%22type%22%3A%22blog%22%2C%22rType%22%3A%22article%22%2C%22rId%22%3A%22129892480%22%2C%22source%22%3A%22qq_39208536%22%7D

2. Write the login interface 

2.1 Write routing urls.py

from django.contrib import admin
from django.urls import path

from sign import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('login/', views.login),

]

2.2 Login method

views.py

# 导入相关的包
from django.core.cache import cache
from django.http import JsonResponse
TIME_OUT = 30 * 60  # 30min

def login(request):
    username = request.POST.get("username")
    password = request.POST.get("pwd")
    token = "1234567890"
    # 存储到缓存中(这个暂时没用,可以注释掉)
    cache.set(username, token, TIME_OUT)
    # 响应结果
    obj = JsonResponse({'code': 200, 'msg': '操作成功', 'token':token})

    # 将token写到浏览器cookie里
    # obj.set_cookie('token',token)
    return obj

Return the login success message and write the token into the browser cookie.

Note: token information can be put in cookie or session.

The operation of putting token information in cookies or sessions should be done by the front end, not the back end.

3. Cross-domain problem handling

We need to deal with cross-domain issues.

Django cross-domain issue error:

https://blog.csdn.net/qq_39208536/article/details/129906624?csdn_share_tail=%7B%22type%22%3A%22blog%22%2C%22rType%22%3A%22article%22%2C%22rId%22%3A%22129906624%22%2C%22source%22%3A%22qq_39208536%22%7D

Django cross-domain problem handling method:

Django notes - solve django cross-domain requests_django closes cross-domain_simpleyako's blog-CSDN blog

In the front-end and back-end separation mode, the front-end and the back-end are different ports, which involves the problem of cross-domain access to data, because the same-origin policy of the browser does not support mutual access to data between two different domain names by default, and We need to transfer data between two domain names, then we need to add support for cross-domain access to the backend.

1. Solve the backend support for cross-domain access through django-cors-headers extension.

 pip install django-cors-headers  -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com

2. Middle layer settings:

settings.py

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

3. Add whitelist

CORS_ORIGIN_WHITELIST = (
        'http://127.0.0.1:8080',
        'http://localhost:8080',
         'https://localhost:8080',
    )
CORS_ALLOW_CREDENTIALS = True  # 允许携带cookie

4. Turn off the cross-domain request forgery protection of Django's default configuration

Guess you like

Origin blog.csdn.net/qq_39208536/article/details/129892740