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判断对象是否相等及eq函数的讲解

摘要 什么是python对象的标识 python对象相等的判断 自定义python对象相等的条件 python对象的标识 python对象标识就是python对象自身的要...

django 微信网页授权登陆的实现

django 微信网页授权登陆的实现

一、准备工作 0x00 开发前准备 服务号!!! 微信认证。 备案过的域名。 服务器。  0x01 手动触发dns更新 0x02 配置业务域名 &nb...

详解Python中的装饰器、闭包和functools的教程

装饰器(Decorators) 装饰器是这样一种设计模式:如果一个类希望添加其他类的一些功能,而不希望通过继承或是直接修改源代码实现,那么可以使用装饰器模式。简单来说Python中的装饰...

Python编程使用*解包和itertools.product()求笛卡尔积的方法

本文实例讲述了Python编程使用*解包和itertools.product()求笛卡尔积的方法。分享给大家供大家参考,具体如下: 【问题】 目前有一字符串s = "['a', 'b']...

Python利用flask sqlalchemy实现分页效果

Python利用flask sqlalchemy实现分页效果

Flask-sqlalchemy是关于flask一个针对数据库管理的。文中我们采用一个关于员工显示例子。 首先,我们创建SQLALCHEMY对像db。 from flask impo...