Python full stack development "11th" Python common Module Three (hashlib,configparser,logging)

Source: Internet
Author: User

Hashlib Module

Hashlib provides common digest algorithms such as MD5 and SHA1, and so on.

So what is a digest algorithm? Abstract algorithm is also called hash algorithm, 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).

Note: The digest algorithm is not a decryption algorithm. (Digest algorithm to detect whether a string has changed)

Apply: 1. Do file verification

2. Login Password

The password cannot be decrypted, but can hit the library, with the ' Add salt ' method can solve the problem of the pool. All you have to do to set the password later is a bit more complicated.

#用户密码import hashlib# md5_obj = HASHLIB.MD5 () not added salt Md5_obj = hashlib.md5 (' Nezha '. Encode (' Utf-8 ')) #加盐后 (Let your password be stronger) md5_ Obj.update (' 123456 '. Encode (' Utf-8 ')) print (Md5_obj.hexdigest ()) md5_obj.update (' Hello '. Encode (' Utf-8 ')) print (MD5 _obj.hexdigest ()) #-----------user = ' Haiyan ' password = ' 123456 ' md5_obj= hashlib.md5 (User.encode (' Utf-8 ')) # Add salt (even if the password is the same as your password, # Then you add salt will only your user name corresponds to your password) md5_obj.update (Password.encode (' Utf-8 ')) print (Md5_obj.hexdigest ())
#文件一致性校验 (detection file changed) import hashlibmd5_obj = Hashlib.md5 () Import osfilesize = os.path.getsize (' filename ')  #文件大小f = Open (' filename ', ' RB ') while filesize>0:    if filesize > 1024x768:        content = F.read (1024x768)        filesize-= 1024    Else:        content = F.read (filesize)        filesize-= filesize    md5_obj.update (content) #     for line in f:# Md5_obj.update (Line.encode (' Utf-8 ')) Md5_obj.hexdigest ()

Configparser 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).

1. Create a file

