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

相关文章

python3.5使用tkinter制作记事本

tkinter是Python下面向tk的图形界面接口库,可以方便地进行图形界面设计和交互操作编程。tkinter的优点是简单易用、与Python的结合度好。tkinter在Python...

python扫描proxy并获取可用代理ip的实例

今天咱写一个挺实用的工具,就是扫描并获取可用的proxy 首先呢,我先百度找了一个网站:http://www.xicidaili.com 作为例子 这个网站里公布了许多的国内外可用的代理...

Python3多线程操作简单示例

本文实例讲述了Python3多线程操作。分享给大家供大家参考,具体如下: python3 线程中常用的两个模块为: _thread threading(推荐使用) thread 模块已被...

Python格式化压缩后的JS文件的方法

本文实例讲述了Python格式化压缩后的JS文件的方法。分享给大家供大家参考。具体分析如下: 该脚本可以把压缩后的js文件格式上进行些还原,当然不会百分百完美,暂不处理语法问题,只是为了...

python3实现用turtle模块画一棵随机樱花树

python3实现用turtle模块画一棵随机樱花树

废话不多说了,直接上代码吧! #!/usr/bin/env python # coding=utf-8 # 画一棵樱花 import turtle import random...