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

yipeiwu_com6年前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贪心算法实例小结

本文实例讲述了Python贪心算法。分享给大家供大家参考,具体如下: 1. 找零钱问题:假设只有 1 分、 2 分、五分、 1 角、二角、 五角、 1元的硬币。在超市结账 时,如果 需要...

Python基于回溯法子集树模板实现图的遍历功能示例

Python基于回溯法子集树模板实现图的遍历功能示例

本文实例讲述了Python基于回溯法子集树模板实现图的遍历功能。分享给大家供大家参考,具体如下: 问题 一个图: A --> B A --> C B --> C B -...

Python制作数据导入导出工具

python 2.6编写,自己瞎写的,备用 ''' Export and Import ElasticSearch Data. Simple Example At __mai...

python实现快速排序的示例(二分法思想)

python实现快速排序的示例(二分法思想)

本文介绍了python实现快速排序的示例(二分法思想),分享给大家,具体如下: 实现思路 将所需要的数字存入一个列表中 1.首先,设置将最左侧的那个数设置为基准数,在列表中索引为0 2...

python实现猜单词小游戏

Python初学者小游戏:猜单词,供大家参考,具体内容如下 游戏逻辑:就像我们曾经英语学习机上的小游戏一样,电脑会从事先预置的词库中抽取单词,然后给出单词的字母数量,给定猜解次数,然后让...