Python module: Hashlib module, configparse module, logging module

Source: Internet
Author: User
Tags md5

I. Hashlib module

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

Abstract the algorithm is also called hash algorithm and hashing algorithm. It uses a function to convert any length of data into a fixed length data string (usually represented by 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.

  For the same string, no matter how long the string, as long as it is the same, regardless of the environment, how many times, in any language using the same algorithm \ The same means the results will always be the same, as long as not the same string, the results must be different.

1. MD5 algorithm

 MD5 is an algorithm, a 32-bit string, each character is a hexadecimal, MD5 algorithm features: Efficient fast algorithm relatively simple

Import'hello,world! '  = hashlib.md5 () md5_obj.update (S.encode ('utf-8'= MD5 _obj.hexdigest ()print(res, type (res), Len (res))#  c0e84e870874dd37ed0d164c7986f03a <class ' str ' >

  Although the value of MD5 is not reversed, there are a lot of people who get the original string by hitting the library.

crash: User password by calculating the value of the MD5 to save the database, but there are a number of people by experimenting with many passwords, Calculate the MD5 value of these passwords, and then go to get someone else's database (password) to compare the MD5 value, if the same can be obtained by the number of passwords. So the password is not safe. So you can solve this problem by adding salt.

 username =  " jack  "  password  =  " 123jack  "  md5_obj  = HASHLIB.MD5 (Username.encode ( " utf-8 " Span style= "COLOR: #800000" > ")" #   Add the username as Salt  md5_obj.update (Password.encode ( " utf-8   "  = Md5_obj.hexdigest ()  print  (res) #   B94B1A2CD520DDC887DF5C946E246EAC  

MD5 in addition to the user password can be protected, but also the consistency of the school check file

With open ('123','RB') as F1:#RB ModeMd5_obj1 =hashlib.md5 () md5_obj1.update (F1.read ()) Res1=md5_obj1.hexdigest () with open ('321','RB') as F2:#I put the file 321 content set with the file 1231 likeMd5_obj2 =hashlib.md5 () md5_obj2.update (F2.read ()) Res2=md5_obj2.hexdigest ()Print(RES1)#537c68a40a4736c27358ae78616c9fa7Print(Res2)#537c68a40a4736c27358ae78616c9fa7

Two. configparse Module

  The module applies to configuration files in a format similar to a Windows INI file, and can contain one or more sections (section), each of which can have multiple parameters (key = value).

ImportConfigparserconfig=Configparser. Configparser ()#print (Config.sections ()) # []Config.read ('Example.ini')#print (Config.sections ()) # [' bitbucket.org ', ' topsecret.server.com ']#print (' bytebong.com ' in config) # False#print (' bitbucket.org ' in config) # True#print (config[' bitbucket.org ' ["User"]) # HG#print (config[' DEFAULT ' [' Compression ']) #yes#print (config[' topsecret.server.com ' [' ForwardX11 ']) #no#print (config[' bitbucket.org ') #<section:bitbucket.org>#for key in config[' bitbucket.org ': # Note that there is a key to default defaults#print (key)#Print (config.options (' bitbucket.org ')) # with For loop, find all keys under ' bitbucket.org '#Print (Config.items (' bitbucket.org ')) #找到 all key-value pairs under ' bitbucket.org '#Print (Config.get (' bitbucket.org ', ' compression ')) # Yes Get method section key corresponding value

Three. Logging module

#function    #1. Specification of log Format    #2. Simplification of Operation    #3. Hierarchical management of logs#What logging can't do for you.    #automatically generate the content you want to print#The programmer needs to define itself at the time of development:    #Where to print, what to print, and the level of content#use of the logging module:    #simple, easy-to-customize differential for general configuration    #complex and customizable object configuration#Understanding Log Ratings#Import Logging#logging.debug (' Debug message ') # Debug mode#logging.info (' info message ') # Basic information#logging.warning (' warning message ') # warning#logging.error (' error message ') # error#logging.critical (' critical message ') # Critical Error

  The log information is displayed on the screen

ImportLogginglogging.basicconfig ( level=logging. DEBUG)#If the level=logging is not set. Debug parameters, Debug (debug Info) and info (basic information) are not printed and displayedLogging.debug ('Debug Message')#Debug ModeLogging.info ('Info Message')#Basic InformationLogging.warning ('warning Message')#WarningLogging.error ('error Message')#ErrorLogging.critical ('Critical Message')#Critical Error#DEBUG:root:debug Message#INFO:root:info Message#WARNING:root:warning Message#ERROR:root:error Message#CRITICAL:root:critical Message

The log can also be written in a file, but it cannot be displayed on the screen at the same time

#The log is displayed in the file, the log formatImportLogginglogging.basicconfig ( level=logging. DEBUG, Format='% (asctime) s% (filename) s[line:% (lineno) d]% (levelname) s% (message) s', Datefmt='%a,%d%b%Y%h:%m:%s', filename='Test.log')#filename parameter is the name of the fileLogging.debug ('Debug Message')#Debug ModeLogging.info ('Info Message')#Basic InformationLogging.warning ('warning Message')#WarningLogging.error ('error Message')#ErrorLogging.critical ('Critical Message')#Critical Error

Log configuration parameters:

The logging.basicconfig () function can change the default behavior of the logging module through specific parameters, with the available parameters: FileName: Creates a filedhandler with the specified file name so that the log is stored in the specified files. FileMode: File is opened by using this parameter when filename is specified, and the default value is "a" and can be specified as "W". Format: Specifies the log display format used by handler. DATEFMT: Specifies the date time format. Level: Set Rootlogger (The following explains the specific concept) stream: Create Streamhandler with the specified stream. You can specify output to Sys.stderr,sys.stdout or file (f=open (' Test.log ', ' W ')), default is Sys.stderr. If you list both the filename and stream two parameters, the stream parameter is ignored. formatting strings that may be used in the format parameter:%(name) s Logger's name%(Levelno) s log level in digital form%(levelname) s log level in text form%(pathname) s The full pathname of the module that invokes the log output function, possibly without%(filename) s The file name of the module that invokes the log output function%module Name of the log output function called by (module) s%(funcName) s function name of the call log output function%(Lineno) d The line of code where the statement that invokes the log output function%(created) F current time, represented by the UNIX standard floating-point number representing the time%(relativecreated) d when the log information is output, the number of milliseconds since logger was created% (asctime) s The current time in string form. The default format is "2003-07-08 16:49:45,896". The comma is followed by milliseconds%(thread) d thread ID. Probably not .%(threadname) s thread name. Probably not .%(process) d ID. Probably not .% (message) s user-output message
Configuration Parameters

Logging object operation log File steps

# logger An object to manipulate the log file # Create a Logger object # Create a file management operator # Create a screen management operator # Create a format for the log output # file Management operators bind a format # The screen management operator binds a format # Logger Object binding file management operators # Logger Object Binding screen management operator
ImportLogging#Create a Logger objectLogger =Logging.getlogger ()#Create a file management operatorFH = logging. Filehandler ('Logger.log', encoding='Utf-8')#Create a screen management operatorSH =logging. Streamhandler ()#Create a format for the log outputFORMAT1 = logging. Formatter ('% (asctime) s-% (name) s-% (levelname) s-% (message) s')#file Management operators bind a formatFh.setformatter (FORMAT1)#The screen management operator binds a formatSh.setformatter (FORMAT1) logger.setlevel (logging. DEBUG)#Logger Object binding file management operators#Logger.addhandler (FH)#Logger Object Binding screen management operatorLogger.addhandler (SH) logger.debug ('Debug Message')#Debug ModeLogger.info ('My Information')#Basic InformationLogger.warning ('warning Message')#WarningLogger.error ('error Message')#ErrorLogger.critical ('Critical Message')#Critical Error#2018-08-10 19:35:36,980-root-debug-debug Message#2018-08-10 19:35:36,980-root-info-My Information#2018-08-10 19:35:36,980-root-warning-warning Message#2018-08-10 19:35:36,980-root-error-error Message#2018-08-10 19:35:36,980-root-critical-critical Message

Python module: Hashlib module, configparse module, logging module

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.