Python Foundation Day6

Source: Internet
Author: User
Tags hmac md5 encryption python script

Summary of the contents of this section:

Bubbling algorithm

Reflection

Module

Regular expressions

Bubbling algorithm:

The bubble sort is also one of the simplest and most basic sorting methods, as described in the previous two sorting approaches. The idea of bubble sorting is simple, which is to compare the size of adjacent elements, move small forward, large back, like bubbles in the water, the smallest elements after several moves, will eventually float to the surface.

For example analysis, the following data:

2 7 4 6 9 1 First compares the last two numbers, finds 1:9 small, and then moves forward

2 7 4 6 1 9 then compare 6 and 1

2 7 4 1 6 9 Continue to move forward, then 4 and 1

2 7 1 4 6 9 7 and 1 comparison

2 1 7 4 6 9 2 and 1

1 2 7 4 6 9 At this point, the first bubbling process is complete, and the smallest element 1 is moved to the first one, and no longer participates in the subsequent ordering process. The next bubbling process is the same, comparing 6 and 9, and so on, and finally getting the results.

Reflection:

Example: A routing system that forges web frames
Reflection: Manipulating its members (GETATTR,DELATTR,SETATTR,HASATTR) in a string-based way to an object (module)
Extensions: Importing Modules
Import
From import
__import__ ()

Def f1 ():    print (' F1 ') F1 () # F1     #函数名 # "F1"   #字符串  two different

    # in the form of a string to the object (module) operation (Find/check/delete/set) member, called Reflection # Delattr () #删掉模块里的成员函数 (all in memory operation, Reload will restore the original module) # setattr () # Set the module in the Clerk # Hasattr (commons,f): #看commons模块里是否有f这个函数成员 # GetAttr () The main function of this method is to implement the reflection mechanism. This means that the method instance can be obtained through a string.    In this way, you can put a method that a class might want to invoke in the configuration file and load it dynamically when needed. #commons. Pydef login (): print ("Cool login Face") def logout (): Print ("Exit Cool page") def Home (): Print ("Cool homepage") #fanshe. Pydef Run        (): INP = input (' Please enter the URL to access: ') #直接输入函数名 if Hasattr (COMMONS,INP): #看模块里是否有这个函数成员 func = getattr (COMMONS,INP) Func () else:print ("404") if __name__ = = ' __main__ ': Run () #运行结果请输入要访问的url: Login #注意输入的字符串炫酷的登录面 # # # # ################################## #def Run (): INP = input (' Enter the URL to access: ') obj = __import__ ("Commons") # via string file name Import m, f = inp.split ('/') if Hasattr (obj, INP): # See if the module has this function member Func = getattr (obj, INP) func () Els E:print ("404") if __name__ = = ' __main__ ': Run () #执行结果请输入要访问的url: Login #注意输入的字符串炫酷的登录面 #################### ###################### #def Run (): INP = input (' Please enter the URL to access: ') m, f = inp.split ('/') obj = __import__ (m) if Hasa TTR (obj, f): # See if the module has this function member Func = getattr (obj, F) func () else:print ("404") #结果请输入要访问的url: Common S/login #注意输入的字符串炫酷的登录面 ############################################ #lib/account.pydef login (): print ("Cool login Face") #    Fanshe.pydef run (): INP = input (' Please enter the URL to access: ') m, f = inp.split ('/') obj = __import__ ("lib." + M, fromlist=true) # import the module under Lib if hasattr (obj, f): # See if the module has this function member Func = getattr (obj, F) func () Else:print ("     404 ") if __name__ = = ' __main__ ': Run () #结果请输入要访问的url: Account/login #注意输入的字符串炫酷的主页

Module:

Print (VARs (commons)) #看模块commons里有哪些变量

Special variables in the module:

__doc__: Document String. If the module does not have a document, this value is none.
__NAME__: The module name is always defined, even if you use import. As it takes an alias, or assigns another variable name.
__DICT__: Contains a dictionary of the property names-attributes available in the module; The object that can be accessed by using the module name. Property name.
__FILE__: Contains the file path for the module. It is important to note that the built-in module does not have this property, and accessing it throws an exception!

__PACKAGE__: A directory or package that introduces a module.

