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程序设计有所帮助。

相关文章

Python实现将照片变成卡通图片的方法【基于opencv】

本文实例讲述了Python实现将照片变成卡通图片的方法。分享给大家供大家参考,具体如下: 之前的文章介绍了使用Photoshop将照片变成卡通图片,今次介绍用代码来实现这项任务,可以就此...

Python实现输入二叉树的先序和中序遍历,再输出后序遍历操作示例

本文实例讲述了Python实现输入二叉树的先序和中序遍历,再输出后序遍历操作。分享给大家供大家参考,具体如下: 实现一个功能:     输入:一颗二叉树的先...

浅谈pycharm的xmx和xms设置方法

PyCharm使用jre,所以设置内存使用的情况和eclipse类似。 编辑PyCharm安装目录下PyCharm 4.5.3\bin下的pycharm.exe.vmoptions文件,...

利用python list完成最简单的DB连接池方法

利用python list完成最简单的DB连接池方法

先来看查看效果: 在代码连接数据库后,并且执行三条sql后,将mysql直接重启掉,故我们的连接池连接均是不ok的,所以,它会全部删除再抓新的连接下来,重启mysql命令: 关于py...

PIL对上传到Django的图片进行处理并保存的实例

1. 介绍 上传的图片文件:如 pic = request.FILES["picture"] # pic是 <class 'django.core.files.uploaded...