Import Configparserconfig = Configparser. Configparser () config["DEFAULT"] = {' Serveraliveinterval ': ' A ',                      ' Compression ': ' Yes ',                     ' compressionlevel ': ' 9 ',                     ' ForwardX11 ': ' Yes '                     }config[' bitbuck et.org '] = {' User ': ' Hg '}config[' topsecret.server.com '] = {' Host Port ' ': ' 50022 ', ' ForwardX11 ': ' No '}with open (' Example.ini ', ' W ') as ConfigFile:   config.write (ConfigFile)

2. Find Files

Import Configparserconfig = Configparser. Configparser () # Print (Config.sections ()) config.read (' Example.ini ') print (Config.sections ())  #读出来的是文件里面的组, # and the [DEFAULT] group does not show up print (' bytebong.com ' in config) # falseprint (' bitbucket.org ' in config) # trueprint (config[' Bitbucket.org ' [user]]  # hgprint (config[' DEFAULT ' [' Compression ']) #yesprint (config[' topsecret.server.com ') [' ForwardX11 '])  #noprint (config[' bitbucket.org '))          #<section:bitbucket.org>for key in config[' Bitbucket.org ']:     # Note that there is a default defaults key print (key    ) print (config.options (' bitbucket.org '))  # with For loop , locate all key print under ' bitbucket.org ' (Config.items (' bitbucket.org '))    #找到 ' bitbucket.org ' under all key-value pairs print (Config.get (' Bitbucket.org ', ' compression ')) # Yes       get method section key corresponding value

3. Adding and removing and changing operation

Import Configparserconfig = Configparser. Configparser () config.read (' Example.ini ') config.add_section (' Yuan ') # config.remove_section (' bitbucket.org ') #删除组 # Config.remove_option (' topsecret.server.com ', "forwardx11") #删除组里面的项config. Set (' topsecret.server.com ', ' K1 ', ' 11111 ') config.set (' Yuan ', ' K2 ', ' 22222 ') config.write (open (' New2.ini ', "w"))

Logging module

Functional Simple Configuration

By default, Python's logging module prints the logs to standard output and only displays logs that are greater than or equal to the warning level, indicating that the default logging level is set to warning (log level level critical > ERROR > WARNING > INFO > DEBUG), the default log format is log level: Logger name: User output message.

Displays only basic logs that are greater than or equal to warning, which indicates that the default logging level is set to warning (log level level Critical>error>warning>info>debug) import Logginglogging.debug (' Debug Message ') Logging.info (' info message ') logging.warning (' warning message ')  #warning Warning (from the beginning of the warning) logging.error (' Error message ') #error error logging.critical (' critical message ') #比错误更严重的级别

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 the output to Sys.stderr,sys.stdout or the file (F=open (' Test.log ', ' W ')), and the default is Sys.stderr. If you list both the filename and stream two parameters, the stream parameter is ignored. Formatted string that may be used in the format parameter:% (name) s logger name% (Levelno) s number form log level% (levelname) s text form log level% (pathname) s The full pathname of the module that calls the log output function, The file name of the module that may not have% (filename) s call log output function% (module) s call log output function module name% (funcName) s call log output function name% (Lineno) d Call Log output function The statement that is located in the line% ( Created) F current time, the current time in the number of milliseconds (asctime) s string as a percentage of the time that the UNIX standard represents a floating-point (relativecreated) d output log information, since logger was created. The default format is "2003-07-08 16:49:45,896". The comma is followed by the millisecond% (thread) d thread ID. There may not be a% (threadname) s thread name. There may not be a% (process) d process ID. Messages that may not have a% (message) s user output

There are two ways to apply the logging module

1. Set config

Import Logginglogging.basicconfig (    level=logging. DEBUG,    #多输出一些细节    # level = logging. WARNING  #就不用输出那些细节了    format = '% (name) s% (asctime) s [% (Lineno) d]---% (message) s ', #本身就存在在python语法中, take it.    # level and format also cannot be changed, it is parameter, not variable    #% (lineno) d Specify code block line    #% (name) S Current Admin user    datefmt = '%d/%m/%y%h:%m:%s ' , #指定日期时间格式    filename = ' logging_info ' #自动创建了一个文件 and writes the log to the file) logging.debug (' Debug Message ') Logging.info (' Info Message ') logging.warning (' warning message ') logging.error (' Error message ') logging.critical (' Critical message ')

2.logger Object Configuration

You can control the input to a file, or you can enter it into the screen

Can be output in several files at the same time

# Logger object import loggingdef MyLogger (filename,file=true,stream=true): Logger = Logging.getlogger () Formater = logging.    Formatter (fmt= '% (name) s% (asctime) s [% (Lineno) d]---% (message) s ', datefmt= '%d/%m/%y%h:%m:%s ' # time format) Logger.setlevel (logging. DEBUG) #指定日志打印的等级 If File:file_handler = logging.        Filehandler (' Logging.log ', encoding= ' Utf-8 ') # Create a handler for writing to the log file File_handler.setformatter (formater) # file stream, file operator Logger.addhandler (file_handler) If Stream:stream_handler = logging. Streamhandler () # Creates a handler to output to the console Stream_handler.setformatter (formater) #屏幕流, and the screen operation Flow #如果想让文件流和屏幕流输出的东西的 Format is not the same, then write a format formater1, so you can Logger.addhandler (stream_handler) return Loggerlogger = MyLogger (' Logging.log ', File=false) logger.warning (' Cheerleader ') logger.debug (' Debug message ') 

The Ogging library provides multiple components: Logger, Handler, Filter, Formatter. The Logger object provides an interface that the application can use directly, handler sends logs to the appropriate destination, and filter provides a way to filter the log information formatter specify the log display format. Alternatively, you can pass: logger.setlevel (logging. Debug) Setting levels, of course, can also be

Fh.setlevel (logging. Debug) to set a level on a file stream.

  

Python full stack development "11th" Python common Module Three (hashlib,configparser,logging)

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.