import json from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from django.contrib.auth.models import User from django.contrib.auth import authenticate, login
# 注册功能 @csrf_exempt defregister(request): if request.method == 'POST': data = json.loads(request.body) username = data.get('username') password = data.get('password')
# 验证用户名长度 iflen(username) < 4: return JsonResponse({'status': 'error', 'message': 'Username must be at least 4 characters'}, status=400)
# 验证密码长度和格式 iflen(password) < 6ornotany(char.isdigit() for char in password) ornotany(char.isalpha() for char in password): return JsonResponse({'status': 'error', 'message': 'Password must be at least 6 characters and contain at least one digit and one letter'}, status=400)
user = User.objects.create_user(username, password=password) return JsonResponse({'status': 'success'}, status=201)
# 登录 @csrf_exempt deflogin_view(request): if request.method == 'POST': data = json.loads(request.body) username = data.get('username') password = data.get('password') user = authenticate(request, username=username, password=password) if user isnotNone: login(request, user) return JsonResponse({'status': 'success', 'token': request.session.session_key}, status=200) else: return JsonResponse({'status': 'error', 'message': 'Invalid credentials'}, status=401) else: return JsonResponse({'status': 'error', 'message': 'Invalid request method'}, status=400)
2、在urls.py文件中配置路由
1 2 3 4 5 6 7 8 9
from django.contrib import admin from django.urls import path from . import views