码迷,mamicode.com
首页 > 其他好文 > 详细

模块大战及装饰器

时间:2015-11-28 11:54:37      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:

装饰器

装饰器是函数,只不过该函数可以具有特殊的含义,装饰器用来装饰函数或类,使用装饰器可以在函数执行前和执行后添加相应操作。

简单实例

def wrapper(func):

    def result():

        print ‘before‘

        func()

        print ‘after‘

    return result

 

@wrapper

def foo():

    print ‘foo‘


复杂实例

*****************************************************
原理:多层装饰器先执行@后函数,在将结果加上@重新执行
*****************************************************
def Before(request,kargs):    #定义两个函数,before和after
    print ‘before‘
    
def After(request,kargs):
    print ‘after‘
 
 
def Filter(before_func,after_func):   #定义一个装饰器,以两个函数作为参数
    def outer(main_func):    #定义装饰器内第一层函数,传入主函数
        def wrapper(request,kargs):   #定义装饰器内第二层函数,传入三个函数需要的参数
            before_result = before_func(request,kargs) #执行before函数,得到返回值
            if(before_result != None):   #如果函数返回值不为空,返回这个值
                return before_result;
            
            main_result = main_func(request,kargs) #执行main函数,得到返回值
            if(main_result != None):   #如果函数返回值不为空,返回这个值
                return main_result;
            
            after_result = after_func(request,kargs) #执行after函数,得到返回值
            if(after_result != None):   #如果函数返回值不为空,返回这个值
                return after_result;
            
        return wrapper     #返回第二层函数函数的内存地址
    return outer     #返回外层函数的
    
@Filter(Before, After)     #对下面的函数使用装饰器
def Index(request,kargs):    #定义一个函数,main
    print ‘index‘
    
    
if __name__ == ‘__main__‘:    #如果是主模块,调用main函数
    Index(1,2)

 

 

hmac模块

用于加密,部分方法定义如下:

def update(self, msg):
    """Update this hashing object with the string msg.
    使其带字符串的msg更新这个哈希对象
    """
    self.inner.update(msg)


def digest(self):
    """Return the hash value of this hashing object.

    This returns a string containing 8-bit data.  The object is
    not altered in any way by this function; you can continue
    updating the object after calling this function.
    返回哈希对象的值。返回一个8位数据。这个对象不会被这个函数用任何方式改变,你可以在调用此方法后继续更新这个对象
    """
    h = self._current()
    return h.digest()


def hexdigest(self):
    """Like digest(), but returns a string of hexadecimal digits instead.
    和digest()方法一样,但是返回一个16进制的字符串
    """
    h = self._current()
    return h.hexdigest()


def new(key, msg = None, digestmod = None):
    """Create a new hashing object and return it.

    key: The starting key for the hash.
    msg: if available, will immediately be hashed into the object‘s starting
    state.

    You can now feed arbitrary strings into the object using its update()
    method, and can ask for the hash value at any time by calling its digest()
    method.

  创建一个哈希对象然后返回它。key:哈希起始的key msg:如果可用,将马上被hash进对象的开始状态 你可以使用update方法提供任意的字符串进对象,
  可以在调用digest后在任何时间调用hash值
    """
    return HMAC(key, msg, digestmod)


实验实例


import hmac

h = hmac.new(‘liqx‘)      #将信息转化为hash值

h.update(‘2015-11-22 23:41:30‘)      #更新hash值(加盐)

print h.hexdigest()       #返回hash值(16进制)

 

**********控制台**********

02f8c81a959a6f887311c6733b85af0f

 

json模块

序列化字典等对象

序列化的概念:序列化 (Serialization[‘s?r??la?z])将对象的状态信息转换为可以存储或传输的形式的过程

方法如下:

_default_encoder = JSONEncoder(
    skipkeys=False,
    ensure_ascii=True,
    check_circular=True,
    allow_nan=True,
    indent=None,
    separators=None,
    encoding=‘utf-8‘,
    default=None,
)


def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True,
        allow_nan=True, cls=None, indent=None, separators=None,
        encoding=‘utf-8‘, default=None, sort_keys=False, **kw):
    """Serialize ``obj`` as a JSON formatted stream to ``fp`` (a
    ``.write()``-supporting file-like object).
 序列化一个对象到文件中

    If ``skipkeys`` is true then ``dict`` keys that are not basic types
    (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
    will be skipped instead of raising a ``TypeError``.

    If ``ensure_ascii`` is true (the default), all non-ASCII characters in the
    output are escaped with ``\uXXXX`` sequences, and the result is a ``str``
    instance consisting of ASCII characters only.  If ``ensure_ascii`` is
    ``False``, some chunks written to ``fp`` may be ``unicode`` instances.
    This usually happens because the input contains unicode strings or the
    ``encoding`` parameter is used. Unless ``fp.write()`` explicitly
    understands ``unicode`` (as in ``codecs.getwriter``) this is likely to
    cause an error.

    If ``check_circular`` is false, then the circular reference check
    for container types will be skipped and a circular reference will
    result in an ``OverflowError`` (or worse).

    If ``allow_nan`` is false, then it will be a ``ValueError`` to
    serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``)
    in strict compliance of the JSON specification, instead of using the
    JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).

    If ``indent`` is a non-negative integer, then JSON array elements and
    object members will be pretty-printed with that indent level. An indent
    level of 0 will only insert newlines. ``None`` is the most compact
    representation.  Since the default item separator is ``‘, ‘``,  the
    output might include trailing whitespace when ``indent`` is specified.
    You can use ``separators=(‘,‘, ‘: ‘)`` to avoid this.
 添加缩进,可以使用,:避免

    If ``separators`` is an ``(item_separator, dict_separator)`` tuple
    then it will be used instead of the default ``(‘, ‘, ‘: ‘)`` separators.
    ``(‘,‘, ‘:‘)`` is the most compact JSON representation.

    ``encoding`` is the character encoding for str instances, default is UTF-8.

    ``default(obj)`` is a function that should return a serializable version
    of obj or raise TypeError. The default simply raises TypeError.

    If *sort_keys* is ``True`` (default: ``False``), then the output of
    dictionaries will be sorted by key.
 key排序

    To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
    ``.default()`` method to serialize additional types), specify it with
    the ``cls`` kwarg; otherwise ``JSONEncoder`` is used.

    """
    # cached encoder
    if (not skipkeys and ensure_ascii and
        check_circular and allow_nan and
        cls is None and indent is None and separators is None and
        encoding == ‘utf-8‘ and default is None and not sort_keys and not kw):
        iterable = _default_encoder.iterencode(obj)
    else:
        if cls is None:
            cls = JSONEncoder
        iterable = cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii,
            check_circular=check_circular, allow_nan=allow_nan, indent=indent,
            separators=separators, encoding=encoding,
            default=default, sort_keys=sort_keys, **kw).iterencode(obj)
    # could accelerate with writelines in some versions of Python, at
    # a debuggability cost
    for chunk in iterable:
        fp.write(chunk)

实例:

a = {‘k1‘:‘v1‘,‘k2‘:‘v2‘}
with open(‘test‘) as b
json.dump(a,b)
print open(‘test‘).readlines()

*********************************************
[‘{"k2": "v2", "k1": "v1"}‘]

 

def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True,
        allow_nan=True, cls=None, indent=None, separators=None,
        encoding=‘utf-8‘, default=None, sort_keys=False, **kw):
    """Serialize ``obj`` to a JSON formatted ``str``.
 序列化一个对象到json字符串
 
    if (not skipkeys and ensure_ascii and
        check_circular and allow_nan and
        cls is None and indent is None and separators is None and
        encoding == ‘utf-8‘ and default is None and not sort_keys and not kw):
        return _default_encoder.encode(obj)
    if cls is None:
        cls = JSONEncoder
    return cls(
        skipkeys=skipkeys, ensure_ascii=ensure_ascii,
        check_circular=check_circular, allow_nan=allow_nan, indent=indent,
        separators=separators, encoding=encoding, default=default,
        sort_keys=sort_keys, **kw).encode(obj)

实例:
import json
a = {‘k1‘:‘v1‘,‘k2‘:‘v2‘}  #字典
b = json.dumps(a)   #json字符串
print(b)
 
**************************
{"k2": "v2", "k1": "v1"}  #序列化字典的字符串,key值带有""

 

a = [1,2,3]    #列表
b = json.dumps(a)   #字符串
print(b)
**************************
[1, 2, 3]

 

_default_decoder = JSONDecoder(encoding=None, object_hook=None,
                               object_pairs_hook=None)


def load(fp, encoding=None, cls=None, object_hook=None, parse_float=None,
        parse_int=None, parse_constant=None, object_pairs_hook=None, **kw):
    """Deserialize ``fp`` (a ``.read()``-supporting file-like object containing
    a JSON document) to a Python object.
 反序列化ftp 成为一个python对象

 If the contents of ``fp`` is encoded with an ASCII based encoding other
    than utf-8 (e.g. latin-1), then an appropriate ``encoding`` name must
    be specified. Encodings that are not ASCII based (such as UCS-2) are
    not allowed, and should be wrapped with
    ``codecs.getreader(fp)(encoding)``, or simply decoded to a ``unicode``
    object and passed to ``loads()``

    ``object_hook`` is an optional function that will be called with the
    result of any object literal decode (a ``dict``). The return value of
    ``object_hook`` will be used instead of the ``dict``. This feature
    can be used to implement custom decoders (e.g. JSON-RPC class hinting).

    ``object_pairs_hook`` is an optional function that will be called with the
    result of any object literal decoded with an ordered list of pairs.  The
    return value of ``object_pairs_hook`` will be used instead of the ``dict``.
    This feature can be used to implement custom decoders that rely on the
    order that the key and value pairs are decoded (for example,
    collections.OrderedDict will remember the order of insertion). If
    ``object_hook`` is also defined, the ``object_pairs_hook`` takes priority.

    To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
    kwarg; otherwise ``JSONDecoder`` is used.

    """
    return loads(fp.read(),
        encoding=encoding, cls=cls, object_hook=object_hook,
        parse_float=parse_float, parse_int=parse_int,
        parse_constant=parse_constant, object_pairs_hook=object_pairs_hook,
        **kw)


实例
a = json.load(open(‘test‘))   #打开一个文件,反序列化
print(a,type(a))
************************************
({u‘k2‘: u‘v2‘, u‘k1‘: u‘v1‘}, <type ‘dict‘>) #反序列化为unicode字符的字典

def loads(s, encoding=None, cls=None, object_hook=None, parse_float=None,
        parse_int=None, parse_constant=None, object_pairs_hook=None, **kw):
    """Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON
    document) to a Python object.
 反序列化一个字符串 成为一个json对象

实例:
a = ‘{"k1":"v1","k2":"v2"}‘  #json字符串
b = json.loads(a)
print(b,type(b))

*****************************
({u‘k2‘: u‘v2‘, u‘k1‘: u‘v1‘}, <type ‘dict‘>)  #反序列化为unicode字符的字典

 

ConfigParser
A setup file consists of sections, lead by a "[section]" header,
and followed by "name: value" entries
一个包含章节的安装文件,以[]开头,后面跟着键值

类:
class ConfigParser(RawConfigParser):
 
ConfigPerser

