Created
July 20, 2021 02:31
-
-
Save thanakijwanavit/260d80ded6dcb962807eaffb919444c0 to your computer and use it in GitHub Desktop.
runningNumber with pynamodb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
KEYTABLE = os.environ.get('KEYTABLE') | |
# Cell | |
from pynamodb.models import Model | |
from pynamodb.attributes import UnicodeAttribute, NumberAttribute | |
from awsSchema.apigateway import Event, Response | |
from datetime import datetime | |
from nicHelper.schema import validateUrl | |
from jsonschema import ValidationError | |
from beartype import beartype | |
import yaml, json | |
# Cell | |
class Counter(Model): | |
class Meta: | |
table_name = KEYTABLE | |
region = 'ap-southeast-1' | |
dax_read_endpoints = ['longtermcluster.vuu7lr.clustercfg.dax.apse1.cache.amazonaws.com:8111'] | |
dax_write_endpoints = ['longtermcluster.vuu7lr.clustercfg.dax.apse1.cache.amazonaws.com:8111'] | |
## hash key | |
key=UnicodeAttribute(hash_key = True) | |
counter = NumberAttribute() | |
lastEdited=NumberAttribute() | |
##### functions #### | |
def __repr__(self): | |
return f'{yaml.dump(self.to_dict())}' | |
def recordTime(self): | |
'''record last edited and creation time''' | |
self.lastEdited = datetime.now().timestamp() # record last edited | |
def save(self): | |
self.recordTime() | |
def save(self): | |
self.lastEdited = datetime.now().timestamp() | |
self.counter += 1 | |
try: | |
super().save() | |
return next(self.query(self.key)) | |
except Exception as e: | |
raise Exception(f'error saving id {self.orderId} {e}') | |
@classmethod | |
@beartype | |
def count(cls, key:str)->int: | |
counter:cls = next(cls.query(key,consistent_read= True), cls(key = key, counter = 0)) | |
i = counter.counter | |
counter.save() | |
return i | |
def to_dict(self): | |
return json.dumps(vars(self)) | |
@classmethod | |
def from_dict(cls, inputDict:dict): | |
return cls(**inputDict) | |
# Cell | |
def generateId(event, *args): | |
''' | |
generate order Id: | |
''' | |
# get parse input | |
payload = Event.parseBody(event) | |
print(payload) | |
## validateInput | |
url = 'https://raw.githubusercontent.com/thanakijwanavit/villaMasterSchema/dev/order/genOrderId.yaml' | |
try: | |
validateUrl(url, payload, format_='yaml') | |
except ValidationError as e: | |
return Response.returnError(f'error validation {e}') | |
except Exception as e: | |
return Response.returnError(f'unknown error {e}') | |
# get year | |
year = str(datetime.now().year)[-2:] | |
## get branchId | |
branchId = payload.get('branchId') | |
## generateKey | |
key = year+branchId | |
# get count n | |
n = str(Counter.count(key)).rjust(10,'0') | |
return Response.returnSuccess({'orderId': f'{branchId}{year}{n}'}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment