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开发实例代码的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

相关文章

python3设计模式之简单工厂模式

在Python3环境下,调试实现了《大话设计模式》中简单工厂模式,通过定义单独的工厂类,完成对具体的产品的实例化,参考链接 具体实现见代码: #!/usr/bin/env pytho...

python基本语法练习实例

1、打印九九乘法表 #只打印结果 for i in range(1,10): for j in range(1,i+1): print(i*j,end=" ") pr...

疯狂上涨的Python 开发者应从2.x还是3.x着手?

疯狂上涨的Python 开发者应从2.x还是3.x着手?

纵观各大编程语言在 2017 年的发展情况,我们会发现涌现出诸如 Go、Swift 这类后起之秀,而其中最为耀眼的当属 Python。之所以 Python 如此受捧,不仅仅是人工智能、数...

使用python分析git log日志示例

用git来管理工程的开发,git log是非常有用的‘历史'资料,需求就是来自这里,我们希望能对git log有一个定制性强的过滤。此段脚本就是在完成这种类型的任务。对于一个repo所有...

Python IDLE清空窗口的实例

使用Python IDLE时发现并没有清空当前窗口的快捷键,也没有像 clear 这样的命令,使用非常不便。 新建一个 ClearWindow.py脚本,源码如下: """ Cle...