Skip to content

Commit 00ab43a

Browse files
committed
[fea] access to fields via getattr
1 parent 84a4ed5 commit 00ab43a

File tree

2 files changed

+49
-2
lines changed

2 files changed

+49
-2
lines changed

mytor/cursor.py

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -103,10 +103,30 @@ def scroll(self, value, mode='relative'):
103103
return async_call_method(self._cursor.scroll, value, mode)
104104

105105

106-
setattr(OriginSSCursor, "__tormysql_class__", SSCursor)
106+
107+
class DBRow(object):
108+
__slots__ = ['__row']
109+
110+
def __init__(self, *args, **kwargs):
111+
self.__row = dict(*args, **kwargs)
112+
113+
def __getattr__(self, item):
114+
return self.__row[item]
115+
116+
def __getitem__(self, item):
117+
return self.__row[item]
118+
119+
def __contains__(self, item):
120+
return item in self.__row
121+
122+
def __repr__(self):
123+
return "Row({0})".format(", ".join("{0}={1!r}".format(k, v) for k, v in self.__row.items()))
124+
125+
def __str__(self):
126+
return self.__repr__()
107127

108128

109129
class SSDictCursor(SSCursor):
110130
__delegate_class__ = OriginSSDictCursor
111131

112-
setattr(OriginSSDictCursor, "__tormysql_class__", SSDictCursor)
132+
DictCursorMixin.dict_type = DBRow

tests/test_with_with.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
#!/usr/bin/env python
22
# encoding: utf-8
3+
import os
34
from tornado.testing import gen_test
5+
from mytor.cursor import SSDictCursor
46
from . import BaseTestCase
57

68

@@ -13,3 +15,28 @@ def test1(self):
1315
yield cursor.execute(sql)
1416
datas = cursor.fetchall()
1517
print (datas)
18+
19+
20+
class TestAsyncCursor(BaseTestCase):
21+
PARAMS = dict(
22+
host=os.getenv("MYSQL_HOST", "127.0.0.1"),
23+
user=os.getenv("MYSQL_USER", "root"),
24+
passwd=os.getenv("MYSQL_PASSWD", ""),
25+
db=os.getenv("MYSQL_DB", "mysql"),
26+
charset=os.getenv("MYSQL_CHARSET", "utf8"),
27+
no_delay=True,
28+
sql_mode="REAL_AS_FLOAT",
29+
init_command="SET max_join_size=DEFAULT",
30+
cursorclass=SSDictCursor
31+
)
32+
33+
@gen_test
34+
def test1(self):
35+
sql = "select 1 as test"
36+
with (yield self.pool.Connection()) as connection:
37+
with connection.cursor() as cursor:
38+
yield cursor.execute(sql)
39+
result = yield cursor.fetchone()
40+
self.assertIn('test', result)
41+
self.assertEqual(result['test'], 1)
42+
self.assertEqual(result.test, 1)

0 commit comments

Comments
 (0)