My first python web development framework (11) -- tool function Package Description (2), pythonweb
Db_helper.py is a database operation package. It has two main functions: read () database read operation function and write () database write operation function. The code of this package was transformed from the blog shared by Dai.
1 #! /Usr/bin/env python 2 # coding = UTF-8 3 4 import psycopg2 5 from common import log_helper 6 from config import const 7 8 # initialize database parameter 9 db_name = const. DB_NAME10 db_host = const. DB_HOST11 db_port = const. DB_PORT12 db_user = const. DB_USER13 db_pass = const. DB_PASS14 15 16 def read (SQL): 17 "18 connect to the PostgreSQL database and perform data query 19. If the connection fails, the error is written to the log and false is returned, if the SQL Execution fails, the error is written to the log and false20 is returned. If all the operations are normal, the queried data is returned. The data is converted to the dictionary format, convenient template calling. The dictionary key is the field name 21 "22 try: 23 # connect to the database 24 conn = psycopg2.connect (database = db_name, user = db_user, password = db_pass, host = db_host, port = db_port) 25 # Get cursor 26 cursor = conn. cursor () 27 failed t Exception as e: 28 print (e. args) 29 log_helper.error ('database Connection Failed: '+ str (e. args) 30 return False31 try: 32 # execute the query operation 33 cursor.exe cute (SQL) 34 # convert the returned results to the dictionary format 35 data = [dict (cursor. description [I] [0], value) for I, value in enumerate (row) for row in cursor. fetchall ()] 36 bytes t Exception as e: 37 print (e. args) 38 log_helper.error ('SQL execution failed:' + str (e. args) + 'SQL:' + str (SQL) 39 return False40 finally: 41 # Close the cursor and database link 42 cursor. close () 43 conn. close () 44 # returned results (Dictionary format) 45 return data46 47 48 def write (SQL, vars ): 49 "50 connect to the PostgreSQL database and perform write operations 51 if the connection fails, the error is written into the log and false is returned. If the SQL Execution fails, the error is also written to the log and false is returned. If all operations are normal, true52 "53 try: 54 # connect to database 55 conn = psycopg2.connect (database = db_name, user = db_user, password = db_pass, host = db_host, port = db_port) 56 # retrieve cursor 57 cursor = conn. cursor () 58 failed t Exception as e: 59 print (e. args) 60 log_helper.error ('database Connection Failed: '+ str (e. args) 61 return False62 try: 63 # Execute SQL statement 64 cursor.exe cute (SQL, vars) 65 # commit transaction 66 conn. commit () 67 failed t Exception as e: 68 print (e. args) 69 # if an error occurs, the transaction rolls back 70 conn. rollback () 71 log_helper.error ('SQL execution failed:' + str (e. args) + 'SQL:' + str (SQL) 72 return False73 else: 74 # Get data 75 try: 76 data = [dict (cursor. description [I] [0], value) for I, value in enumerate (row) 77 for row in cursor. fetchall ()] 78 failed t Exception as e: 79 # When returning is not set or a modify or delete statement is executed, the record does not exist 80 data = None81 finally: 82 # Close the cursor and database link 83 cursor. close () 84 conn. close () 85 86 # if data is written, return the data returned by the database to the caller 87.View Code
Read (SQL) is used to perform database query operations, and there is no transaction commit in it, so when you use it to perform the add, delete, and modify operations, although it can be submitted successfully, however, the database record does not change after execution, so you can only use it to execute the select statement.
Write (SQL, data) is used to perform database write operations. After the write function is executed, the following statuses are returned:
1. False status (this status is returned if the database connection fails, the SQL statement is incorrect, or the database is connected during Operation)
2. none status (the SQL statement does not add the RETURNING id code to specify that the specified field value is returned after the SQL statement is executed. If you modify row 80th of code, data = None is data = True, if the execution is successful, True is returned)
3. [] (the returning function is added to the SQL statement and the record does not exist when modification or deletion is performed)
4. {'id': 1,} (the returning function is added to the SQL statement. After successful execution, the specified field value is returned)
PS: when executing the add operation, if you want to obtain the newly added id, postgresql has a very useful function returning. You only need to add the returning id or returning id after the addition, deletion, and modification statements, name or returning * when you want to return the field name, the specified field values will be returned after the statement is executed successfully. You can try to modify the test case code to see what the returned value is.
#! /Usr/bin/evn python # coding = utf-8import unittestfrom common import db_helperclass DbHelperTest (unittest. testCase): "database operation package test class" def setUp (self): "initialize test environment" print ('------ ini ------') def tearDown (self): "clear test environment" print ('------ clear ------') def test (self): # Add record, SQL = "INSERT INTO product_class (name, is_enable) VALUES (% s, % s)" data = ('conf', 1) without the return Parameter) result = db_helper.write (SQL, data) print (result) # Add a record. Use the return parameter to return the new id SQL = "" INSERT INTO product_class (name, is_enable) VALUES (% s, % s) RETURNING id; "" data = ('biscuit ', 1) result = db_helper.write (SQL, data) print (result) # modify the SQL = "UPDATE product_class SET name = % s, is_enable = % s WHERE id = 10000 RETURNING id;" "data = ('cid ', 1) result = db_helper.write (SQL, data) print (result) # query record SQL = "SELECT * FROM product_class" result = db_helper.read (SQL) print (result) if _ name _ = '_ main _': unittest. main ()
Execution result
------ Ini ------ None [{'id': 2}] [] [{'id': 1, 'name': 'candy ', 'add _ time': datetime. datetime (2017, 10, 16, 14, 51, 49), 'is _ enable': 1}, {'id': 2, 'name': 'biscuit ', 'Add _ time': datetime. datetime (2017, 10, 16, 15, 30, 50), 'is _ enable': 1}] ------ clear ------
Encrypt_helper.py is an encryption operation package. Currently, only md5 encryption functions are available. Other encryption functions need to be added later.
#! /Usr/bin/evn python # coding = utf-8import hashlibdef md5 (text): "md5 encryption function" md5 = hashlib. md5 () if not isinstance (text, bytes): text = str (text ). encode ('utf-8') md5.update (text) return md5.hexdigest ()
The md5 () parameter type supports various types. If the parameter is not of the bytes type, it is automatically converted to the str type for operation. For example, in the following test case, you can also test the results using tuples, dictionaries, or list types.
#! /Usr/bin/evn python # coding = utf-8import unittestfrom common import encrypt_helperclass DbHelperTest (unittest. testCase): "database operation package test class" def setUp (self): "initialize test environment" print ('------ ini ------') def tearDown (self): "clear test environment" print ('------ clear ------') def test (self): result = encrypt_helper.md5 (1) print (result) self. assertEqual (result, 'c4ca4238a0b923820dcc509a6f75849b ') result = encrypt_helper.md5 ('1') print (result) self. assertEqual (result, 'c4ca4238a0b923820dcc509a6f75849b ') result = encrypt_helper.md5 (B '1') print (result) self. assertEqual (result, 'c4ca4238a0b923820dcc509a6f75849b ') if _ name _ =' _ main _ ': unittest. main ()
Execution result
------ini------c4ca4238a0b923820dcc509a6f75849bc4ca4238a0b923820dcc509a6f75849bc4ca4238a0b923820dcc509a6f75849b------clear------
The main function of the effect_helper.py package is to obtain the stack information of the current position of the Code. It is called by the error () error log of the log_helper.py package and outputs the stack information content when an error occurs, this helps developers analyze code exceptions.
#! /Usr/bin/evn python # coding = utf-8import osimport sysdef detailtrace (): "Get the stack information that the program is currently running" retStr = "" f = sys. _ getframe () f = f. f_back # first frame is detailtrace, ignore it while hasattr (f, "f_code"): co = f. f_code retStr = "% s (% s: % s)->" % (OS. path. basename (co. co_filename), co. co_name, f. f_lineno) + retStr f = f. f_back return retStr
The json_helper.py package contains only one date formatting class.
#!/usr/bin/evn python# coding=utf-8import jsonimport datetimeclass CJsonEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, datetime.datetime): return obj.strftime('%Y-%m-%d %H:%M:%S') elif isinstance(obj, datetime.date): return obj.strftime('%Y-%m-%d') else: return json.JSONEncoder.default(self, obj)
When python json converts the time type to a string, it cannot handle the exception. You need to use this custom class for formatting.
For example, if we convert the time type in this way, an exception occurs:
def test(self): js = { 'test5': datetime.datetime.now(), } print(js) result = json.dumps(js) print(result)
Execution result:
------ini------{'test5': datetime.datetime(2017, 10, 16, 16, 56, 58, 654832)}------clear------ErrorTraceback (most recent call last): File "E:\Python\simple\code\test\json_helper_test.py", line 26, in test result = json.dumps(js) File "C:\Users\Empty\AppData\Local\Programs\Python\Python35-32\lib\json\__init__.py", line 230, in dumps return _default_encoder.encode(obj) File "C:\Users\Empty\AppData\Local\Programs\Python\Python35-32\lib\json\encoder.py", line 198, in encode chunks = self.iterencode(o, _one_shot=True) File "C:\Users\Empty\AppData\Local\Programs\Python\Python35-32\lib\json\encoder.py", line 256, in iterencode return _iterencode(o, 0) File "C:\Users\Empty\AppData\Local\Programs\Python\Python35-32\lib\json\encoder.py", line 179, in default raise TypeError(repr(o) + " is not JSON serializable")TypeError: datetime.datetime(2017, 10, 16, 16, 56, 58, 654832) is not JSON serializable
The code below is normal.
def test(self): js = { 'test5': datetime.datetime.now(), } print(js) result = json.dumps(js, cls=json_helper.CJsonEncoder) print(result)
Execution result
------ini------{'test5': datetime.datetime(2017, 10, 16, 16, 59, 40, 756103)}{"test5": "2017-10-16 16:59:40"}------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.