基於django框架開發登錄接口的四個方法


文件路徑user/login

一、登錄接口;get請求  username password url參數傳遞

二、登錄接口:post請求,username password url-encode表單傳遞

意思實現的功能是 :

①、實現一:用戶名和密碼都是admin 顯示 home.html  提示歡迎登錄 即用戶名和密碼正確頁面返回到home.html頁面

②、實現二:用戶面和密碼錯誤或者不寫 顯示error.html 提示參數錯誤 即用戶名或密碼錯誤 活着不填頁面返回到error.html頁面

前端頁碼 templates添加home.html頁面
<html lang="en">
<head>
<meta charset="UTF-8">
<title>測試平台</title>
</head>
<body>
<h3>歡迎登錄測試平台 ,{{ username}}</h3>
<a href="/userapi/logout/">注銷</a>>
</body>
</html>

代碼實現:

@api_view(["GET","POST"])
def login(request):
if request.method =="GET":
username = request.GET.get("username")
pwd = request.GET.get("password")
elif request.method == "POST":
username = request.POST.get("username")
pwd = request.POST.get("password")
else:
return render(request,template_name="error.html",context={"msg":"請求方法錯誤"})
if username is not None and pwd is not None:
if username =='admin'and pwd == "admin":
return render(request,"home.html",context={"username":username})
else:
return render(request, "error.html", context={"msg": "用戶名和密碼錯誤"})

else:
return render(request,"error.html",context={"msg":"用戶名和密碼必填"})
第二個實現:前端有完整的登錄頁面:前端有個登錄頁面即輸入登錄和密碼的輸入框 后端有個登錄接口 user/login有用戶名和密碼前端的 后端user/api/login后端真正的登錄接口
路由修改: user/urls文件
urlpatterns = [
path('hello/', views.hello),
path('login/',views.login),#只有一個后端登錄接口
path('home/',views.home),
path('api/login/',views.api_login),#前后端都有的登錄接口
path('api/logout/',views.api_logout)
]
后端接口層:views.py
def login(request):#前端請求路徑127.0.0.1:8000/user/login
return render(request,'login.html')
@api_view(["POST"])#有頁面返回了所以去掉get
def api_login(request):
username = request.POST.get("username")
pwd = request.POST.get("password")
is_login =request.POST.get('is_login')
if username is not None and pwd is not None:
      if username =='admin'and pwd == "admin":
         res = render(request,"home.html",context={"username":username})
      else:
    return render(request, "error.html", context={"msg": "用戶名和密碼錯誤"})
  else:
  return render(request,"error.html",context={"msg":"用戶名和密碼必填"}
前端頁碼 templates添加login.html頁面
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用戶登錄</title>
</head>
<body>
<form action="/user/api/login/" method="post">#前端提交數據到form表單的action屬性,action存實際的請求地址,以post形式 對用views文件的api_login
<label>用戶名:</label><input name="username">
<br>
<label>用戶名:</label><input name="pwd">
<br><br>
<button type="submit" name="登錄">登錄</button>
</form>>
</body>
</html>
驗證結果:瀏覽器請求url地址127.0.0.1:8000/user/login->輸入用戶名和地址調api_login接口 驗證邏輯返回相應的頁面
 
        



  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM