My first python web development framework (12) -- tool function Package Description (3), pythonweb

Source: Internet
Author: User

My first python web development framework (12) -- tool function Package Description (3), pythonweb

Mail_helper.py is a mail operation package used to send emails.

1 #! /Usr/bin/evn python 2 # coding = UTF-8 3 4 import smtplib 5 from email. mime. text import MIMEText 6 from traceback import format_exc 7 from config import const 8 9 # initialize mail parameter 10 smtp = const. SMTP11 port = const. PORT12 user = const. EMAIL_USER13 passwd = const. EMAIL_PWD14 email_list = const. EMAIL_LIST15 err_title = const. EMAIL_ERR_TITLE16 17 18 def send_mail (subject, context, to_list): 19 ''' 20 send mail 21 Receiving parameter: 22 subject mail subject 23 context mail content 24 to_list receiver mail list, each email address is separated by "," by 25 ''' 26 if not subject or not context or not to_list: 27 return '. The email fails to be sent, email Subject, content, and recipient email are required. '28 29 # initial email-related parameter 30 email = MIMEText (context, 'html', 'utf-8 ') 31 email ['to'] = to_list32 email ['subobject'] = subject33 email ['from'] = user34 35 # I sent 36 # s = smtplib through ssl. SMTP (smtp) 37 s = smtplib. SMTP_SSL (smtp) 38 try: 39 s. login (user, passwd) 40 s. sendmail (user, email_list, email. as_string () 41 s. close () 42 return None43 failed t Exception as e: 44 s. close () 45 stacktrace = format_exc () 46 return 'failed to send the email. Exception:' + str (e. args) + stacktrace + '\ n' 47 48 49 def send_error_mail (context): 50''' 51 send mail 52 receiving parameters: 53 context email content 54 ''' 55 if not context: 56 return 'the email content is required. '57 58 send_mail (err_title, context, email_list)View Code

The send_mail () function only needs to submit the mail title, content, and recipient list to send the mail. The sender is configured with const. if the corresponding account password is not set in the configuration, the email cannot be sent.

The send_error_mail () function is used to send exception log information. By default, it is called to the exception Logging Function error () in log_helper.py, so that an exception occurs during code execution, we will immediately receive this exception email, and then we can handle it accordingly. Of course, if the server encounters a fault, it may suddenly receive a large number of emails, which are blocked by the email server. Therefore, I usually use my own mailbox to send it to myself. In this case, if an IP address is blocked, I can still receive emails that fail to be sent. In addition, as mentioned earlier, the _ init __. py is a bit different from this file in other folders. You can compare it to solve many basic problems, especially when updating online code, you sometimes forget to submit new python files, this file is called by other files. In this case, an exception occurs during python initialization. In the first time, we will receive a reminder email to avoid failure of online services.

The mail title of the send_error_mail () function can be in const. set in the py configuration (see the following parameters). Generally, I will divide the title into development, test, pre-production, and production. In this way, when we receive the mail, it is convenient to distinguish that the environment is faulty.

### Mail service parameters #### Mail Server SMTP = 'smtp .qq.com '# mail server PORT = 465 # email sending account EMAIL_USER = 'xxxxxx @ qq.com' # email sending Password EMAIL_PWD = 'xxxxxxxxxxxxxxxxxxxxxx' # system exception email notification address, multiple addresses are separated by commas (,). environment, # -- If you differentiate when sending exception notifications, you may not be able to figure out the problem in that environment. # -- you can set the mail title: development, testing, pre-production, production, and other labels are used to differentiate the exception notifications that are sent in that environment. EMAIL_ERR_TITLE = 'System exception notifications-simple-developing'

Test cases:

#! /Usr/bin/evn python # coding = utf-8import unittestfrom common import mail_helper, except_helperclass MailHelperTest (unittest. testCase): "mail operation package test class" def setUp (self): "initialize test environment" print ('------ ini ------') def tearDown (self): "Clean up the test environment" print ('------ clear ------') def test (self): mail_helper.send_mail ('test', 'test', '2017 @ qq.com ') effect_info = effect_helper.detailtrace () mail_helper.send_error_mail ('exception, stack information: '+ effect_info) if _ name _ =' _ main _ ': unittest. main ()

Execution result:

 

Log_helper.py is a log operation package.

1 #! /Usr/bin/evn python 2 # coding = UTF-8 3 4 import logging 5 import logging. handlers 6 import traceback 7 8 from common import mail_helper, effect_helper 9 10 11 def info (content): 12 "record log information" 13 if content: 14 logging.info (content) 15 16 def error (content = '', is_send_mail = True): 17" record error log information "" 18 if traceback: 19 content = content + '\ n' + traceback. format_exc () + '\ n' 20 # obtain the stack information currently running by the Program 21 detailtrace = effect_helper.detailtrace () 22 content = content +: '+ detailtrace +' \ n' 23 24 logging.info (content) 25 26 # send email to relevant personnel 27 if is_send_mail: 28 info = mail_helper.send_error_mail (context = content) 29 if info: logging.info (info)View Code

