zoukankan      html  css  js  c++  java
  • python装饰器

    一、json数据

    python的json模块可以用import json导入模块,主要是json.dumps()和json.loads()两个函数。
    JSON的编码格式和Python的语法格式相近,除了一些小的地方有所不同,例如Python中的True对应JSON编码格式的true,False对应false,None对应null。
    >>> d = { 'a' : True, 'b' : 'Hello', 'c' : None}
    >>> json.dumps(d)
    '{"a": true, "c": null, "b": "Hello"}'
    >>> print(json.dumps(data,sort_keys=True))
    {"name": "dwada", "price": 2345, "shares": 100}
    >>> print(json.dumps(data,sort_keys=True,indent=4))
    {
        "name": "dwada", 
        "price": 2345, 
        "shares": 100
    }
    发现Redis端口的Python脚本
    #!/usr/bin/python
    # -*- coding: utf-8 -*-
    import subprocess
    import json
    args = "netstat -tanp|awk -F':' '/redis-server/&&/LISTEN/{print $2}'|awk '{print $1}'"
    t=subprocess.Popen(args,shell=True,stdout=subprocess.PIPE).communicate()[0]
    ports=[]
    for port in t.split('
    '):
        if len(port) != 0:
            ports.append({'{#REDISPORT}':port})
    print json.dumps({'data':ports},indent=4,separators=(',',':'))
    输出为:
    {
        "data":[
            {
                "{#REDISPORT}":"6377"
            },
            {
                "{#REDISPORT}":"6378"
            }
        ]
    }

    二、装饰器

    装饰器概念(含义):以函数为参数,并返回一个函数的函数;

    装饰器本质上让其他函数在不需要做任何代码变动的前提下增加额外功能,装饰器的返回值也是一个函数对象。它经常用于有切面需求的场景,比如:插入日志、性能测试、事务处理、缓存、权限校验等场景。装饰器是解决这类问题的绝佳设计,有了装饰器,我们就可以抽离出大量与函数功能本身无关的雷同代码并继续重用。概括的讲,装饰器的作用就是为已经存在的对象添加额外的功能。

    了解三个知识点:

    1、一个函数可以作为参数传入另一个函数;

    2、一个函数可以作为返回值(return 函数名);

    3、函数可以使用外层空间的变量(作用域);

    PS:函数即变量,类型为函数

    高阶函数:

    满足下列条件之一就可成函数为高阶函数

    1. 某一函数当做参数传入另一个函数中

    2. 函数的返回值包含n个函数,n>0

    内嵌函数和变量作用域:

    定义:在一个函数体内创建另外一个函数,这种函数就叫内嵌函数(基于python支持静态嵌套域)

    闭包

    如果在一个内部函数里,对在外部作用域(但不是在全局作用域)的变量进行引用,那么内部函数就被认为是 closure

    内嵌函数+高阶函数+闭包=》装饰器

    装饰器应用案例:

    装饰器功能:函数超时则终止

     1 # -*- coding: utf-8 -*-  
     2 from threading import Thread  
     3 import time  
     4    
     5 class TimeoutException(Exception):  
     6     pass  
     7    
     8 ThreadStop = Thread._Thread__stop#获取私有函数  
     9    
    10 def timelimited(timeout):  
    11     def decorator(function):  
    12         def decorator2(*args,**kwargs):  
    13             class TimeLimited(Thread):  
    14                 def __init__(self,_error= None,):  
    15                     Thread.__init__(self)  
    16                     self._error =  _error  
    17                        
    18                 def run(self):  
    19                     try:  
    20                         self.result = function(*args,**kwargs)  
    21                     except Exception,e:  
    22                         self._error =e  
    23    
    24                 def _stop(self):  
    25                     if self.isAlive():  
    26                         ThreadStop(self)  
    27    
    28             t = TimeLimited()  
    29             t.start()  
    30             t.join(timeout)  
    31         
    32             if isinstance(t._error,TimeoutException):  
    33                 t._stop()  
    34                 raise TimeoutException('timeout for %s' % (repr(function)))  
    35    
    36             if t.isAlive():  
    37                 t._stop()  
    38                 raise TimeoutException('timeout for %s' % (repr(function)))  
    39    
    40             if t._error is None:  
    41                 return t.result  
    42    
    43         return decorator2  
    44     return decorator  
    45   
    46 @timelimited(2)  
    47 def fn_1(secs):  
    48     time.sleep(secs)  
    49     return 'Finished'  
    50        
    51 if __name__ == "__main__":  
    52     print fn_1(4)
    def auth(auth_type):
        def outer_wrapper(func):
            def wrapper(*args, **kwargs):
                print("wrapper func args:", *args, **kwargs)
                if auth_type == "local":
                    user = input("---name-->: ").strip()
                    passwd = input("----passwd-:").strip()
                    if user == username and passwd == password:
                        res = func(*args, **kwargs)
                        print("----->after authentication")
                        return res
                    else:
                        exit("passwd is error")
                elif auth_type == "ldap":
                    print("is error ldap!")
            return wrapper
        return outer_wrapper
    
    
    
    def index():
        print('welcome to index page')
    
    @auth(auth_type='local')
    def home():
        print('welcome to home page')
        return "from home"
    @auth(auth_type='ldap')
    def bbs():
        print('welcome to bbs page')
  • 相关阅读:
    Net163网页测试
    单片机无线上网的几种方式
    5V到3V3的电平转换-串口通信
    uart rs232 rs485
    转:TI公司CC系列的各种芯片的区别
    OpenWrt 路由器固件
    cortex-m4 不能运行Linux, 可以运行 uclinux, ucos iii
    Lwip Uip
    Java-06-交换两个变量的值
    Java-05-比较equals()与== [转载]
  • 原文地址:https://www.cnblogs.com/patrick0715/p/5786545.html
Copyright © 2011-2022 走看看