类:
class RawConfigParser:
    def __init__(self, defaults=None, dict_type=_default_dict,
                 allow_no_value=False):
        self._dict = dict_type
        self._sections = self._dict()
        self._defaults = self._dict()
        if allow_no_value:
            self._optcre = self.OPTCRE_NV
        else:
            self._optcre = self.OPTCRE
        if defaults:
            for key, value in defaults.items():
                self._defaults[self.optionxform(key)] = value

    def defaults(self):
        return self._defaults
        返回默认值

    def sections(self):
        """Return a list of section names, excluding [DEFAULT]"""
        # self._sections will never have [DEFAULT] in it
        返回一个包含[]的列表
       

       
        return self._sections.keys()

    def add_section(self, section):
        """Create a new section in the configuration.
    添加一个[],如果存在,抛异常
    
实例:
import ConfigParser

c = ConfigParser.ConfigParser()
result = c.read(‘test1‘)
#print(result)

c.add_section(‘a2‘)       #添加section,只添加进实例
print(c.sections())
******************************
[‘a1‘, ‘a2‘]


        Raise DuplicateSectionError if a section by the specified name
        already exists. Raise ValueError if name is DEFAULT or any of it‘s
        case-insensitive variants.
        """
        if section.lower() == "default":
            raise ValueError, ‘Invalid section name: %s‘ % section

        if section in self._sections:
            raise DuplicateSectionError(section)
        self._sections[section] = self._dict()

    def has_section(self, section):
        """Indicate whether the named section is present in the configuration.
    判断是否有这个[]
        The DEFAULT section is not acknowledged.
        """
       
        return section in self._sections

实例
c = ConfigParser.ConfigParser()
result = c.read(‘test‘)
c1 =  c.has_section(‘a3‘)
print(c1)
********************
False

    def options(self, section):
        """Return a list of option names for the given section name."""
        列出所给[]中的选项
        try:
            opts = self._sections[section].copy()
        except KeyError:
            raise NoSectionError(section)
        opts.update(self._defaults)
        if ‘__name__‘ in opts:
            del opts[‘__name__‘]
        return opts.keys()
实例
c = ConfigParser.ConfigParser()
result = c.read(‘test‘)
print(c.options(‘a1‘))   
***************************************
[‘a‘]    #option指的是类似key的值

    def read(self, filenames):
        """Read and parse a filename or a list of filenames.

        读取和解析一个文件,或一个文件的列表,调用read(fp,file方法)再调用__read()方法,读取文件内容传给实例
        Files that cannot be opened are silently ignored; this is
        designed so that you can specify a list of potential
        configuration file locations (e.g. current directory, user‘s
        home directory, systemwide directory), and all existing
        configuration files in the list will be read.  A single
        filename may also be given.
    不能打开的文件将被忽略,你可以提供一个配置文件路径的列表。
        Return list of successfully read files.
        """
        if isinstance(filenames, basestring):
            filenames = [filenames]
        read_ok = []
        for filename in filenames:
            try:
                fp = open(filename)
            except IOError:
                continue
            self._read(fp, filename)
            fp.close()
            read_ok.append(filename)
        return read_ok
实例:
import ConfigParser
c = ConfigParser.ConfigParser()
c1 = c.read(‘test1‘)
print(c1)
print(c.sections())
**************************************
[‘test1‘]
[‘a1‘]


    def readfp(self, fp, filename=None):
        """Like read() but the argument must be a file-like object.
    读一个文件对象,参数必须有一个readline方法。
        The `fp‘ argument must have a `readline‘ method.  Optional
        second argument is the `filename‘, which if not given, is
        taken from fp.name.  If fp has no `name‘ attribute, `<???>‘ is
        used.

        """
        if filename is None:
            try:
                filename = fp.name
            except AttributeError:
                filename = ‘<???>‘
        self._read(fp, filename)

    def get(self, section, option):
 ‘‘‘
 取option对应的值
 ‘‘‘
        opt = self.optionxform(option)
        if section not in self._sections:
            if section != DEFAULTSECT:
                raise NoSectionError(section)
            if opt in self._defaults:
                return self._defaults[opt]
            else:
                raise NoOptionError(option, section)
        elif opt in self._sections[section]:
            return self._sections[section][opt]
        elif opt in self._defaults:
            return self._defaults[opt]
        else:
            raise NoOptionError(option, section)
实例
c = ConfigParser.ConfigParser()
result = c.read(‘test‘)
print(c.get(‘a1‘,‘a‘))
*************************************
b

    def items(self, section):
 ‘‘‘
 获取[]对应的值
 ‘‘‘
        try:
            d2 = self._sections[section]
        except KeyError:
            if section != DEFAULTSECT:
                raise NoSectionError(section)
            d2 = self._dict()
        d = self._defaults.copy()
        d.update(d2)
        if "__name__" in d:
            del d["__name__"]
        return d.items()

