下面是一个数据库池示例。我不明白以下几点。在
从psycopg2.pool导入SimpleConnectionPool 从contextlib导入contextmanager
dbConnection = "dbname='dbname' user='postgres' host='localhost' password='postgres'"
# pool define with 10 live connections
connectionpool = SimpleConnectionPool(1,10,dsn=dbConnection)
@contextmanager
def getcursor():
con = connectionpool.getconn()
try:
yield con.cursor()
finally:
connectionpool.putconn(con)
def main_work():
try:
# with here will take care of put connection when its done
with getcursor() as cur:
cur.execute("select * from \"TableName\"")
result_set = cur.fetchall()
except Exception as e:
print "error in executing with exception: ", e**
你的两个问题都是相关的。在python中,当您看到
with
语句时,我们使用的就是上下文管理器。经典地说,它们是这样写的。在现在,当您使用上下文管理器时,它将在
^{pr2}$with
语句上调用__enter__
方法,并在退出上下文时调用__exit__
方法。就这样想吧。在@contextmanager
装饰器是一种使创建上下文管理器更容易的糖。基本上,它使用yield
语句将执行返回给调用者。直到并包括yield
语句的所有内容都是__enter__
方法,之后的所有内容都是__exit__
语句。在相关问题 更多 >
编程相关推荐