class Term(DyBase): __tablename__ = 'term' __metadata__ = { 'throughput': { 'read': 1, 'write': 1, }, 'global_indexes': [ GlobalIndex.all('ts-index', 'group_id').throughput(read=1, write=1), ], } group_id = Field(data_type=STRING, nullable=False) name = Field(data_type=STRING, nullable=False) start_date = Field(data_type=NUMBER, nullable=False) end_date = Field(data_type=NUMBER, nullable=False) family_spread = Field(data_type=STRING, nullable=False) # New instance instantiation procedure def __init__(self, group_id, name, start_dt, end_dt, family_spread): super(Term, self).__init__() self.group_id = group_id self.name = name self.start_date =start_dt self.end_date = end_dt self.family_spread = family_spread def __repr__(self): return '<term name %r>' % (self.name)
class ReferralRequest(Model): """ Token exclusivo de compartilhamento """ user_id = Field(data_type=str, range_key=True) id = Field(data_type=str, hash_key=True, nullable=False) created_at = Field(data_type=datetime, index='create-index') updated_at = Field(data_type=datetime, nullable=True)
class RefreshToken(Model): u""" refresh token """ EXPIRES_IN_ = 3600 * 24 * 365 # 1 year token = Field(data_type=unicode, hash_key=True) expires_at = Field(data_type=datetime.datetime) client_session_id = Field(data_type='identity')
class Rule(DyBase): __tablename__ = 'rule' __metadata__ = { 'throughput': { 'read': 1, 'write': 1, }, 'global_indexes': [ GlobalIndex.all('ts-index', 'group_id', 'term_id').throughput(read=1, write=1), ], } # Identification Data: email & password group_id = Field(data_type=STRING, nullable=False) term_id = Field(data_type=STRING, nullable=False) definition = Field(data_type=STRING, nullable=False) # New instance instantiation procedure def __init__(self, group_id, term_id, definition): super(Rule, self).__init__() self.group_id = group_id self.term_id = term_id self.definition = definition def __repr__(self): return '<group %r>' % (self.group_id)
class Children(DyBase): __tablename__ = 'term_children' __metadata__ = { 'throughput': { 'read': 1, 'write': 1, }, 'global_indexes': [ GlobalIndex.all('ts-index', 'term_id').throughput(read=1, write=1), ], } term_id = Field(data_type=STRING, nullable=False) child_count = Field(data_type=NUMBER, nullable=False) # New instance instantiation procedure def __init__(self, term_id, child_count): super(Children, self).__init__() self.term_id = term_id self.child_count = child_count def __repr__(self): return '<term id %r>' % (self.term_id)
class Invite(DyBase): __tablename__ = 'invite' __metadata__ = { 'throughput': { 'read': 1, 'write': 1, }, 'global_indexes': [ GlobalIndex.all('ts-index', 'group_id').throughput(read=1, write=1), ], } email = Field(data_type=STRING, nullable=False) group_id = Field(data_type=STRING, nullable=False) invite_token = Field(data_type=STRING, nullable=True) # New instance instantiation procedure def __init__(self, email, group_id, invite_token): super(Invite, self).__init__() self.email = email self.group_id = group_id self.invite_token = invite_token def __repr__(self): return '<Email %r>' % (self.email)
class Company(EntityMixin, Model): """ A company has a name. """ id = Field(hash_key=True) name = Field()
def test_int_no_data_loss(self): """ Int fields refuse to drop floating point data """ field = Field(data_type=int, coerce=True) with self.assertRaises(ValueError): field.coerce(4.5) with self.assertRaises(ValueError): field.coerce(Decimal('4.5'))
class Group(DyBase): __tablename__ = 'group' __metadata__ = { 'throughput': { 'read': 1, 'write': 1, }, 'global_indexes': [ GlobalIndex.all('ts-index', 'domain').throughput(read=1, write=1), ], } # Identification Data: email & password name = Field(data_type=STRING) type_id = Field(data_type=NUMBER) domain = Field(data_type=STRING) default_term_id = Field(data_type=STRING, nullable=True) # New instance instantiation procedure def __init__(self, name, type_id, domain): super(Group, self).__init__() self.name = name self.type_id = type_id self.domain = domain def __repr__(self): return '<Group %r>' % (self.name) def __getitem__(self, key): return self.id
class EmailNotify(DyBase): __tablename__ = 'email_notify' __metadata__ = { 'throughput': { 'read': 1, 'write': 1, }, 'global_indexes': [ GlobalIndex.all('ts-index', 'email', 'date_created').throughput(read=1, write=1), ], } # Identification Data: email & password email = Field(data_type=STRING, nullable=False) type = Field(data_type=STRING, nullable=False) # New instance instantiation procedure def __init__(self, email, type): super(EmailNotify, self).__init__() self.email = email self.type = type def __repr__(self): return '<email %r>' % (self.email)
class Widget(Model): """ Test model for ordering """ id = Field(hash_key=True) name = Field(range_key=True) alpha = Field(data_type=int, index='alpha-index') beta = Field(data_type=int, index='beta-index')
class Member(DyBase): __tablename__ = 'group_member' __metadata__ = { 'throughput': { 'read': 1, 'write': 1, }, 'global_indexes': [ GlobalIndex.all('ts-index', 'group_id').throughput(read=1, write=1), ], } group_id = Field(data_type=STRING, nullable=False) user_id = Field(data_type=NUMBER, nullable=False) # New instance instantiation procedure def __init__(self, group_id, user_id): super(Member, self).__init__() self.group_id = group_id self.user_id = user_id def __repr__(self): return '<User_id %r>' % (self.user_id)
class PublicHoliday(DyBase): __tablename__ = 'public_holiday' __metadata__ = { 'throughput': { 'read': 1, 'write': 1, }, 'global_indexes': [ GlobalIndex.all('ts-index', 'group_id').throughput(read=1, write=1), ], } created_by_id = Field(data_type=STRING, nullable=False) group_id = Field(data_type=STRING, nullable=False) holiday_date = Field(data_type=NUMBER, nullable=False) # full day or half day is_halfday = Field(data_type=NUMBER, nullable=False) # New instance instantiation procedure def __init__(self, created_by_id, group_id, date, is_halfday): super(PublicHoliday, self).__init__() self.created_by_id = created_by_id self.group_id = group_id self.holiday_date = date self.is_halfday = is_halfday def __repr__(self): return '<Date %r>' % (str(self.holiday_date)) def __getitem__(self, key): return self.holiday_date
class PackageSummary(Model): """ Aggregate data about packages """ name = Field(hash_key=True) stable = Field() unstable = Field() last_modified = Field(data_type=datetime) def __init__(self, package): super(PackageSummary, self).__init__(package.name) self.unstable = package.version if not package.is_prerelease: self.stable = package.version self.last_modified = package.last_modified.replace(tzinfo=UTC) def update_with(self, package): """ Update summary with a package """ if self.name != package.name: LOG.error("Summary name '%s' doesn't match package name '%s'", self.name, package.name) return self.unstable = max(self.unstable, package.version, key=parse_version) self.last_modified = max(self.last_modified.replace(tzinfo=UTC), package.last_modified.replace(tzinfo=UTC)) if not package.is_prerelease: if self.stable is None: self.stable = package.version else: self.stable = max(self.stable, package.version, key=parse_version)
class Article(Model): """ Super simple test model """ title = Field(hash_key=True) text = Field() views = Field(data_type=int) def __init__(self, title='Drugs win Drug War', **kwargs): super(Article, self).__init__(title, **kwargs)
class Employee(EntityMixin, Model): """ A employee has a name and associated company. """ company_id = Field(hash_key=True) id = Field(range_key=True) name = Field()
def test_coerce_boto_s3key(self): """ Coerce boto key to S3 key """ field = Field(data_type=S3Type('mybucket')) boto_key = boto.s3.key.Key() boto_key.key = 'my/path' ret = field.coerce(boto_key) self.assertTrue(isinstance(ret, Key)) self.assertEqual(ret.key, 'my/path')
class UserRequest(Model): """ Tentativas de acertos """ id = Field(data_type=str, range_key=True) user_id = Field(data_type=str, hash_key=True, nullable=False) sequence = Field(data_type=str, index='sequence-index') game_level = Field(data_type=str, index='level-index') created_at = Field(data_type=datetime, index='create-index')
class VillageModel(EntityModel): u""" 村のモデル Repository から永続データを取得すると、そこに紐付いている 住人が自動的に _residents に付与される。 """ DAYTIME_LENGTH = 10 # 10 sec name = Field(data_type=unicode) status = Field(data_type='VillageStatus') generation = Field(data_type=int) day = Field(data_type=int) def __init__(self, *args, **kwargs): _kwargs = dict( status=VillageStatus.OUT_GAME, generation=1, day=1, ) _kwargs.update(kwargs) super(VillageModel, self).__init__(*args, **_kwargs) def get_resident(self, user): try: return get_game_repository('resident').get_by_village_and_user( self.identity, self.generation, user.identity) except ValueError as e: logger.info("resident repository error: {}".format(e)) return None def in_game(self): return self.status is VillageStatus.IN_GAME def is_resident(self, user): return self.get_resident(user) is not None def get_residents(self, role=None): return get_game_repository('resident').find(village_id=self.identity, generation=self.generation, role=role) def get_alive_residents(self, role=None): return get_game_repository('resident').find( village_id=self.identity, generation=self.generation, status=ResidentStatus.ALIVE, role=role) def to_dict(self): return dict( identity=self.identity.hex, name=self.name, status=self.status.name, day=self.day, # start_at=self.start_at, # end_at=self.end_at, created=self.created, modified=self.modified)
class OldDict(Model): """ Model that uses an old-style json field as a dict store """ __metadata__ = { '_name': 'dict-test', } id = Field(hash_key=True) data = Field(data_type=JsonType())
class DynamoPasswordResetToken(Model): """ Token used to verify a user's password reset request """ def __init__(self, user_id, reset_code): self.user_id = user_id self.reset_code = reset_code super().__init__() user_id = Field(type=NUMBER, range_key=True) reset_code = Field(type=STRING, hash_key=True)
class Tips(Model): """ Discas dos jogos """ game_level = Field(data_type=str, hash_key=True, nullable=False) tip = Field(data_type=str, default="") created_at = Field(data_type=datetime, range_key=True) updated_at = Field(data_type=datetime, index='updated-index', nullable=True) published_at = Field(data_type=datetime, index='publish-index')
class PackageSummary(Model): """ Aggregate data about packages """ name = Field(hash_key=True) summary = Field() last_modified = Field(data_type=datetime) def __init__(self, package): super(PackageSummary, self).__init__(package.name) self.last_modified = package.last_modified.replace(tzinfo=UTC) self.summary = package.summary
class Post(Model): """ Test model with composite fields """ __metadata__ = { 'global_indexes': [ GlobalIndex('score-index', 'c_all', 'score'), ] } hkey = Composite('userid', 'id', hash_key=True) userid = Field() id = Field() c_all = Composite('userid', 'id', 'about', 'text') score = Composite('likes', 'ts', 'deleted', data_type=NUMBER, merge=lambda x, y, z: None if z else x + y) likes = Field(data_type=int, default=0) ts = Field(data_type=float, default=0) deleted = Field(data_type=bool, default=False) points = Field(data_type=Decimal, default=Decimal('0')) about = Field() text = Field() tags = Field(data_type=set) keywords = Composite('text', 'about', data_type=set, merge=lambda t, a: t.split() + a.split(), coerce=True) def __init__(self, userid, id, ts, text='foo', about='bar'): super(Post, self).__init__(userid=userid, id=id, ts=ts, text=text, about=about)
class Minion_Brand(Model): brandId = Field(data_type=NUMBER, hash_key=True) brandName = Field(data_type=STRING) brandCategory = Field(data_type=STRING) def __init__(self, brandId, brandName, brandCategory): super(Minion_Brand, self).__init__() self.brandId = brandId self.brandName = brandName self.brandCategory = brandCategory
class Message(Model): id = Field(data_type=STRING, hash_key=True) total_parts = Field(data_type=NUMBER) parts = Field(data_type=ListType) message_sent = Field(data_type=NUMBER) def __init__(self, id, total_parts): super(Message, self).__init__() self.id = id self.parts = [None] * int(total_parts) self.message_sent = 0
class DynamoPackage(Package, Model): """ Python package stored in DynamoDB """ __metadata__ = { 'global_indexes': [ GlobalIndex('name-index', 'name'), ], } filename = Field(hash_key=True) name = Field() version = Field() last_modified = Field(data_type=datetime) data = Field(data_type=dict)
class User(Model): """ Model for testing queries """ __metadata__ = { 'global_indexes': [ GlobalIndex('name-index', 'name', 'score'), ], } id = Field(hash_key=True) name = Field(range_key=True) score = Field(data_type=NUMBER, index='score-index', default=0) str_set = Field(data_type=STRING_SET)
class DyBase(Model): __abstract__ = True id = Field(data_type=STRING, hash_key=True) date_created = Field(data_type=NUMBER) date_modified = Field(data_type=NUMBER) def __init__(self): self.id = str(uuid.uuid4()) self.date_created = int(time.time()) self.date_modified = int(time.time())
class UserCredential(Model): u""" user credential model """ user_id = Field(data_type='identity', hash_key=True) credential_type = Field(data_type='CredentialType', index='credentail-type-index') key = Field(data_type=str) secret = Field(data_type=str) created = Field(data_type=datetime.datetime, range_key=True) def __init__(self, *args, **kwargs): _kwargs = dict(created=datetime.datetime.utcnow(), ) _kwargs.update(kwargs) super(UserCredential, self).__init__(*args, **_kwargs)
class SessionObject(Model): __metadata__ = { '_name': sessions_tablename, } key = Field(hash_key=True) state = Field() token = Field() def __init__(self, key, state): self.key = key self.state = state
class Minion_Vault(Model): brandId = Field(data_type=NUMBER, range_key = True) userId = Field(data_type=STRING, hash_key = True) coinAmt = Field(data_type=NUMBER) lastChangeDate = Field(data_type=datetime,index='ts_index') # uid = Composite('userId','quantity', data_type=STRING, merge=score_merge,range_key=True) def __init__(self, brandId, userId, coinAmt, lastChangeDate): super(Minion_Vault, self).__init__() self.brandId = brandId self.userId = userId self.coinAmt = coinAmt self.lastChangeDate = lastChangeDate
def test_coerce_date_fail(self): """ Coercing to date fails """ field = Field(data_type=date, coerce=True) with self.assertRaises(TypeError): field.coerce(12345)
def test_coerce_bool_fail(self): """ Coerce to bool fails if coerce=False """ field = Field(data_type=bool) with self.assertRaises(TypeError): field.coerce(2)
def test_int_coerce_long(self): """ Int fields can transparently handle longs """ field = Field(data_type=int) val = 100 ret = field.coerce(val) self.assertEqual(ret, val)
def test_coerce_binary_set(self): """ Coerce to binary set """ field = Field(data_type=set_(six.binary_type), coerce=True) ret = field.coerce([six.u('hello')]) self.assertEqual(ret, set([b'hello']))
def test_datetime_tz(self): """ Normal datetime fields add UTC timezone """ field = Field(data_type=datetime) dt = field.ddb_load(1432828089.027812) self.assertEqual(dt.tzinfo, UTC)
def test_coerce_set(self): """ Coerce to set """ field = Field(data_type=set, coerce=True) ret = field.coerce([1, 2]) self.assertTrue(isinstance(ret, set))
def test_coerce_number_set(self): """ Coerce to number set """ field = Field(data_type=set_(int), coerce=True) ret = field.coerce([2, '4']) self.assertEqual(ret, set([2, 4]))
def test_coerce_decimal(self): """ Coerce to Decimal """ field = Field(data_type=Decimal, coerce=True) ret = field.coerce(5.5) self.assertTrue(isinstance(ret, Decimal))
def test_coerce_decimal_fail(self): """ Coerce to Decimal fails if coerce=False """ field = Field(data_type=Decimal) with self.assertRaises(TypeError): field.coerce(5.5)
def test_coerce_float_fail(self): """ Coerce to float fails if coerce=False """ field = Field(data_type=float) with self.assertRaises(TypeError): field.coerce('4.3')
def test_always_coerce_int_float(self): """ Always coerce ints to float """ field = Field(data_type=float) ret = field.coerce(5) self.assertTrue(isinstance(ret, float))
def test_coerce_float(self): """ Coerce to float """ field = Field(data_type=float, coerce=True) ret = field.coerce('4.3') self.assertTrue(isinstance(ret, float))
def test_coerce_basic_set(self): """ Coerce to an untyped set """ field = Field(data_type=set, coerce=True) ret = field.coerce(['a', 'b']) self.assertEqual(ret, set(['a', 'b']))
def test_coerce_dict(self): """ Coerce to dict """ field = Field(data_type=dict, coerce=True) ret = field.coerce([(1, 2)]) self.assertTrue(isinstance(ret, dict))
def test_coerce_basic_set_fail(self): """ Coercing to untyped set fails """ field = Field(data_type=set) with self.assertRaises(TypeError): field.coerce(['a', 'b'])
def test_coerce_str_fail(self): """ Coerce to bytes fails if coerce=False """ field = Field(data_type=six.binary_type) with self.assertRaises(TypeError): field.coerce(5)
def test_coerce_number_set_fail(self): """ Coerce to number set fails """ field = Field(data_type=set_(int)) with self.assertRaises(TypeError): field.coerce([2, '4'])
def test_always_coerce_unicode_str(self): """ Always coerce unicode to bytes """ field = Field(data_type=six.binary_type) ret = field.coerce(six.u('val')) self.assertTrue(isinstance(ret, six.binary_type))
def test_naive_datetime(self): """ Naive datetime fields don't add timezone """ field = Field(data_type=DateTimeType(naive=True)) dt = field.ddb_load(1432828089.027812) self.assertIsNone(dt.tzinfo)
def test_coerce_list_fail(self): """ Coerce to list fails if coerce=False """ field = Field(data_type=list) with self.assertRaises(TypeError): field.coerce(set([1, 2]))
def test_coerce_str(self): """ Coerce to bytes """ field = Field(data_type=six.binary_type, coerce=True) ret = field.coerce(5) self.assertTrue(isinstance(ret, six.binary_type))
def test_coerce_bool(self): """ Coerce to bool """ field = Field(data_type=bool, coerce=True) ret = field.coerce(2) self.assertTrue(isinstance(ret, bool))
def test_coerce_dict_fail(self): """ Coerce to dict fails if coerce=False """ field = Field(data_type=dict) with self.assertRaises(TypeError): field.coerce([(1, 2)])
def test_coerce_unicode(self): """ Coerce to unicode """ field = Field(data_type=six.text_type, coerce=True) ret = field.coerce(5) self.assertTrue(isinstance(ret, six.text_type))
def test_coerce_list(self): """ Coerce to list """ field = Field(data_type=list, coerce=True) ret = field.coerce(set([1, 2])) self.assertTrue(isinstance(ret, list))
def test_coerce_unicode_fail(self): """ Coerce to unicode fails if coerce=False """ field = Field(data_type=six.text_type) with self.assertRaises(TypeError): field.coerce(5)
def test_int_coerce(self): """ Int fields can coerce floats """ field = Field(data_type=int, coerce=True) ret = field.coerce(4.0) self.assertEquals(ret, 4) self.assertTrue(isinstance(ret, int))
def test_int_coerce_fail(self): """ Coerce to int fails if coerce=False """ field = Field(data_type=int) with self.assertRaises(TypeError): field.coerce(4.0)