The so-called context manager is a class that rewrites the "enter" method and the "exit" method in a class.
We can simplify some operations through the with statement in combination with the context manager.
Use with statement and custom context manager to complete the corresponding operation of the database. The code is as follows:
# 1. Import module import pymysql # Create a custom context manager object class MyDatabase(object): # Receive parameters and create database connection objects def __init__(self, host, port, user, passwd, database): self.__db = pymysql.Connection(host, port, user, passwd, database, charset='utf8') # Return database connection object def __enter__(self): return self.__db # Close database connection def __exit__(self, exc_type, exc_val, exc_tb): self.__db.close() def main(): # use with Keyword receive enter Object returned to db with MyDatabase('localhost', 3306, 'root', 'mysql', 'JDDB') as db: # utilize db Create cursor cur = db.cursor() sql = '''select * from %s''' cur.execute(sql, (goods,)) result = cur.fetchall() for i in result: print(i) # Close cursor cur.close() # Program entry if __name__ == '__main__': main()
Code flow of context manager class:
1. Write "init" method to receive parameters and create database connection object;
2. Rewrite the enter method to return the database connection object;
3. Rewrite the exit method to close the database connection;
with statement code flow:
1. When the statement to create an object is put into the with statement, the object will not be created, but will accept the object returned by the enter method and give an alias to the object;
2. Create a cursor by using the received object, i.e. database connection object;
3. Write SQL statement and execute SQL statement through cursor;
4. Get the query result of SQL statement and display it;
5. Close the cursor;
6. When the code in the with statement is completed, execute the exit method automatically to close the database connection.
Note: with mydatabase() as DB -- > DB = mydatabase(). Enter
Use with with and custom context class to realize HTTP server:
# 1.Import socket Modular import socket class MySocket(object): # 2.to write init Method reception port parameter def __init__(self, port): self.__port = port # 3.Establish socket object self.__sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 4.to write enter Method returns the socket object def __enter__(self): # Set up port multiplexing self.__sk.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True) # Bind port self.__sk.bind(self.__port) # Set port listening self.__sk.listen(128) # Return socket object return self.__sk # 5.to write exit Method to close the socket object def __exit__(self, exc_type, exc_val, exc_tb): self.__sk.close() def main(): # use with Key and accept the socket object returned to sk with MySocket(8000) as sk: # Waiting for client connection clicent, ip_port = sk.accept() recv_data = clicent.recv(1024) print(recv_data.decode('utf-8')) # to write HTTP response message http_line = 'HTTP/1.1 GET 200 OK\r\n' http_header = 'Server PWS/1.0\r\n' http_body = 'Welcome to index!\r\n' send_data = (http_line + http_header + '\r\n' + http_body).encode('utf-8') clicent.send(send_data) # Close client connection clicent.close() # Programming entry if __name__ == '__main__': main()
Code interpretation of the custom context manager class:
1. Write the init method to receive parameters and create socket object;
2. Write "enter" method, use socket object to set port reuse, bind port, set listening, and then return socket object;
3. Write the exit method to close the socket object.
with statement code interpretation:
1. Receive the socket object returned by the enter and set up an alias,
2. Wait for the client to connect by returning the socket object,
3. A new socket and IP port number will be returned after the receiving client successfully connects,
4. Use client socket to send HTTP response message
5. Close client connection
6. When the code in the with statement is executed, execute the exit method automatically to close the server connection