c = ConfigParser.ConfigParser()
result = c.read(‘test‘)
print(c.items(‘a1‘))
******************************************
[(‘a‘, ‘b‘)]   #返回一个列表

    def _get(self, section, conv, option):
        return conv(self.get(section, option))

    def getint(self, section, option):
 ‘‘‘
 得到option对应值的整数部分
 ‘‘‘
        return self._get(section, int, option)

    def getfloat(self, section, option):
        return self._get(section, float, option)

    _boolean_states = {‘1‘: True, ‘yes‘: True, ‘true‘: True, ‘on‘: True,
                       ‘0‘: False, ‘no‘: False, ‘false‘: False, ‘off‘: False}

    def getboolean(self, section, option):
        v = self.get(section, option)
        if v.lower() not in self._boolean_states:
            raise ValueError, ‘Not a boolean: %s‘ % v
        return self._boolean_states[v.lower()]

    def optionxform(self, optionstr):
        return optionstr.lower()

    def has_option(self, section, option):
        """Check for the existence of a given option in a given section."""
 判断给出的option是否存在于给出的section
        if not section or section == DEFAULTSECT:
            option = self.optionxform(option)
            return option in self._defaults
        elif section not in self._sections:
            return False
        else:
            option = self.optionxform(option)
            return (option in self._sections[section]
                    or option in self._defaults)

    def set(self, section, option, value=None):
        """Set an option.
 设置一个option的值
 """
        if not section or section == DEFAULTSECT:
            sectdict = self._defaults
        else:
            try:
                sectdict = self._sections[section]
            except KeyError:
                raise NoSectionError(section)
        sectdict[self.optionxform(option)] = value

实例:
c = ConfigParser.ConfigParser()
result = c.read(‘test‘)
c.set(‘a1‘,‘a‘,value=‘123‘)  #value=123失败:TypeError: argument of type ‘int‘ is not iterable
print(c.get(‘a1‘,‘a‘))
*************************************************
123


    def write(self, fp):
        """Write an .ini-format representation of the configuration state."""
 写入一个对象进文件
        if self._defaults:
            fp.write("[%s]\n" % DEFAULTSECT)
            for (key, value) in self._defaults.items():
                fp.write("%s = %s\n" % (key, str(value).replace(‘\n‘, ‘\n\t‘)))
            fp.write("\n")
        for section in self._sections:
            fp.write("[%s]\n" % section)
            for (key, value) in self._sections[section].items():
                if key == "__name__":
                    continue
                if (value is not None) or (self._optcre == self.OPTCRE):
                    key = " = ".join((key, str(value).replace(‘\n‘, ‘\n\t‘)))
                fp.write("%s\n" % (key))
            fp.write("\n")

实例
c = ConfigParser.ConfigParser()
c.read(‘test‘)
c.write(open(‘test1‘,‘w‘))
*************************************************
#test1如下
[a1]
a = 123


    def remove_option(self, section, option):
        """Remove an option.
 删除一个option
 """
        if not section or section == DEFAULTSECT:
            sectdict = self._defaults
        else:
            try:
                sectdict = self._sections[section]
            except KeyError:
                raise NoSectionError(section)
        option = self.optionxform(option)
        existed = option in sectdict
        if existed:
            del sectdict[option]
        return existed
实例
c = ConfigParser.ConfigParser()
c.read(‘test‘)
c.remove_option(‘a1‘,‘a‘)
print(c.options(‘a1‘))
***************************************************
[]


    def remove_section(self, section):
        """Remove a file section.
 删除一个section
 """
        existed = section in self._sections
        if existed:
            del self._sections[section]
        return existed
