Browse Source

restart db conn if necessary

David 9 năm trước cách đây
mục cha
commit
f56ed1e6ab
1 tập tin đã thay đổi với 20 bổ sung7 xóa
  1. 20 7
      back/db.py

+ 20 - 7
back/db.py

@@ -4,6 +4,19 @@ class db():
 	DB = "EBA_STOCK"
 	USER = "root"
 	PASSWORD = "howdoiturnthison"
+
+	def get_cursor(self):
+		if not self.conn.open:
+			self.connect()
+		
+		try:
+			cur = self.conn.cursor()
+		except:
+			self.connect()
+			cur = self.conn.cursor()
+
+		return cur
+
 	def connect(self):
 		self.conn = pymysql.connect(unix_socket='/var/run/mysqld/mysqld.sock', user=db.USER, passwd=db.PASSWORD, db=db.DB,cursorclass=pymysql.cursors.DictCursor)
 
@@ -11,7 +24,7 @@ class db():
 		self.connect()
 
 	def client(self, _hash):
-		cur = self.conn.cursor()
+		cur = self.get_cursor()
 		cur.execute("SELECT id,nombre,apellido,hash FROM clientes where hash=%s", (_hash,))
 		res = cur.fetchall()
 		if len(res) == 0:
@@ -20,7 +33,7 @@ class db():
 	
 
 	def get_pedido(self, clientid, pedidoid):
-		cur = self.conn.cursor()
+		cur = self.get_cursor()
 		cur.execute( "SELECT id, cant_productos, subtotal, fecha, estado FROM pedidos where cliente = %s and id = %s", (int(clientid),pedidoid) )
 		pedido = cur.fetchone()
 		pedido["fecha"] = pedido["fecha"].isoformat() #strftime("%Y-%m-%d %H:%M")
@@ -40,7 +53,7 @@ class db():
 
 	def pedidos(self, clientid):
 		ret=[]
-		cur = self.conn.cursor()
+		cur = self.get_cursor()
 		cur.execute( "SELECT id, cant_productos, subtotal, fecha, estado FROM pedidos where cliente = %s", (int(clientid),) )
 		for row in cur.fetchall():
 			row["fecha"] = row["fecha"].isoformat() #strftime("%Y-%m-%d %H:%M")
@@ -51,7 +64,7 @@ class db():
 	def products(self, _id=None):
 		ret=[]
 		if _id is None:
-			cur = self.conn.cursor()
+			cur = self.get_cursor()
 			cur.execute("SELECT id,nombre,precio FROM productos where id between 1000 and 2999")
 			for row in cur.fetchall():
 				row["cantidad"]=0
@@ -63,7 +76,7 @@ class db():
 
 	def update_pedido(self, productos, _hash, id_pedido):
 		clienteID = int(self.client(_hash)["id"])
-		cur = self.conn.cursor()
+		cur = self.get_cursor()
 
 		cur.execute( "SELECT 1 FROM pedidos where id = %s and cliente = %s", (id_pedido, clienteID) )
 		if not cur.fetchone():
@@ -83,7 +96,7 @@ class db():
 	def create_pedido(self, productos, _hash):
 		clienteID = int(self.client(_hash)["id"])
 
-		cur = self.conn.cursor()
+		cur = self.get_cursor()
 		subtotal = sum([ p["precio"]*p["cantidad"] for p in productos])
 		params = ( clienteID, sum([ p["cantidad"] for p in productos]), subtotal )
 
@@ -96,6 +109,6 @@ class db():
 	
 	def confirm(self, _hash, _id):
 		c = self.client(_hash)
-		cur = self.conn.cursor()
+		cur = self.get_cursor()
 		cur.execute("UPDATE pedidos set estado = 'CONFIRMADO', fecha=NOW() where id = %s and cliente = %s and estado = 'CREADO'", (_id,c["id"]))
 		self.conn.commit()