special pynamodb attributes
from pynamodb.models import Model
from pynamodb.attributes import NumberAttribute
from dataclasses import dataclass
from dataclasses_json import dataclass_json
from nicHelper.dataclassUtil import enforce_types
import pytest
@enforce_types
@dataclass_json
@dataclass
class Product:
code: str
id_: int
class Table(Model):
class Meta:
table_name='test-please-delete'
region_name='ap-southeast-1'
id_= NumberAttribute(hash_key=True)
product = DataclassJsonAttribute(customDataClass=Product)
Table.create_table(billing_mode='PAY_PER_REQUEST')
Table(id_=123,product={'code':'123','id_':123 }).save()
with pytest.raises(TypeError):
Table(id_=123,product={'code':123,'id_':123 }).save()
raise Exception('type error should occur')
Table.delete_table()
testSchema = 'https://gist.githubusercontent.com/thanakijwanavit/e2720d091ae0cef710a49b57c0c9cd4c/raw/ed2d322eac4900ee0f95b431d0f9067a40f3e0f0/squirrelOpenApiV0.0.3.yaml'
schema = yaml.load(requests.get(testSchema).text, Loader= yaml.Loader)
path = 'components/schemas/Location'
dpath.util.get(schema, path)
schemaUrl = 'https://raw.githubusercontent.com/thanakijwanavit/villaMasterSchema/master/Product.json'
from typing import Any
class TestModel(SuperModel):
class Meta:
table_name="colab-test-sensitive-column"
region = 'ap-southeast-1'
data = SchemaAttribute(schemaUrl = schemaUrl, null=True)
phoneHash = UnicodeAttribute(hash_key=True)
# Overrides
def pullOutKeys(self)->None:
self.phoneHash = str(self.data.get('phoneHash') or self.data.get('iprcode') or self.data.get('id') )
@beartype
def toDict(self)->dict:
return self.data
@classmethod
@beartype
def fromDict(cls, inputDict:dict)->Any:
return cls(data=inputDict)
@beartype
def update(self,inputDict:dict)->None:
self.data.update(inputDict)
d = TestModel('123', data={'iprcode': 4, 'cprcode': 123 , 'oprCode': '123', 'orderId': 123})
assert d.pullOutKeys() == None
assert type(d.toDict()) == dict
assert d.update({'cprcode': 234}) ==None
from nicHelper.exception import errorString
try:
test = TestModel.fromDict({'iprcode': 4, 'cprcode': 123 , 'oprCode': '123', 'orderId': 123})
test.save()
except Exception as e:
print(e)
print(errorString())
next(TestModel.query('1'))
next(TestModel.query('1'))
try:
TestModel(
data = {'iprcode': '4', 'cprcode': 123 , 'oprCode': '123'}
).save()
except Exception as e:
print(e)
next(TestModel.query('1'))
schemaUrl = 'https://gist.githubusercontent.com/thanakijwanavit/e2720d091ae0cef710a49b57c0c9cd4c/raw/ed2d322eac4900ee0f95b431d0f9067a40f3e0f0/squirrelOpenApiV0.0.3.yaml'
path = '/components/schemas/Location'
class ProductModel(SuperModel):
class Meta:
table_name="colab-test-sensitive-column"
region = 'ap-southeast-1'
phoneHash = UnicodeAttribute(hash_key=True)
data = SchemaAttribute(schemaUrl = schemaUrl,path=path, null=True)
def pullOutKeys(self):
self.phoneHash = self.data.get('id')
def test_nested():
result = {}
try:
ProductModel(
data = {'type': 'something invalid', 'street_address': '123' }
).save()
except Exception as e:
print('faulty data is rejected')
result['errorModel'] = True
try:
data = {'type': 'pick up', 'street_address': '123' , 'id': '123', 'city':'sth', 'state': 'CA', 'zip':'23523', 'capacity':5, 'status':'open'}
product:ProductModel = ProductModel.fromDict(data)
result['successModel'] = True
except Exception as e:
print(f'valid data is rejected\n{e}')
result['successModel'] = False
assert next(TestModel.query('1')).data == {'type': 'pick up', 'street_address': '123' , 'id': '123', 'city':'sth', 'state': 'CA', 'zip':'23523', 'capacity':5, 'status':'open'}
assert result['successModel'] == True, 'success model didnt save properly'
assert result['errorModel'] == True, 'error model went through'
test_nested()
def create (event, *args):
body = Event.parseBody(event)
body['id'] = body['phoneHash']
event2 = Event.getInput(body)
r = createData(event2, hashKeyName='phoneHash', mainClass=TestModel)
if r.get('statusCode') != 200: return r
r2 = next(TestModel.query(body['phoneHash']), None)
if not r2: return Response.returnError('st wrong with saving, saving but didnt go through')
return Response.returnSuccess(r2)
schemaUrl = 'https://raw.githubusercontent.com/thanakijwanavit/villaMasterSchema/master/Product.json'
data = {'phoneHash': '123','iprcode': 4, 'cprcode': 123 , 'oprCode': '123'}
event = Event.getInput(data)
item = next(TestModel.queryId('123'), None)
print('existing item is :',item)
# delete item if exist
if item:
print(item.delete())
create(event)
createData(Event.getInput(data), hashKeyName='phoneHash', mainClass =TestModel)
next(TestModel.query('123'))
test = TestModel(data = data)
test.save()
test.phoneHash
next(TestModel.query('123'))
def lambdaGet(event, *args):
query = Event.parseBody(event)
if 'key' not in query: return Response.returnError(f'missing key')
return getData(query['key'], TestModel)
data = {'phoneHash': '123','iprcode': 4, 'cprcode': 123 , 'oprCode': '123'}
event = Event.getInput(data)
create(event)
lambdaGet(Event.getInput({'key': '123'}))
lambdaGet(Event.getInput({'key': 123}))
def update(event, *args):
body = Event.parseBody(event)
body['id'] = body['phoneHash']
event2 = Event.getInput(body)
hashKeyname = 'id'
return updateData(event2, hashKeyName=hashKeyname, mainClass=TestModel)
r = create(Event.getInput({'phoneHash': '123','iprcode': 5, 'cprcode': 123 , 'oprCode': '123'}))
r = update(Event.getInput({'phoneHash': '123','iprcode': 5, 'cprcode': 123 , 'oprCode': '1234'}))
lambdaGet(Event.getInput({'key':'123'}))