Python Chapter 1.13---module

Source: Internet
Author: User
Tags parent directory sha1 shuffle python script

One. Time

1. Time representation

In Python, there are usually three ways to represent time: timestamp, tuple (struct_time), formatted time string:
(1) timestamp (timestamp): Typically, a timestamp represents an offset that is calculated in seconds, starting January 1, 1970 00:00:00. We run "type (Time.time ())" and return the float type.

(2) formatted time string (format string): ' 1988-03-16 '

(3) tuple (struct_time): Struct_time A total of 9 elements total nine elements: (year, month, day, time, minute, second, week of the year, Day of the year, etc.)

#<1> timestamp >>> import time>>> time.time () 1493200540.9646277# <2> time string >>> Time.strftime ('%y-%m-%d%x ') ' 2017-04-26 17:56:30 ' # <3> time tuple >>> time.localtime () time.struct_time (tm_ year=2017, tm_mon=4, tm_mday=26, tm_hour=17, tm_min=56, tm_sec=48, tm_wday=2, tm_yday=116, tm_isdst=0)

Summary: Time stamp is the time that the computer can recognize; The time string is the time that a person can read; Tuples are used to manipulate time.

2. Conversion of several time forms

(1)

#一 timestamp <----> structured time:  localtime/gmtime   mktime>>> time.localtime (3600*24) >>> Time.gmtime (3600*24) >>> time.mktime (Time.localtime ()) #字符串时间 <----> structured time: strftime/strptime>> > Time.strftime ("%y-%m-%d%x", Time.localtime ()) >>> time.strptime ("2017-03-16", "%y-%m-%d")

(2)

>>> Time.asctime (Time.localtime (312343423)) ' Sun Nov 10:03:43 1979 ' >>> time.ctime (312343423) ' sun Nov 25 10:03:43 1979 '

1 #--------------------------Other Method 2 # Sleep (secs) 3 # thread postpones the specified time to run, in seconds.

Two. Random module

>>> import random>>> random.random ()    #大于0且小于1 small tree 0.7032311694364002>>> >> > Random.randint (1,5) #1 <= and <=5 integer 3>>> >>> random.randrange (1,3) #大于等于1且小于3之间的整数2 > >> >>> Random.choice ([1, ' [4,5]]) #1或23或 [4,5][4, 5]>>> >>> random.sample ([1, ' 23 ') , [4,5]],2] #列表元素任意2个组合 [' 23°c ', [4, 5]]>>> >>> >>> random.uniform (1,3) #大于1 Decimals less than 3 1.1161744833134866>>> >>> >>> >>> l = [1,3,5,7,9]>>> >>> Random.shuffle (l)  #打乱次序 >>> l[1, 3, 7, 5, 9]>>> random.shuffle (l) #再次打乱 >>> l[9, 7, 3, 1, 5]

#生成验证码:

Import Random def V_code ():     "'     for  in range (5):        num=random.randint (0,9)        Alf=CHR (Random.randint (65,90))  #ASIIC code        add=random.choice ([num,alf])        code="". Join ([Code,str (add)])    return  codePrint(V_code ())
View Code

Three. Hashlib

1. Algorithm Introduction

Python's hashlib provides a common digest algorithm, such as MD5,SHA1 ...

Abstract algorithm, also known as hashing algorithm, hashing algorithm. It uses a function to convert any length of data into a fixed length data string (usually with a 16 binary string)

Abstract the algorithm is to calculate the fixed-length summary digest by the Digest function f () to the data of arbitrary length, in order to find out whether the original data has been tampered with.

Abstract the algorithm can point out whether the data has been tampered with, because the digest function is a one-way function, it is easy to calculate f (data), but it is very difficult to digest data by using it. Also, making a bit change to the original data will result in a completely different summary of the calculations.

We use the Common Digest algorithm MD5 as an example to calculate the MD5 value of a string:

Import HASHLIBM = Hashlib.md5 () m.update (' Alex '. Encode (' UTF8 '))   print (M.hexdigest ()) # Output result 534b44a19bf18d20b71ecc4eb77c572f

ImportHASHLIBM=hashlib.md5 () m.update ('Alex'. Encode ('UTF8'))#534b44a19bf18d20b71ecc4eb77c572fPrint(M.hexdigest ()) M.update ('Alex'. Encode ('UTF8'))#AlexalexPrint(M.hexdigest ()) n= HASHLIB.MD5 ('Salt'. Encode ('UTF8')) N.update (b'Alexalex')Print(N.hexdigest ())
Example One

If you have a large amount of data, you can call Update () multiple times in chunks, and the result is the same:

ImportHASHLIBM=hashlib.md5 () m.update ('How do I use the md5 in Python hashlib?'. Encode ('UTF8'))Print(M.hexdigest ())##结果#d26a53750bc40b38b65a520292f69306m=hashlib.md5 () m.update ('How to use MD5 in'. Encode ('UTF8')) M.update ('python hashlib?'. Encode ('UTF8'))Print(M.hexdigest ())##结果d26a53750bc40b38b65a520292f69306
View Code

MD5 is the most common digest algorithm and is fast enough to generate a fixed byte of bytes, typically represented by a 32-bit 16 binary string. Another common digest algorithm is SHA1, which calls SHA1 and calls MD5 exactly like:

Import Hashlib SHA1 = HASHLIB.SHA1 () sha1.update (' How to use SHA1 in ') sha1.update (' Python hashlib? ') Print Sha1.hexdigest ()

The result of the SHA1 is a bit byte, which is usually represented by a 40-bit 16 binary string. Algorithms that are more secure than SHA1 are SHA256 and SHA512, but the more secure the algorithm is, the slower it is, and the longer the digest length.

2. Summary algorithm Application

Any site that allows users to log on will store the user name and password that the user is logged on to. How do I store a user name and password? method is stored in the database table:

Name    | password--------+----------Michael | 123456bob     | abc999alice   | alice2008

If the user password is saved in clear text, if the database is compromised, all users ' passwords fall into the hands of the hacker. In addition, the site operators can access the database, that is, to get all the user's password. The correct way to save a password is not to store the user's plaintext password, but instead to store a digest of the user's password, such as MD5:

Username | Password---------+---------------------------------Michael  | E10adc3949ba59abbe56e057f20f883ebob      | 878ef96e86145580c38c87f0410ad153alice    | 99b1c2188db85afee403b1536010c2c9

Consider such a situation, many users like to use 123456,888888,password these simple password, so, the hacker can calculate in advance these common password MD5 value, get a counter-push table:

' e10adc3949ba59abbe56e057f20f883e ': ' 123456 ' 21218cca77804d2ba1922c33e0151105 ': ' 888888 ' 5f4dcc3b5aa765d61d8327deb882cf99 ': ' Password '

This way, no need to crack, only need to compare the database MD5, hackers get the use of common password user account.

For the user, of course, do not use too simple password. But can we enhance the protection of simple passwords in program design?

Because the MD5 value of the common password is easy to calculate, so to ensure that the Stored user password is not the MD5 of the commonly used password, this method is implemented by adding a complex string to the original password, commonly known as "Add salt":

HASHLIB.MD5 ("Salt". Encode ("UTF8"))

Salt processing of the MD5 password, as long as the salt is not known by hackers, even if the user entered a simple password, it is difficult to MD5 the plaintext password.

But if two users all use the same simple password such as 123456, in the database, two identical MD5 values will be stored, which means that the password of the two users is the same. Is there a way for users with the same password to store different MD5?

If the user cannot modify the login, it is possible to calculate the MD5 by using the login as part of the salt, so that users who implement the same password also store different MD5.

Abstract algorithms are widely used in many places. Note that the digest algorithm is not an encryption algorithm and cannot be used for encryption (because plaintext cannot be reversed by the digest), but it is only used for tamper-proof, but its one-way computing feature determines that the user's password can be verified without storing the plaintext password.

Four. OS Module

An OS module is an interface that interacts with the operating system

"' 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 the current directory: ('. ') Os.pardir Gets the parent directory string name of the current directory: (' ... ') Os.makedirs (' dirname1/dirname2 ') 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 ') to 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 the shell rmdir Dirnameos.listdir (' dirname ') lists all files and subdirectories under the specified directory, including hidden files, and prints os.remove () 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 under "\ \", Linux for "/" OS.LINESEP output the current platform using the line terminator, win under "\t\n", Linux "\ N "os.pathsep output is used to split the file path of the string win under;, Linux: The Os.name output 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.path.dirname (path) to the directory where path is returned. 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) If path exists, returns true if path does not exist, returns Falseos.path.isabs (path) If path is an absolute path, returns Trueos.path.isfile (path Returns true if path is a file that exists. 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, the parameters before the first absolute path are ignored Os.path.getatime (path) returns the last access time of the file or directory to which path is pointing os.path.getmtime (path) Returns the last modified time of the file or directory pointed to by Path Os.path.getsize (path) returns the size of path "

Module Operation:

#----->1ImportOSPrint(OS.GETCWD ()) F= Open ('Test.txt','W') Os.chdir (R'D:\pycharm\catalog\py_fullstack_s4\day32')#Change path 33 toF= Open ('Test2.txt','W')Print(OS.GETCWD ())#----->2ImportOsos.makedirs ('aaaaa/bbb') Os.removedirs ('aaaaa/bbb')#----->3ImportOSPrint(Os.listdir (R'd:\pycharm\catalog\py_fullstack_s4/day33'))##输出结果##[' aaaaa ', ' osmy.py ', ' test.txt ', ' validation.py ', ' __init__.py ', ' Digest hash. Py ', ' random number. Py ']Print(Os.stat (R'D:\pycharm\catalog\py_fullstack_s4/day33/test.txt'))#----->4#' pang ' +os.sep+ ' di 'Print(Os.name)Print(Os.system ('dir'))#----->5ImportOsabs= Os.path.abspath ('Test.txt')Print(Os.path.basename (ABS))Print(Os.path.dirname (ABS))#Output Resultstest.txtd:\pycharm\catalog\py_fullstack_s4\day33#----->6ImportOss1= R'D:/pycharm/catalog'S2= R'py_fullstack_s4/day33'#print (S1+OS.SEP+S2)ret= Os.path.join (S1,S2)#Recommended MethodPrint(ret)#Output ResultsD:/pycharm/catalog\py_fullstack_s4/day33
View Code

Five. SYS module
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

Python Chapter 1.13---module

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.