django Auth用户登录
from apps.子应用名.models import UserDetails, User
from django.contrib import auth
from django.db import transaction
from django.shortcuts import HttpResponse
from django.http import HttpRequest, JsonResponse
from django.views.decorators.http import require_http_methods
import json
@require_http_methods(['POST'])
def sign_in(request: HttpRequest, *args, **kwargs):
body = json.loads(request.body)
if 'email' in body and 'password' in body:
existing = auth.authenticate(
email=body['email'], # 这里
password=body['password']
)
if existing is not None:
auth.login(request, existing) # 写session和cookies,一定要是authenticate的返回值当参数
response = JsonResponse({
'email': existing.email, 'name': existing.username
})
else:
response = HttpResponse('请先注册。', status=202)
else:
response = HttpResponse("缺少参数。", status=400)
return response
上面代码中的参数不是username是因为之前对djangoAuth的用户实体进行了自定义。
import requests
import json
res = requests.post(
url='http://localhost:8000/signIn/', # urls里映射成/signIn了
data=json.dumps({
'email': '[email protected]',
'password': 'password'
})
)
print(res.status_code, res.text, res.cookies)
输出:
200 {"email": "[email protected]", "name": "hello_ world"} <RequestsCookieJar[<Cookie index=dhtsjajgqg064n26hfbd1sey6tifh594 for localhost.local/>]>