python-Decorator Detailed

Source: Internet
Author: User
Tags hmac

Beginner python, what is a decorator?

1: adorners are functions, except that the function can have special meanings, adorners are used to decorate functions or classes, and adorners can be used to add actions before and after the function executes.

2: At least two layers of function

Way one: the way of understanding
def auth (func):    def inner ():        print ' before '        func ()    return Innerdef F1 ():    print ' f1 ' ret = auth (F1) F1 = RETF1 ()
Execution Result:

Before
F1

Execution process:

# 1: Execute def auth (func): # 2:def F1 (): # 3:ret = Auth (F1) Execute auth function, pass F1 to Func, # because the inner function is not executed, return returns directly, but the inner function name is returned, Inside the func== incoming F1 # 4: this time ret = innet function name # 5: Execute f1 = ret, assign inner function name to F1 # 5: Execute F1 (), that is, execute inner function, then print before, the Func function inside it, but func== F1, so execute F1 function, print F1

Way two: normal way
def auth (func):    def inner ():        print ' before '        func ()    return Inner@authdef F1 ():    print ' F1 ' F1 ()

Execution process:

# 1: Use @auth instead of two commented-out lines. # 2: Execute @auth, use the following function name F1 as the parameter of the Auth # 3: Execute the AUTH function, the decorated function as the parameter auth (foo), the return value of the Auth function, assign to the function name of the decorated function @auth

Method Three: Do the operation before and after the function is executed separately
def auth (func):    def inner ():        print ' before '        func ()        print ' after '    return inner@authdef F1 ():    print ' F1 ' F1 () results:beforef1after
Mode four: Adorner with parameters
def auth (func):    def Inner (ARG):        print ' verify '        func ' "        print ' log '    return inner@authdef F1 (arg ):    print ' F1 ', ARGF1 (' with parameters ') result: Verify F1 with parameter log
Method Five: Contains return value
def auth (func):    def Inner (*args,**kwargs):        print ' verify '        tmp = func (*args,**kwargs)        print ' login log '        return tmp    return inner@authdef fetch_server_list ():    print ' server list '    server_list = [1,2,3,4,5]    return Server_listret = Fetch_server_list () print ret result: Verify server list login log [
1, 2, 3, 4, 5]Method Six: Several different types of parameters.
def login ():    name = ' CCC '    if name = = ' CGT ':        return True    else:        return falsedef Auth (func):    def Inner (*args,**kwargs):        is_login = login ()        if not is_login:            return ' invaild username '        tmp = func (*args, **kwargs)        print ' log '        return tmp    return inner@authdef fetch_server_list ():    print ' Server list '    server_list = [1,2,3,4,5]    return server_listret = Fetch_server_list () print ret result:
1: If name = CCC Output Invaild Username 2: Output Server list log in if name = CGT [1, 2, 3, 4, 5]Method VII: Example verification function, using key value

function function

def login (key):    local = "1234567890"    if key  = = Local:        return True    else:        return falsedef auth ( Func):    def Inner (*args,**kwargs):        key = Kwargs.pop (' token ')                             #token是从调用函数是传参进来的        
        Is_login = Login (key)        if not  is_login:            return ' invaild username '        tmp = func (*args,**kwargs)        Print "Login log"        return tmp    return inner@authdef fetch_server_list (ARG):    print ' server list '    Server_ List = [1,2,3,4,5,6]    return server_list

Calling functions

Import Tmpkey = "1234567890" #key = "12345678" ret = tmp.fetch_server_list (' text ', Token=key) print ret

Execution Result: 1: If the key is the same, the correct execution result is: Server list
Login log
[1, 2, 3, 4, 5, 6]2: If key is different, the output invaild username

Mode eight: Multi-adorner
def W1 (func):    def inner ():        print ' before--1 '        func ()        print ' after--1 '    return innerdef W2 (func):    def inner ():        print ' before--2 '        func ()        print ' after--2 '    return inner@w2@w1def F1 ():    print ' 1111 ' F1 () results:before
--2
Before
--1 1111
After
--1
After
--2Recursive

Fibonacci numbers refer to such a sequence of 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368

Implementation method:

def func (arg1,arg2):    if arg1 = = 0:        pass    arg3 = arg1 + arg2    print Arg3    func (ARG2,ARG3) func (0,1)

If the value is about 1000, return this number

def func (arg1,arg2):    if arg1 = = 0:        pass    arg3 = arg1 + arg2    if Arg3 >:        return arg3    ret = Fu NC (ARG2,ARG3)    return retprint func (0,1)
Module

A module is a collection of code that implements a function with a piece of code

For example: The OS is a system-related module; file is a module related to the operation of files

Types of modules
    • Custom Modules
    • Built-in Modules
    • Open source Module
Custom Modules

1: Define Module

The. py file that you write to implement a feature is called defining a module

2: Import Module

Modules to be used, the first to import modules, modules are imported into the following several ways:

    1. Import Module
    2. From module.x.x import x
    3. From module.x.x import x as Rename
    4. From module.x.x Import *

The import module is actually telling the Python interpreter to explain which PY file

    • Import a py file, the interpreter interprets the py file
    • Import a package, the interpreter interprets the __init__.py file under the package

Path of the Import module

  1:import SYS
  2:print Sys.path
  3: Results:
  4: [' E:\\python\\day5 ', ' E:\\python ', ' c:\\windows\\system32\\python27.zip ', ' c:\\python27\\dlls ', ' C:\\Python27\\ Lib ', ' C:\\python27\\lib\\plat-win ', ' c:\\python27\\lib\\lib-tk ', ' c:\\python27 ', ' c:\\python27\\lib\\ Site-packages ']

