Python advanced (8): common module 2 + exception handling, python advanced

Source: Internet
Author: User

Python advanced (8): common module 2 + exception handling, python advanced

Some time ago I talked about a lot of modules. I didn't talk about objects at the time. I didn't talk about them today. I also talked about exception handling.

 

I. hashlib Module

Python hashlib provides common digest algorithms, such as MD5 and SHA1.

Digest algorithms are also called hash algorithms and hash algorithms. It converts data of any length into a fixed-length data string through a function.

Import hashlib md5 = hashlib. md5 () md5.update ('How to use md5 in python hashlib? '. 'Utf-8') print (md5.hexdigest () Calculation Result: d26a53750bc40b38b65a520292f69306Md5

If the data volume is large, you can call update () multiple times in multiple parts. The calculation result is the same:

Md5 = hashlib. md5 () md5.update ('How to use md5 in '. 'utf-8') md5.update ('python hashlib? '. 'Utf-8') print (md5.hexdigest ())Md5

MD5 is the most common Digest algorithm, which is very fast. The generated result is a fixed 128-bit byte, which is usually represented by a 32-bit hexadecimal string. Another common Digest algorithm is SHA1. Calling SHA1 is similar to calling MD5:

Import hashlib sha1 = hashlib. sha1 () sha1.update ('How to use sha1 in python hashlib? '. 'Utf-8') print sha1.hexdigest ()Sha1

The result of SHA1 is 160 bits, usually expressed in a 40-bit hexadecimal string. SHA256 and SHA512 are more secure than SHA1, but the more secure the algorithm is, the longer the digest length.

Digest algorithm application:

Any website that allows users to log on will store the user name and password for user logon. The user name and password are stored in the database. If the user password is stored in plain text, and the database leaks, the passwords of all users will fall into the hands of hackers. In addition, website O & M personnel can access the database, that is, they can obtain the passwords of all users. The correct password saving method is not to store the user's plaintext password, but to store the digest of the user's password, such as MD5

Import hashlibuser = 'lln' pwd = '000000' md5 _ obj = hashlib. md5 () md5_obj.update (pwd. encode ('utf-8') print (md5_obj.hexdigest ())Application

Because Abstract Functions are unidirectional functions and cannot decrypt plain text through summaries, what are the basis of many deciphering tools? Many users prefer simple passwords such as 123456,888888 and password. Therefore, hackers can calculate the MD5 value of these commonly used passwords in advance to obtain a push table, use your digest to match the database hit.

Because the MD5 values of common passwords are easily calculated, make sure that the stored user passwords are not the MD5 values of common passwords that have been calculated, this method is implemented by adding a complex string to the original password, commonly known as "adding salt ":

Import hashlibuser = 'lln' pwd = '000000' md5 _ obj = hashlib. md5 (user. encode ('utf-8') # Add md5_obj.update (pwd. encode ('utf-8') print (md5_obj.hexdigest ())Add salt

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 digest reverse plain text cannot be used). It can only be used to prevent tampering, however, its one-way computing feature determines that the user password can be verified without storing the plaintext password.

 

Ii. configparser Module

This module is applicable to the configuration file in a format similar to the windows INI file. It can contain one or more sections, and each section can have multiple parameters (Key = value ).

1. Create a configuration file

[DEFAULT] ServerAliveInterval = 45 Compression = yesCompressionLevel = 9ForwardX11 = yes [bitbucket.org] User = hg [topsecret.server.com] Port = 50022ForwardX11 = noCommon File import configparserconfig = configparser. configParser () config ["DEFAULT"] = {'serveraliveinterval': '45', 'compression': 'yes', 'compressionlevel': '9', 'forwardx11 ': 'Yes'} config ['bitbucket. org '] = {'user': 'Hg'} config ['topsecret .server.com '] = {'host port': '2013', 'forwardx11 ': 'No'} with open ('example. ini ', 'w') as configfile: config. write (configfile)File Creation

2. Search for files

Import configparserconfig = configparser. configParser () # --------------------------- search for file content, print (config. sections () # [] config. read ('example. ini ') print (config. sections () # ['bitbucket. org ', 'topsecret .server.com'] print ('bytebong. com 'in config) # Falseprint ('bitbucket. org 'in config) # Trueprint (config ['bitbucket. org '] ["user"]) # huplint (config ['default'] ['compression']) # yesprint (config ['topsecret .server.com'] ['forwardx11']) # noprint (config ['bitbucket. org ']) # <Section: bitbucket.org> for key in config ['bitbucket. org ']: # note that the default key print (key) print (config. options ('bitbucket. org ') # Find 'bitbucket' in the same for loop. print (config. items ('bitbucket. org ') # Find 'bitbucket. print (config. get ('bitbucket. org ', 'compression') # yes value corresponding to the key in the get method SectionFile Search

3. add, delete, and modify operations

Import configparserconfig = configparser. configParser () config. read ('example. ini ') config. add_section ('yuanyuan ') config. remove_section ('bitbucket. org ') config. remove_option ('topsecret .server.com ', "forwardx11") config. set ('topsecret .server.com ', 'k1', '123') config. set ('yuany', 'k2', '123') config. write (open ('new2. ini ', "w "))Add, delete, and modify

 

Iii. logging Module

Update tomorrow...

 

 

Iv. Exception Handling

1. Exception types

X # NameError: name 'X' is not definedint ('abc') # ValueError: invalid literal for int () with base 10: 'abc' l = [] l [10000] # IndexError: list index out of rangeclass Foo: passFoo. x # AttributeError: type object 'foo' has no attribute 'X' 1/0 # ZeroDivisionError: division by zerodic = {'K': 'V'} dic ['k2'] # KeyError: 'k2' l = [1] ll = iter (l) print (next (ll) # StopIterationPreviously we encountered an exception x # NameError: name 'X' is not definedint ('abc') # ValueError: invalid literal for int () with base 10: 'abc' l = [] l [10000] # IndexError: list index out of rangeclass Foo: passFoo. x # AttributeError: type object 'foo' has no attribute 'X' 1/0 # ZeroDivisionError: division by zerodic = {'K': 'V'} dic ['k2'] # KeyError: 'k2' l = [1] ll = iter (l) print (next (ll) # StopIterationCommon exceptionsMore exceptions

2. Exception Handling

1) What is an exception?

After an exception occurs

After the exception, the code will not be executed, that is, the bug we mentioned.

2) Exception Handling

