Django框架用户注销功能实现方法分析

yipeiwu_com5年前Python基础

本文实例讲述了Django框架用户注销功能实现方法。分享给大家供大家参考,具体如下:

HttpResponse()里有个delete_cookie()方法专门用来删除cookie

我们到此来完整的实现一下:访问首页如果没有登录,就跳转到登录页面,登录成功之后再跳转回来的过程。

3个方法,index、login、logout

# coding:utf-8
from django.shortcuts import render,render_to_response
# Create your views here.
from django.http import HttpResponse
from UserClass import UserLogin
def index(request):
  msg = {'username':'guest'}
  if request.COOKIES.get('userlogin_username') != None :
    msg['username'] = request.COOKIES.get('userlogin_username')
  myReponse = render_to_response("index.html",msg)
  return myReponse
def login(request):
  msg = {'result': ''}
  if request.method == 'POST':
    getUserName = request.POST.get('username')
    getPwd = request.POST.get('pwd')
    # 实例化UserLogin类
    loginObj = UserLogin(getUserName,getPwd)
    if loginObj.isLogin():
      myReponse = HttpResponse("<script>self.location='/index'</script>")
      myReponse.set_cookie('userlogin_username',getUserName,3600)
      return myReponse
    else:
      msg['result'] = '用户名或密码错误'
  myReponse = render_to_response("login.html", msg)
  return myReponse
# 用户注销
def logout(request):
  r = HttpResponse()
  r.delete_cookie('userlogin_username')
  r.write("<script>self.location='/index'</script>")
  return r

首页模板index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>首页</title>
</head>
<body>
  <h2>这是首页,当前登录用户是:{{ username }}</h2>
  {% ifequal username "guest" %}
  <p><a href="/login" rel="external nofollow" >登录</a></p>
  {% else %}
  <p><a href="/logout" rel="external nofollow" >安装退出</a></p>
  {% endifequal %}
</body>
</html>

其中用到了Django的模板语法

希望本文所述对大家基于Django框架的Python程序设计有所帮助。

相关文章

vscode 配置 python3开发环境的方法

vscode 配置 python3开发环境的方法

vscode来写python,配置灵活,界面美观,是个非常好的选择。我这里是在ubuntu系统下配置vscode的python3开发环境,当然也可以参照本文在其它操作系统下配置vscod...

基于python监控程序是否关闭

这篇文章主要介绍了基于python监控程序是否关闭,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 监控一个服务系exe在他关闭后打印,...

Python使用Shelve保存对象方法总结

Shelve是一个功能强大的Python模块,用于对象持久性。搁置对象时,必须指定一个用于识别对象值的键。通过这种方式,搁置文件成为存储值的数据库,其中任何一个都可以随时访问。 Pyth...

python比较两个列表是否相等的方法

本文实例讲述了python比较两个列表是否相等的方法。分享给大家供大家参考。具体如下: 这里演示了 == 和 is两种方法的区别: L1 = [1, ('a', 3)] # same...

Python ORM框架SQLAlchemy学习笔记之安装和简单查询实例

最近正好在寻求一种Python的数据库ORM (Object Relational Mapper),SQLAlchemy (项目主页)这个开源项目进入了我的视线,本来想尝试着使用Djan...