-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsqlalchemy-ext-query.py
55 lines (41 loc) · 1.28 KB
/
sqlalchemy-ext-query.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# coding: utf-8
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
def conntodb():
dbconnurl = ('mysql+pymysql://{user}:{passwd}@{host}:{port}'
'/{db}?charset=utf8&connect_timeout=10').format(
user = 'root',
passwd = '******',
host = '127.0.0.1',
port = 3306,
db = 'testtable'
)
engine = create_engine(dbconnurl)
DBSession = sessionmaker(bind=engine)
return DBSession()
dbsession = conntodb()
class ConnectToDB(object):
def __init__(self):
self.session = dbsession
def __enter__(self):
return self.session
def __exit__(self, exc_type, exc_value, exc_tb):
self.session.close()
class _QueryProperty(object):
def __init__(self, func):
self.func = func
def __get__(self, obj, cls):
with ConnectToDB() as session:
return self.func(cls, session)
class TableModelExt(object):
@_QueryProperty
def query(cls, session):
return session.query(cls)
def save(self):
with ConnectToDB() as session:
session.add(self)
session.commit()
def delete(self):
with ConnectToDB() as session:
session.delete(self)
session.commit()