Skip to content

Commit 13cc0ea

Browse files
committed
Add mapper example at root, rename existing example
1 parent cfd8091 commit 13cc0ea

3 files changed

Lines changed: 113 additions & 0 deletions

File tree

cassandra/cqlengine/connection.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,17 +42,24 @@ class CQLConnectionError(CQLEngineException):
4242
def default():
4343
"""
4444
Configures the global mapper connection to localhost, using the driver defaults
45+
(except for row_factory)
4546
"""
4647
global cluster, session
4748
cluster = Cluster()
4849
session = cluster.connect()
50+
session.row_factory = dict_factory
4951

5052

5153
def set_session(s):
5254
"""
5355
Configures the global mapper connection with a preexisting :class:`cassandra.cluster.Session`
56+
57+
Note: the mapper presently requires a Session :attr:`~.row_factory` set to ``dict_factory``.
58+
This may be relaxed in the future
5459
"""
5560
global cluster, session
61+
if s.row_factory is not dict_factory:
62+
raise CQLEngineException("Failed to initialize: 'Session.row_factory' must be 'dict_factory'.")
5663
session = s
5764
cluster = s.cluster
5865

File renamed without changes.

example_mapper.py

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
#!/usr/bin/env python
2+
3+
# Copyright 2013-2015 DataStax, Inc.
4+
#
5+
# Licensed under the Apache License, Version 2.0 (the "License");
6+
# you may not use this file except in compliance with the License.
7+
# You may obtain a copy of the License at
8+
#
9+
# http://www.apache.org/licenses/LICENSE-2.0
10+
#
11+
# Unless required by applicable law or agreed to in writing, software
12+
# distributed under the License is distributed on an "AS IS" BASIS,
13+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
# See the License for the specific language governing permissions and
15+
# limitations under the License.
16+
17+
import logging
18+
19+
log = logging.getLogger()
20+
log.setLevel('DEBUG')
21+
handler = logging.StreamHandler()
22+
handler.setFormatter(logging.Formatter("%(asctime)s [%(levelname)s] %(name)s: %(message)s"))
23+
log.addHandler(handler)
24+
25+
from uuid import uuid4
26+
27+
from cassandra.cqlengine import columns
28+
from cassandra.cqlengine import connection
29+
from cassandra.cqlengine import management
30+
from cassandra.cqlengine.exceptions import ValidationError
31+
from cassandra.cqlengine.models import Model
32+
from cassandra.cqlengine.query import BatchQuery
33+
34+
KEYSPACE = "testkeyspace"
35+
36+
37+
class FamilyMembers(Model):
38+
__keyspace__ = KEYSPACE
39+
id = columns.UUID(primary_key=True, default=uuid4)
40+
surname = columns.Text(primary_key=True)
41+
name = columns.Text(primary_key=True)
42+
birth_year = columns.Integer()
43+
sex = columns.Text(min_length=1, max_length=1)
44+
45+
def validate(self):
46+
super(FamilyMembers, self).validate()
47+
if self.sex and self.sex not in 'mf':
48+
raise ValidationError("FamilyMember.sex must be one of ['m', 'f']")
49+
50+
if self.birth_year and self.sex == 'f':
51+
raise ValidationError("FamilyMember.birth_year is set, and 'a lady never tells'")
52+
53+
54+
def main():
55+
connection.default()
56+
57+
# Management functions would normally be used in development, and possibly for deployments.
58+
# They are typically not part of a core application.
59+
log.info("### creating keyspace...")
60+
management.create_keyspace_simple(KEYSPACE, 1)
61+
log.info("### syncing model...")
62+
management.sync_table(FamilyMembers)
63+
64+
log.info("### add entities serially")
65+
simmons = FamilyMembers.create(surname='Simmons', name='Gene', birth_year=1949, sex='m') # default uuid is assigned
66+
67+
# add members later
68+
FamilyMembers.create(id=simmons.id, surname='Simmons', name='Nick', birth_year=1989, sex='m')
69+
FamilyMembers.create(id=simmons.id, surname='Simmons', name='Sophie', sex='f')
70+
# showing validation
71+
try:
72+
FamilyMembers.create(id=simmons.id, surname='Tweed', name='Shannon', birth_year=1957, sex='f')
73+
except ValidationError:
74+
log.exception('INTENTIONAL VALIDATION EXCEPTION; Failed creating instance:')
75+
FamilyMembers.create(id=simmons.id, surname='Tweed', name='Shannon', sex='f')
76+
77+
log.info("### add multiple as part of a batch")
78+
# If creating many at one time, can use a batch to minimize round-trips
79+
hogan_id = uuid4()
80+
with BatchQuery() as b:
81+
FamilyMembers.batch(b).create(id=hogan_id, surname='Hogan', name='Hulk', sex='m')
82+
FamilyMembers.batch(b).create(id=hogan_id, surname='Hogan', name='Linda', sex='f')
83+
FamilyMembers.batch(b).create(id=hogan_id, surname='Hogan', name='Nick', sex='m')
84+
FamilyMembers.batch(b).create(id=hogan_id, surname='Hogan', name='Brooke', sex='f')
85+
86+
log.info("### All members")
87+
for m in FamilyMembers.all():
88+
print m, m.birth_year, m.sex
89+
90+
log.info("### Select by partition key")
91+
for m in FamilyMembers.objects(id=simmons.id):
92+
print m, m.birth_year, m.sex
93+
94+
log.info("### Constrain on clustering key")
95+
for m in FamilyMembers.objects(id=simmons.id, surname=simmons.surname):
96+
print m, m.birth_year, m.sex
97+
98+
log.info("### Delete a record")
99+
FamilyMembers(id=hogan_id, surname='Hogan', name='Linda').delete()
100+
for m in FamilyMembers.objects(id=hogan_id):
101+
print m, m.birth_year, m.sex
102+
103+
management.drop_keyspace(KEYSPACE)
104+
105+
if __name__ == "__main__":
106+
main()

0 commit comments

Comments
 (0)