The info () function is used to record some information during program execution. For example, when communicating with a third-party interface (the most common is the payment Interface), the submitted URL, parameters, and returned results are recorded, it is convenient for us to view and troubleshoot errors as needed. For example, when we need to troubleshoot exceptions in the production environment and locate the error information, add it in the middle of the relevant code, and then record the relevant data variable values, help us locate the problem ......

In addition to the info () function, the error () function records information and automatically sends an email to our mailbox. Put it in try... into t.

#! /Usr/bin/evn python # coding = utf-8import loggingimport osimport unittestfrom common import log_helperclass LogHelperTest (unittest. testCase): "log operation package test class" def setUp (self): "initialize test environment" print ('------ ini ------') # obtain the parent path of the script (because log_helper_text.py is under the test directory, not in the root directory, and we want to record all the logs in the log directory under the directory, so you need to obtain the parent directory of test) program_path = OS. path. abspath (OS. path. dirname (OS. path. dirname (_ file _) # initialize the log directory log_path = OS. path. join (program_path, 'log') # create the log directory if not OS when the log directory does not exist. path. exists (log_path): OS. mkdir (log_path) # define the log output format logging. basicConfig (level = logging. INFO, format = '% (asctime) s % (filename) s [line: % (lineno) d] % (levelname) s % (message) s ', filename = "% s/info. log "% log_path, filemode = 'A') def tearDown (self):" clear test environment "" print ('------ clear ------') def test (self ): log_helper.info ('records or information related to code execution ') try: result = '0'/10 failed t Exception as e: log_helper.error ('exception:' + str (e. args) if _ name _ = '_ main _': unittest. main ()

Execution result:

 

 

Random_helper.py is a random number operation package. Through the functions in it, we can quickly and conveniently obtain the numeric Random Number of the specified size range. The random numbers of the specified length, uppercase/lowercase letters, numbers, and letters are mixed; obtain the random uuid.

1 #! /Usr/bin/evn python 2 # coding = UTF-8 3 4 import random 5 import uuid 6 from common import encrypt_helper 7 8 ### define constants ### 9 # lowercase letters 10 lowercase_letters = "abcdefghijklmnopqrstuvwxyz" 11 # uppercase letter 12 majuscule = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 13 # Number 14 numbers = "0123456789" 15 ################ 16 17 def ___ get_randoms (length, text): 18 "19 internal function, get the specified length of random characters 20: param length: the length of the characters to be generated 21: param text: generate random character pool 22: return: The generated random string 23 "24 return random. sample (text, length) 25 26 def get_number (length): 27 "28 get the number of the specified length, type: String 29: param length: length of the characters to be generated 30: return: The generated random string 31 "32 return ''. join (___ get_randoms (length, numbers) 33 34 def get_number_for_range (small, max): 35 "" 36 get the integer value of the specified size 37: param small: Minimum value 38: param max: maximum value 39: return: generated random value 40 "41 return random. randint (small, max) 42 43 def get_string (length): 44 "" 45 get a string of the specified length (uppercase/lowercase letters + digits) 46: param length: length 47: return: The generated random string 48 "49 return ''. join (___ get_randoms (length, lowercase_letters + majuscule + numbers) 50 51 def get_letters (length): 52 "" 53 generate random English letter strings (uppercase/lowercase English letters) 54: param length: length of the character to be generated 55: return: The generated random string 56 "57 return ''. join (___ get_randoms (length, lowercase_letters + majuscule) 58 59 def get_uuid (): 60 "" 61 randomly generated uuid62: return: uuid63 "64 return str (uuid. uuid4 ()). replace ('-','')View Code

Because it is relatively simple, it is not described one by one. Let's look at the test cases directly.

#! /Usr/bin/evn python # coding = utf-8import unittestfrom common import random_helperclass RandomHelperTest (unittest. testCase): "random number operation package test class" def setUp (self): "initialize test environment" print ('------ ini ------') def tearDown (self): "clear test environment" print ('------ clear ------') def test (self): print ('get a random number between 0 and 100 ') print (random (0,100) print (random_helper.get_number_for_range (0,100) print ('get a 5-digit random Code') print (random_helper.get_number (5) print (random_helper.get_number (5 )) print ('get 6 English random Code') print (random_helper.get_letters (6) print (random_helper.get_letters (6) print ('get 6 numbers and English random Code ') print (random_helper.get_string (6) print (random_helper.get_string (6) print ('get uuid') print (random_helper.get_uuid ()) if _ name _ = '_ main _': unittest. main ()

Execution result:

------ Ini ------ get a random number between 0 and 100 get a random number with a length of 5 random code 5421 get an English random code with a length of 6 BqQCZPybFIaB get a number with a length of 6 and an English random code FZfEgdGAslRy get a random ------ clear ------

 

 

  Download the source code for this article

 

Author: AllEmpty
Source: http://www.cnblogs.com/EmptyFS/
If you are interested, you can add the python development QQ group: 669058475. Let's discuss it together. If you have any questions, you can ask questions in the group. Of course, if I am busy at work, I may not reply in time.

This article is original in AllEmpty. You are welcome to repost it, but you must keep this statement without your consent, and provide the original article connection clearly on the article page. Otherwise, you will be held legally liable.

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.