实例
c = ConfigParser.ConfigParser()
c.read(‘test‘)
c.remove_section(‘a1‘)
c.write(open(‘test‘,‘w‘))   #将对象写入文件
print(c.sections())
********************************************
[]

    #
    # Regular expressions for parsing section headers and options.
    #
    SECTCRE = re.compile(
        r‘\[‘                                 # [
        r‘(?P<header>[^]]+)‘                  # very permissive!
        r‘\]‘                                 # ]
        )
    OPTCRE = re.compile(
        r‘(?P<option>[^:=\s][^:=]*)‘          # very permissive!
        r‘\s*(?P<vi>[:=])\s*‘                 # any number of space/tab,
                                              # followed by separator
                                              # (either : or =), followed
                                              # by any # space/tab
        r‘(?P<value>.*)$‘                     # everything up to eol
        )
    OPTCRE_NV = re.compile(
        r‘(?P<option>[^:=\s][^:=]*)‘          # very permissive!
        r‘\s*(?:‘                             # any number of space/tab,
        r‘(?P<vi>[:=])\s*‘                    # optionally followed by
                                              # separator (either : or
                                              # =), followed by any #
                                              # space/tab
        r‘(?P<value>.*))?$‘                   # everything up to eol
        )

    def _read(self, fp, fpname):
        """Parse a sectioned setup file.

        The sections in setup file contains a title line at the top,
        indicated by a name in square brackets (`[]‘), plus key/value
        options lines, indicated by `name: value‘ format lines.
        Continuations are represented by an embedded newline then
        leading whitespace.  Blank lines, lines beginning with a ‘#‘,
        and just about everything else are ignored.
        """
        cursect = None                        # None, or a dictionary
        optname = None
        lineno = 0
        e = None                              # None, or an exception
        while True:
            line = fp.readline()
            if not line:
                break
            lineno = lineno + 1
            # comment or blank line?
            if line.strip() == ‘‘ or line[0] in ‘#;‘:
                continue
            if line.split(None, 1)[0].lower() == ‘rem‘ and line[0] in "rR":
                # no leading whitespace
                continue
            # continuation line?
            if line[0].isspace() and cursect is not None and optname:
                value = line.strip()
                if value:
                    cursect[optname].append(value)
            # a section header or option header?
            else:
                # is it a section header?
                mo = self.SECTCRE.match(line)
                if mo:
                    sectname = mo.group(‘header‘)
                    if sectname in self._sections:
                        cursect = self._sections[sectname]
                    elif sectname == DEFAULTSECT:
                        cursect = self._defaults
                    else:
                        cursect = self._dict()
                        cursect[‘__name__‘] = sectname
                        self._sections[sectname] = cursect
                    # So sections can‘t start with a continuation line
                    optname = None
                # no section header in the file?
                elif cursect is None:
                    raise MissingSectionHeaderError(fpname, lineno, line)
                # an option line?
                else:
                    mo = self._optcre.match(line)
                    if mo:
                        optname, vi, optval = mo.group(‘option‘, ‘vi‘, ‘value‘)
                        optname = self.optionxform(optname.rstrip())
                        # This check is fine because the OPTCRE cannot
                        # match if it would set optval to None
                        if optval is not None:
                            if vi in (‘=‘, ‘:‘) and ‘;‘ in optval:
                                # ‘;‘ is a comment delimiter only if it follows
                                # a spacing character
                                pos = optval.find(‘;‘)
                                if pos != -1 and optval[pos-1].isspace():
                                    optval = optval[:pos]
                            optval = optval.strip()
                            # allow empty values
                            if optval == ‘""‘:
                                optval = ‘‘
                            cursect[optname] = [optval]
                        else:
                            # valueless option handling
                            cursect[optname] = optval
                    else:
                        # a non-fatal parsing error occurred.  set up the
                        # exception but keep going. the exception will be
                        # raised at the end of the file and will contain a
                        # list of all bogus lines
                        if not e:
                            e = ParsingError(fpname)
                        e.append(lineno, repr(line))
        # if any parsing errors occurred, raise an exception
        if e:
            raise e

        # join the multi-line values collected while reading
        all_sections = [self._defaults]
        all_sections.extend(self._sections.values())
        for options in all_sections:
            for name, val in options.items():
                if isinstance(val, list):
                    options[name] = ‘\n‘.join(val)

模块大战及装饰器

标签:

原文地址:http://www.cnblogs.com/liqxd/p/5002404.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!