Python使用装饰器进行django开发实例代码

yipeiwu_com6年前Python基础

本文研究的主要是Python使用装饰器进行django开发的相关内容,具体如下。

装饰器可以给一个函数,方法或类进行加工,添加额外的功能。

在这篇中使用装饰器给页面添加session而不让直接访问index,和show。在views.py中

def index(request):
    return HttpResponse('index')
 
def show(request):
    return HttpResponse('show')

这样可以直接访问index和show,如果只允许登陆过的用户访问index和show,那么就需修改代码

def index(request):
    if request.session.get('username'):
      return HttpResponse('index')
    else:
      return HttpResponse('login')<br data-filtered="filtered">
def show(request):
    if request.session.get('username'):
      return HttpResponse('show')
    else:
      return HttpResponse('login')

这样可以实现限制登陆过的用户访问功能,但是代码中也出现了许多的相同部分,于是可以把这些相同的部分写入一个函数中,用这样一个函数装饰index和show。这样的函数就是装饰器

def decorator(main_func):
  def wrapper(request):        #index,show中是一个参数,所以在wrapper中也是一个参数
    if request.session.get('username'):
      return main_func(request)
    else:
      return HttpResponse('login')
  return wrapper
 
@decorator
def index(request):
  return HttpResponse('index')
def show(request):
  return HttpResponse('show')

这样在视图函数中只要是一个参数就可以通过decorator函数装饰,如果有两个参数就需要修改装饰器

def decorator(main_func):
  def wrapper(request):       
    if request.session.get('username'):
      return main_func(request)
    else:
      return HttpResponse('login')
  return wrapper
 
def decorator1(main_func):
  def wrapper(request,page):       
    if request.session.get('username'):
      return main_func(request,page)
    else:
      return HttpResponse('login')
  return wrapper
 
@decorator
def index(request):
  return HttpResponse('index')
 
@decorator1
def show(request,page):
  return HttpResponse('show')

这个如果有一个参数就通过decorator来修饰,如果有两个参数就通过decorator1来修饰。于是可以通过动态参数的方式来结合decorator和decorator1,可以同时修饰index和show。

def decorator3(main_func):
    def wrapper(request,*args,**kwargs):
        if not request.session.get('username'):
            return main_func(request,*args,**kwargs)
        else:
            return HttpResponse('login')
    return wrapper
 
 
@decorator3
def index(request,*args,**kwargs):
    return HttpResponse('index')
@decorator3
def show(request,*args,**kwargs):
    return HttpResponse('show')

总结

以上就是本文关于Python使用装饰器进行django开发实例代码的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

相关文章

python递归打印某个目录的内容(实例讲解)

以下函数列出某个目录下(包括子目录)所有文件,本随笔重点不在于递归函数的实现,这是一个很简单的递归,重点在于熟悉Python 库os以及os.path一些函数的功能和用法。 1. os....

Python第三方库xlrd/xlwt的安装与读写Excel表格

前言 相信大家都应该有所体会,在平时经常会遇到处理 Excel 表格数据的情况,人工处理起来实在是太麻烦了,我们可以使用 Python 来解决这个问题,我们需要两个 Python 扩展,...

python时间序列按频率生成日期的方法

有时候我们的数据是按某个频率收集的,比如每日、每月、每15分钟,那么我们怎么产生对应频率的索引呢?pandas中的date_range可用于生成指定长度的DatetimeIndex。 我...

Python对象与引用的介绍

Python对象与引用的介绍

对象 Python 中,一切皆对象。每个对象由:标识(identity)、类型(type)、value(值)组成。 1. 标识用于唯一标识对象,通常对应于对象在计算机内存地址。使用...

详解Python2.x中对Unicode编码的使用

我确定有很多关于Unicode和Python的说明,但为了方便自己的理解使用,我还是打算再写一些关于它们的东西。   字节流 vs Unicode对象 我们先来用Python定...