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

yipeiwu_com5年前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中函数的参数定义和可变参数用法。分享给大家供大家参考。具体如下: 刚学用Python的时候,特别是看一些库的源码时,经常会看到func(*args, **kwa...

详解Python安装tesserocr遇到的各种问题及解决办法

详解Python安装tesserocr遇到的各种问题及解决办法

Tesseract的安装及配置 在Python爬虫过程中,难免遇到各种各样的验证码问题,最简单的就是​这种验证码了,那么在遇到验证码的时候该怎么办呢?我们就需要OCR技术了,...

详解如何管理多个Python版本和虚拟环境

多个Python版本:在同一台机器上安装不同的Python,例如2.7和3.4。 虚拟环境:独立的环境,既可以同时安装特定版本的Python,也可以安装任何特定于项目的软件包,而不会影...

Python数据分析之如何利用pandas查询数据示例代码

前言 在数据分析领域,最热门的莫过于Python和R语言,本文将详细给大家介绍关于Python利用pandas查询数据的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的...

Python 使用 prettytable 库打印表格美化输出功能

Python 使用 prettytable 库打印表格美化输出功能

pip install prettytable 每次添加一行 from prettytable import PrettyTable # 默认表头:Field 1、Field 2....