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

相关文章

Linux-ubuntu16.04 Python3.5配置OpenCV3.2的方法

Linux-ubuntu16.04 Python3.5配置OpenCV3.2的方法

1.OpenCV下载 首先创建一个空的文件夹,进入文件夹执行如下命令,如我创建的文件夹是opencv-python cd opencv-python git clone https...

用Python制作简单的钢琴程序的教程

用Python制作简单的钢琴程序的教程

录一段音频,把它的音高改变50次并把每一个新的音频匹配到键盘的一个键位,你就能把电脑变成一架钢琴! 一段音频可以被编码为一组数值的数组(或者列表),像这样: 我们可以在数组中每隔一秒...

Python中 Lambda表达式全面解析

什么是Lambda表达式 “Lambda 表达式”(lambda expression)是一个匿名函数,Lambda表达式基于数学中的λ演算得名,直接对应于其中的lambda抽象(lam...

Python判断变量是否已经定义的方法

Python判断变量是否已经定义是一个非常重要的功能,本文就来简述这一功能的实现方法。 其实Python中有很多方法可以实现判断一个变量是否已经定义了。这里就举出最常用的两种作为示例,如...

python学习教程之使用py2exe打包

前言 本文主要给大家介绍了关于python使用py2exe打包的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧。 遇坑 之前经过折腾,pyinstaller打...