程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python context manager context manager

編輯:Python

The context manager is with sentence , This is a python Unique statement .

with Often used for file operations ,with After the statement is executed, the opened file is automatically closed , The code is simpler :

with open("myfile.txt", 'r') as file:
pass

among ,open It's a class.

You can also implement custom Context manager , for example , The following database operation code has many repetitions , Whether it's creating , Update or delete , Connect to the database every time , Close the database , To avoid this repetition , You can write the code to be executed each time to a context manager , That is, in a class .

def get_all_books():
connection = sqlite3.connect('data.db')
cursor = connection.cursor()
cursor.execute("SELECT * FROM books")
books = [{
'name': row[0], 'author': row[1], 'read': row[2]} for row in cursor.fetchall()]
connection.close()
return books
def add_book(name, author):
connection = sqlite3.connect('data.db')
cursor = connection.cursor()
cursor.execute(f'INSERT INTO books VALUES(?, ?, 0)', (name, author))
connection.commit()
connection.close()

Implementation of context manager :

import sqlite3
class DatabaseConnection:
def __init__(self, host):
self.connection = None
self.host = host
def __enter__(self):
self.connection = sqlite3.connect(self.host)
return self.connection
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type or exc_val or exc_tb: # in case of any error, close the connection without commit
self.connection.close()
else:
self.connection.commit()
self.connection.close()

The database code can therefore be simplified :

def add_book(name, author):
with DatabaseConnection('data.db') as connection:
cursor = connection.cursor()
cursor.execute(f'INSERT INTO books VALUES(?, ?, 0)', (name, author))
def get_all_books():
with DatabaseConnection('data.db') as connection:
cursor = connection.cursor()
cursor.execute("SELECT * FROM books")
books = [{
'name': row[0], 'author': row[1], 'read': row[2]} for row in cursor.fetchall()]
return books

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved