Package: braincube-aws-core-alpha
braincube-aws-coreMicroframework for Python AWS lambdas.Installationpipinstallbraincube-aws-core-alphaBuilt Withasyncpg- A fast PostgreSQL Database Client Library for Python/asyncio.pydantic- Data validation using Python type hints.pypika- Python Query Builder.Application Controllers Exampleimportasynciofromuuidimportuuid4fromhttpimportHTTPStatusfromcore.rest.dataimportHTTPRequest,HTTPResponsefromcore.rest.app_moduleimportAppModulefromcore.rest.app_controllerimportAppControllerfrompydanticimportBaseModelclassAccountDto(BaseModel):iban:strbban:strdata={"a0a412d9-87ef-474b-9ac8-b682ec5e0fb3":AccountDto(iban="EUR27100777770209299700",bban="EURC12345612345678"),"5ebc25bd-e152-4a70-b251-d68e43be581e":AccountDto(iban="GR27100777770209299700",bban="GRC12345612345678"),}app=AppController("/accounts")@app.get("/{id}")asyncdefget_account(request:HTTPRequest)->HTTPResponse:account=data.get(request.path_parameters["id"])returnHTTPResponse(HTTPStatus.OKifaccountelseHTTPStatus.NO_CONTENT,account)@app.post()asyncdefcreate_account(request:HTTPRequest[AccountDto])->HTTPResponse:data[uuid4()]=request.bodyreturnHTTPResponse(HTTPStatus.CREATED)loop=asyncio.get_event_loop()module=AppModule([app])defmain(event,context):returnloop.run_until_complete(module.serve(event,context))Dependency Injection Examplefromcore.di.injectorimportinjectfromcore.dal.postgres_connectionimportget_pool,Pool@inject("data_warehouse_pool")asyncdefprovide_warehouse_pool()->Pool:returnawaitget_pool()@inject(qualifier="pool:data_warehouse_pool")classBankService:def__init__(self,pool:Pool):self._pool=poolPostgres Repository Examplefromcore.rest.dataimportHTTPRequestfromcore.utils.dataimportOrder,OrderTypefromcore.dal.dataimportKey,Schema,Column,Relation,SimpleColumn,JoinType,JoinThrough,StatementFieldfromcore.dal.postgres_connectionimportget_pool,Poolfromcore.dal.postgres_repositoryimportPostgresRepository# schema definitionequities=Schema(table="equities",alias="e",primary_key=["id"],columns=[Column("id",updatable=False,insertable=False),Column("name"),Column("type"),Column("issuer_id",alias="issuerId"),Column("industry_sector",alias="industrySector"),Column("isin"),Column("reference"),Column("bloomberg_code",alias="bloombergCode"),Column("market_symbol",alias="marketSymbol"),Column("currency"),Column("country",),Column("min_amount",alias="minAmount"),],statement_fields=[StatementField("isTypeOne",statement="CASE WHEN e.type = 1 then True else False END")],order=[Order(type=OrderType.asc,alias="name")],relations=[Relation(table="parties",alias="p",columns=[SimpleColumn("name"),SimpleColumn("short_name",alias="shortName"),],join_forced=False,join_type=JoinType.left,join_through=JoinThrough(from_column_name="issuer_id",to_column_name="id"))])# repository definitionclassEquitiesRepo(PostgresRepository):def__init__(self,pool:Pool):super().__init__(pool,equities)# repository usagerequest=HTTPRequest()repo=EquitiesRepo(awaitget_pool())awaitrepo.find_by_pk(Key(request.path_parameters["id"]),request.query_parameters.fields)awaitrepo.exists_by_pk(Key("9448a57b-f686-4935-b152-566baab712db"))awaitrepo.find_one(request.query_parameters.fields,conditions=request.query_parameters.conditions,order=request.query_parameters.order)awaitrepo.find_all(request.query_parameters.fields,conditions=request.query_parameters.conditions,order=request.query_parameters.order)awaitrepo.find_all_by_pk([Key("9448a57b-f686-4935-b152-566baab712db"),Key("43c8ec37-9a59-44eb-be90-def391ba2f02")],aliases=request.query_parameters.fields,order=request.query_parameters.order)awaitrepo.find_many(request.query_parameters.fields,conditions=request.query_parameters.conditions,page=request.query_parameters.page,order=request.query_parameters.order)awaitrepo.insert({"name":"Bursa de Valori Bucuresti SA","type":1,"industrySector":40,"isin":"ROBVBAACNOR0","bloombergCode":"BBG000BBWMC5","marketSymbol":"BVB RO Equity","currency":"RON","country":"RO",})awaitrepo.insert_bulk(aliases=["name","type","industrySector","isin","bloombergCode","marketSymbol","currency","country"],data=[["Bursa de Valori Bucuresti SA",1,40,"ROBVBAACNOR0","BBG000BBWMC5","BVB RO Equity","RON","RO"],["Citigroup Inc",1,40,"US1729674242","BBG000FY4S11","C US Equity","USD","US"],["Coca-Cola HBC AG",1,49,"CH0198251305","BBG004HJV2T1","EEE GA Equity","EUR","GR"],])awaitrepo.update({"type":1,"isin":40,},request.query_parameters.conditions,request.query_parameters.fields)awaitrepo.update_by_pk(Key("9448a57b-f686-4935-b152-566baab712db"),{"type":1,"isin":40})awaitrepo.delete(request.query_parameters.conditions,["id","name","type"])awaitrepo.delete_by_pk(Key("9448a57b-f686-4935-b152-566baab712db"),["id","name","type"])awaitrepo.fetch("SELECT * FROM equities WHERE type = $1 and isin = $2",[1,"TREEGYO00017"])awaitrepo.fetch_one("SELECT * FROM equities WHERE id = $1",["2b67122a-f47e-41b1-b7f7-53be5ca381a0"])awaitrepo.execute("DELETE FROM equities WHERE id = $1",["2b67122a-f47e-41b1-b7f7-53be5ca381a0"])Query params formatfields=name, type, industrySector, isin, bloombergCode, parties_name, parties_shortName
type=1
isin=range(40, 49)
id=any(9448a57b-f686-4935-b152-566baab712db, 43c8ec37-9a59-44eb-be90-def391ba2f02)
page_no=1
page_size=50
top_size=50
order=name, id DESCLocal Development RequirementsTo use the SAM CLI, you need the following tools.SAM CLIPython 3DockerRun server locally# open ssh tunelsudoshssh_tunnel_Analog_JBox.sh# apply code changes to docker imagesam-api$sambuild# start server locally on http://127.0.0.1:3000sam-api$samlocalstart-api--warm-containersEAGER# or run function locally using event.json as parametersam-api$samlocalinvokeApiFunction--eventevents/event.jsonDeploy to AWSsambuild--use-container
samdeploy--capabilitiesCAPABILITY_NAMED_IAM--guided--profileanalog_user--regioneu-west-1Build and deploy new package version using twinepython3-mpipinstall--upgradepip
python3-mpipinstall--upgradebuild
python3-mpipinstall--upgradetwinepython3-mbuild
twineupload--skip-existingdist/*ResourcesSAM template.ymlasyncpg driverPyPika query builderPydantic