Skip to content

Commit d48d42c

Browse files
authored
Merge pull request #243 from caitinggui/master
customize dictionary
2 parents d304225 + d998ee8 commit d48d42c

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

docs/cursors.rst

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -313,6 +313,50 @@ Cursor
313313

314314
loop.run_until_complete(test_example())
315315

316+
You can customize your dictionary, see example::
317+
318+
import asyncio
319+
import aiomysql
320+
321+
class AttrDict(dict):
322+
"""Dict that can get attribute by dot, and doesn't raise KeyError"""
323+
324+
def __getattr__(self, name):
325+
try:
326+
return self[name]
327+
except KeyError:
328+
return None
329+
330+
class AttrDictCursor(aiomysql.DictCursor):
331+
dict_type = AttrDict
332+
333+
loop = asyncio.get_event_loop()
334+
335+
@asyncio.coroutine
336+
def test_example():
337+
conn = yield from aiomysql.connect(host='127.0.0.1', port=3306,
338+
user='root', password='',
339+
db='mysql', loop=loop)
340+
341+
# create your dict cursor
342+
cursor = yield from conn.cursor(AttrDictCursor)
343+
344+
# execute sql query
345+
yield from cursor.execute(
346+
"SELECT * from people where name='bob'")
347+
348+
# fetch all results
349+
r = yield from cursor.fetchone()
350+
print(r)
351+
# {'age': 20, 'DOB': datetime.datetime(1990, 2, 6, 23, 4, 56),
352+
# 'name': 'bob'}
353+
print(r.age)
354+
# 20
355+
print(r.foo)
356+
# None
357+
358+
loop.run_until_complete(test_example())
359+
316360

317361
.. class:: SSCursor
318362

0 commit comments

Comments
 (0)