You can also add the path you want: sys.path.append (' path ')

Various directories can be obtained through the OS module, for example:

  1:import SYS
  2:import OS
  3:pre_path = Os.path.abspath ('.. /‘)
  4:print Pre_path
  5:sys.path.append (Pre_path)

Open source Module

Download installation

Way One:

# Yum
# PIP
# Apt-get

Way two:

# Download Source code
# Unzip the source code
# Enter Directory
# Compile and decode Python setup.py build
# Install the source Python setup.py install

Comments:

Because it is a source installation, you need to use the GCC and Python development environment

Yum–y Install GCC
Yum–y Install Python-devel

After the installation is successful, the module is automatically installed to a directory in the Sys.path

Import Module

And the import method in the custom module is consistent

Example:

Module Paramiko

Paramiko is a module for remote control that can be used to command or file operations on a remote server. Remote management within fabric and ansible is implemented using Paramiko

1: Download and install

# Pycrypto, because the Paramiko module is internally dependent on Pycrypto, so download and install Pycrypto # download Install Pycryptowget http://files.cnblogs.com/files/wupeiqi/ PYCRYPTO-2.6.1.TAR.GZTAR-XVF pycrypto-2.6.1.tar.gzcd pycrypto-2.6.1python setup.py buildpython setup.py install#  Enter the python environment, import Crypto Check whether the installation succeeded #  import Crypto # download Install Paramikowget http://files.cnblogs.com/files/wupeiqi/ PARAMIKO-1.10.1.TAR.GZTAR-XVF paramiko-1.10.1.tar.gzcd paramiko-1.10.1python setup.py buildpython setup.py Install #< c2/> into the Python environment, import Paramiko Check for successful installation #   import Paramiko

2: Using modules

Execute command-connect to server with username and password

#!/usr/bin/env python#-*-coding:utf-8-*-import paramikossh = Paramiko. Sshclient () Ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ()) ssh.connect (' 10.0.0.9 ', +, ' root ', ' 123456 ') Stdin,stdout,stderr = Ssh.exec_command (' df ') print Stdout.read () Ssh.close () results: [email protected]:/server/scripts# python 10.py Filesystem     1k-blocks    used Available use% mounted On/dev/sda3       19276064 1532552  16757656   9%/tmpfs             508148       0    508148   0%/dev/shm/dev/sda1         194241   36013    147988  20%/boot
Built-in Modules

1:os

Used to provide system-level operations

Import osos.getcwd () # Gets the current working directory Os.chdir () # Changes the current script working directory, equivalent to the shell under Cdos.curdir # Return to current directory: (' ... ') Os.pardir # Gets the string name of the parent directory of the current directory: (' ... ') Os.makedirs (' dirname1/dirname2 ') # can generate a multi-level recursive directory Os.removedirs (' dirname1 ') # If the directory is empty, then delete, and recursively to the previous level of the directory, if it is also empty, then delete, and so on Os.mkdir (                     ' DirName ') # Generate a single-level directory; Os.listdir (' dirname ') # Lists all files and subdirectories under the specified directory, including Yin Can files, and prints os.remove as a list ()                          # Delete a file Os.rename (' oldname ', ' newname ') # Rename file/directory Os.stat (' Path/filename ') # Get File/directory information os.sep                      # output operating system-specific path delimiter, win:\\ LINUX:/OS.LINESEP # outputs the line terminator used by the current platform, win:\t\n linux:\nos.pathsep # output string for splitting the file path Os.name # Output string indicates the current use of platform win:nt Linux:posixos.system (' Bash comm and ') # Run shell command, direct display Os.environ # GET system environment variable Os.path.abspath () # Return path normalized absolute path OS.P Ath.split () # divides path into directory and file name two tuples return Os.path.dirnAme () # Returns the directory of path, which is actually the first element of Os.path.split (path) os.path.basename () # Returns the last file name of path. If path is terminated with a/or \, the return is null os.path.exists () # returns TRUEOS.PATH.ISABS () if the path exists () # returns TRUEO if it is an absolute path S.path.isfile () # If path is an existing file, the return value is Trueos.path.isdir () # If path is an existing directory, the return value is TRUEOS.PATH.J Oin () # Returns a combination of multiple paths, the parameter before the first absolute path is ignored Os.path.getatime (path) # Returns the last access time of the file or directory to which path is pointing os.path.getmt IME (PATH) # returns the last modified time of the file or directory to which path is pointing

2:sys

Used to provide an interpreter-related action

SYS.ARGV                            # command-line argument list, the first element is the program itself path Sys.exit (n)                         # exits the program, exit normally (0) sys.version                         # Gets the version information of the Python interpreter sys.maxint                          # maximum int value Sys.path                            # returns the search path for the module, using the value of the PYTHONPATH environment variable when initializing Sys.platform                        # Returns the operating system platform name Sys.stdout.write (' please: ') val = Sys.stdin.readline () [:-1]

3:hashlib

Used to encrypt the operation that you want to shut down instead of the MD5 module and the SHA module

Import Hashlibhash = hashlib.md5 (' 123456 ')                # Add a custom Keyhash.update (' admin ')                        # actual to encrypt Keyprint hash.hexdigest ()                      # outputs the final encrypted value # Result: b9d11b3be25f5a1a7dc8ca04cd310b28#======================================================== ================================================
using the HMAC module, he internally processes the key and content we created and then encrypts it.
Import Hmach = hmac.new (' 123456 ') h.update (' admin ') print h.hexdigest () # Result: 20238ad293024e2ea2f505db927cd52e

python-Decorator Detailed

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.