iT邦幫忙

2024 iThome 鐵人賽

DAY 25
0

讓我們來創建一個登錄 API,該 API 將檢查用戶的帳號和密碼是否正確。這裡我們將使用 Django 的內建身份驗證系統來進行檢查。

首先,我們需要在 views.py 中添加一個新的 View 函數來處理登錄請求。然後,我們將在 urls.py 中設置相應的 urls。

1. 更新 views.py

請在 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"
}

https://ithelp.ithome.com.tw/upload/images/20241007/20140622mVvScmzT6M.png


上一篇
D24 - 加上客制化的 api 端點
下一篇
D26 - JWT token 簡介,因為接下來會用到
系列文
使用 Django 框架和 Wagtail,快速打造一個 CMS 網站30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言