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

相关文章

wxpython中Textctrl回车事件无效的解决方法

本文实例讲述了wxpython中Textctrl回车事件无效的解决方法。分享给大家供大家参考,具体如下: 今天使用wxptyhon的Textctrl控件开发客户端时遇到了一个问题, 按照...

Python中使用strip()方法删除字符串中空格的教程

 strip()方法返回所有字符从开始及字符串的末尾(默认空格字符)被去除后的字符串的一个副本。 语法 以下是strip()方法的语法: str.strip([chars]...

django-rest-framework解析请求参数过程详解

django-rest-framework解析请求参数过程详解

前言 我们在django-rest-framework 自定义swagger 文章中编写了接口, 调通了接口文档. 接口文档可以直接填写参数进行请求, 接下来的问题是如何接受参数, 由...

python中virtualenvwrapper安装与使用

virtualenv与virtualenvwrapper 当涉及到python项目开发时为了不污染全局环境,通常都会使用环境隔离管理工具virtualenv与virtualenvwra...

Python安装第三方库的3种方法

【方法一】: 通过setuptools来安装python模块 首先下载 http://peak.telecommunity.com/dist/ez_setup.py NOTE: 最好下载...