The python interpreter detects an error and triggers an exception (it also allows the programmer to throw an exception)

Programmers write specific code specifically to catch this exception (this code is irrelevant to the Program Logic and related to Exception Handling)

If the capture succeeds, it will go to another Processing Branch and execute the logic you have customized for it so that the program will not crash. This is exception handling.

3) Why should we handle exceptions?

The python parser executes the program. When an error is detected, it triggers an exception. When an exception is triggered and not processed, the program terminates at the current exception, the code below will not run, and who will use a software that suddenly crashes.

Therefore, you must provide an exception processing mechanism to enhance the robustness and fault tolerance of your program.

3. Exception Handling

1) Basic Processing

Try: The detected code block occurrence t exception type: once an exception is detected in try, the logic at this position is executed.Basic syntax try: int (num) Comment t ValueError: print ('enter a number ')Simple instance

An exception class can only be used to handle specified exceptions. if an exception is not specified, it cannot be processed.

# If no exception is caught, the program directly reports an error s1 = 'hello' try: int (s1) failed t IndexError as e: print eView Code

2) Multiple branches

S1 = 'hello' try: int (s1) failed t IndexError as e: print (e) failed t KeyError as e: print (e) failed t ValueError as e: print (e)View Code

3) omnipotent exception

10 thousand of python exceptions can be abnormal: Exception, which can catch any exceptions.

S1 = 'hello' try: int (s1) expect t Exception as e: print (e)Universal exception

It is not recommended because it is difficult to find exceptions after capturing them, and it is unfriendly to handle all exceptions in the same way.

4) Other organizations with exceptions

S1 = 'hello' try: int (s1) failed t IndexError as e: print (e) failed t KeyError as e: print (e) failed t ValueError as e: print (e) # failed t Exception as e: # print (e) else: print ('execute me if there is no Exception in the try code block ') finally: print (' This module is executed no matter whether the Exception or not, usually cleaning ')View Code

5) actively throw an exception

Try: raise TypeError ('Type error') failed t Exception as e: print (e)View Code

6) custom exception

Class EvaException (BaseException): def _ init _ (self, msg): self. msg = msgtry: raise EvaException ('Type error') failed t EvaException as e: print (e)View Code

7) Assertions

# Assert condition assert 1 = 1 assert 1 = 2 # a judgment that throws an exception # It is basically difficult to use. It is only applicable to certain scenarios.View Code

4. When to handle exceptions

When this block of code has a strange problem, you can solve the specific mistakes you don't think.

You can think of exceptions, and there may be many exceptions in this code, which cannot be enumerated one by one.

Exception Handling outside a large code segment is prohibited

If you only want to prevent and make restrictions within the scope you can think of, you can use if

 

Related Article

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.