#commons. py "I am the annotation" #module. Pyimport commonsprint (commons.__doc__) #获取文件注释 # result I'm comment print (__file__) #当前py文件所在的路径__ name__  #只有执行当前文件的时候 to execute the Run function, the special variable of the current file if  __name__ = = "__main__":    run ()        print (commons.__cached__)  #获取字节码位置 # results C:\USERS\QINLING\PYCHARMPROJECTS\S13\DAY6\__PYCACHE__\COMMONS.CPYTHON-35.PYCD = Os.path.dirname ( Os.path.dirname (Os.path.abspath (__file__))) print (d) #结果C: \users\qinling\pycharmprojects\s13    #s13/day6/ module.py from Lib import accountprint (account.__package__)  #假设文件夹lib下有一个account. py# results Lib

Hashlib Encryption Module

MD5 encryption is irreversible but can be compared with ciphertext

Import Hashlib # ######## MD5 ####### #hash = HASHLIB.MD5 () # Help (hash.update) hash.update (bytes (' admin ', encoding= ' utf-8 ') print (Hash.hexdigest ()) print (Hash.digest ()) #以上加密算法虽然依然非常厉害, but when there is a flaw, namely: through the pool can be reversed. Therefore, it is necessary to add a custom key to the encryption algorithm to do encryption. obj = hashlib.md5 (bytes (' sdfsd ', encoding= ' Utf-8 '))  #加key Two layers of encryption are more secure Obj.update (bytes (' 123 ', encoding= ' Utf-8 ')) # Python3  #3.0 requires byte conversion Python2 does not require result = Obj.hexdigest () print (result)  #d34ed9e2a8d7a756128f5838809ec95e # Python also has an HMAC module, which internally creates a key and content for us to further process and then encrypt the import hmac h = hmac.new (bytes (' 898oafs09f ', encoding= "Utf-8")) H.update (bytes (' admin ', encoding= "Utf-8")) print (H.hexdigest ())

Sys

Used to provide actions related to the Python interpreter:

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         the largest 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.stdin          input related sys.stdout         output related sys.stderror       error related

If the Sys.path path list does not have the path you want, it can be added by Sys.path.append (' path ').

OS

Used to provide system-level operations:

OS.GETCWD () Gets the current working directory, that is, the directory path of the current Python script work os.chdir ("DirName") changes the current script working directory, equivalent to the shell Cdos.curdir Return to current directory: ('. ') Os.pardir Gets the parent directory string name of the current directory: (' ... ') Os.makedirs (' Dir1/dir2 ') can generate a multi-level recursive directory Os.removedirs (' dirname1 ') if the directory is empty, then deleted, and recursively to the previous level of the directory, if also empty, then delete, and so on Os.mkdir (' DirName ' Generate a single-level directory, equivalent to the shell mkdir dirnameos.rmdir (' dirname ') delete the single-level empty directory, if the directory is not empty can not be deleted, error; equivalent to RmDir dirnameos.listdir in the shell (' dirname ') lists all files and subdirectories under the specified directory, including hidden files, and prints os.remove () Delete a file Os.rename ("Oldname", "new") Rename File/directory OS                  . Stat (' Path/filename ') gets file/directory information OS.SEP operating system-specific path delimiter, win under "\ \", Linux for "/" Os.linesep The current platform uses the line terminator, win under "\t\n", Linux for "\ n" os.pathsep the string used to split the file path Os.name string indicates the current use of the platform. Win-> ' NT ';       Linux-> ' POSIX ' Os.system ("Bash command") runs a shell command that directly displays the Os.environ get system environment variable Os.path.abspath (PATH) Return path normalized absolute path Os.path.split (path) splits path into directory and file name two tuples return Os.pathThe. DirName (path) returns the directory of path. In fact, the first element of Os.path.split (path) os.path.basename returns the last file name of path. If path ends with a/or \, then a null value is returned. The second element of Os.path.split (path), os.path.exists (path), returns True if path exists, or Falseos.path.isabs if path is not present if path is An absolute path that returns Trueos.path.isfile (path) If path is an existing file that returns TRUE. Otherwise, return Falseos.path.isdir (path) True if path is a directory that exists.  Otherwise return Falseos.path.join (path1[, path2[, ...]) When multiple paths are combined and returned, the parameters before the first absolute path are ignored Os.path.getatime (path) returns the file or directory to which path points to the last access time Os.path.getmtime (path) returns the file or directory that the path points to The last modified time

Re

The RE module in Python provides regular expression-related operations:

Character:

. Match any character other than line break
\w match letters or numbers or underscores or kanji
\s matches any whitespace character
\d Matching numbers
\b Match the beginning or end of a word
^ Start of matching string
$ match End of string

Number:

* Repeat 0 or more times
+ Repeat one or more times
? Repeat 0 or one time
{n} repeats n times
{n,} repeats n or more times
{N,m} repeats n to M times

Python Foundation Day6

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.