balance-application/service/balance_service.py

114 lines
2 KiB
Python
Raw Normal View History

2024-09-10 04:14:09 +00:00
import psycopg2
from pydantic import BaseModel
from util.config import conn_param
class Balance(BaseModel):
name: str
date: int
price: int
2024-09-10 07:36:03 +00:00
buy: bool = True
2024-09-10 04:14:09 +00:00
memo: str = ""
class UpdateForm(BaseModel):
name: str = ""
date: int = 0
price: int = 0
2024-09-10 07:36:03 +00:00
buy: bool = True
2024-09-10 04:14:09 +00:00
memo: str = ""
class BalanceService:
def __init__(self):
self._conn = psycopg2.connect(conn_param)
2024-09-10 08:59:43 +00:00
def create(self, username: str, balance: Balance):
2024-09-10 05:20:11 +00:00
ok = True
2024-09-10 04:14:09 +00:00
cur = self._conn.cursor()
2024-09-10 05:20:11 +00:00
try:
cur.execute(
2024-09-10 08:59:43 +00:00
"insert into balset(name, uid, date, price, buy, memo) values (%s, %s, %s, %s, %s, %s);",
(balance.name, username, balance.date, balance.price, balance.buy, balance.memo)
2024-09-10 05:20:11 +00:00
)
2024-09-10 04:14:09 +00:00
2024-09-10 05:20:11 +00:00
self._conn.commit()
except:
self._conn.rollback()
ok = False
finally:
cur.close()
self._conn.close()
2024-09-10 04:14:09 +00:00
2024-09-10 05:20:11 +00:00
return ok
2024-09-10 04:14:09 +00:00
2024-09-10 08:59:43 +00:00
def query(self):
cur = self._conn.cursor()
cur.execute("select * from balset;")
raw = cur.fetchall()
data = []
if len(raw) == 0:
return None
for d in raw:
data.append({
"id": d[0],
"name": d[1],
"date": d[2],
"price": d[3],
"buy": d[4],
"memo": d[5]
})
return data
2024-09-10 04:14:09 +00:00
def read(self, id: int):
cur = self._conn.cursor()
cur.execute("select * from balset where id = %s;", (id))
data = cur.fetchone()
if data == None:
2024-09-10 07:36:03 +00:00
return None
2024-09-10 04:14:09 +00:00
cur.close()
self._conn.close()
return {
"id": data[0],
"name": data[1],
"date": data[2],
"price": data[3],
2024-09-10 07:36:03 +00:00
"buy": data[4],
"memo": data[5]
2024-09-10 04:14:09 +00:00
}
def update(self, id: int, act: str, balance: UpdateForm):
2024-09-10 05:20:11 +00:00
ok = True
2024-09-10 04:14:09 +00:00
cur = self._conn.cursor()
2024-09-10 05:20:11 +00:00
try:
cur.execute(f"update balset set {act} = %s where id = %s;", (balance[act], id))
self._conn.commit()
except:
self._conn.rollback()
ok = False
finally:
cur.close()
self._conn.close()
2024-09-10 04:14:09 +00:00
2024-09-10 05:20:11 +00:00
return ok
2024-09-10 04:14:09 +00:00
def delete(self, id: int):
2024-09-10 05:20:11 +00:00
ok = True
2024-09-10 04:14:09 +00:00
cur = self._conn.cursor()
2024-09-10 05:20:11 +00:00
try:
cur.execute("delete from balset where id = %s;", (id))
self._conn.commit()
except:
self._conn.rollback()
ok = False
finally:
cur.close()
self._conn.close()
return ok