基于django框架开发登录接口的四个方法

文件路径user/login

一、登录接口;get请求  username password url参数传递

二、登录接口:post请求,username password url-encode表单传递

意思实现的功能是 :

①、实现一:用户名和密码都是admin 显示 home.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后端真正的登录接口
路由修改:
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)
]
后端接口层:
def login(request):
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形式
<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接口 验证逻辑返回相应的页面
 



  

猜你喜欢

转载自www.cnblogs.com/qd1228/p/12981652.html
今日推荐