讓我們來創建一個登錄 API,該 API 將檢查用戶的帳號和密碼是否正確。這裡我們將使用 Django 的內建身份驗證系統來進行檢查。
首先,我們需要在 views.py 中添加一個新的 View 函數來處理登錄請求。然後,我們將在 urls.py 中設置相應的 urls。
請在 mysite/api/views.py 中添加以下代碼:
from django.contrib.auth import authenticate
from django.contrib.auth.models import User
from django.http import JsonResponse
from rest_framework.decorators import api_view
@api_view(['POST'])
def login_view(request):
account = request.data.get('account')
password = request.data.get('password')
user = authenticate(username=account, password=password)
if user is not None:
return JsonResponse({"message": "Login successful!"}, status=200)
else:
return JsonResponse({"message": "Invalid credentials."}, status=401)
2. 更新 urls.py
接下來,請在 mysite/api/urls.py 中添加新的路由:
from django.urls import path
from .views import hello_world, login_view
urlpatterns = [
path('helloworld/', hello_world, name='hello_world'),
path('login/', login_view, name='login'),
]
現在,可以使用 POST 請求來測試 /api/login/ 端點。請求的 JSON 主體應該包含 account 和 password 參數,例如:
{
"account": "your_username",
"password": "your_password"
}