Package: noverde-serpens
serpensA set of Python utilities, recipes and snippets.SQS UtilitiesAPI UtilitiesSchemaCSV UtilsDynamoDB DocumentsSQS UtilitiesThis utility is a decorator that iterate by each sqs record.For each sqs record will be inserted arecord object (from type sqs.Record)as  argument that will process the sqs messages.fromserpensimportsqs@sqs.handlerdefmessage_processor(record:sqs.Record):# code to process each sqs messageprint(record.body)RecordThe client function that will process the sqs messages will receive an instance ofsqs.Recorddataclass. This class has the follow structure:classRecord:data:Dict[Any,Any]body:Union[dict,str]message_attributes:Dict[Any,Any]queue_name:strsent_datetime:datetimeRecord attributesdata: Contain all data from SQS message. This attribute is assigned in each iteration in SQS message.body: Returndata["body"]converted todictorstr.message_attributes: Return thedata["messageAttributes"]converted todict.queue_name: Return the queue name extracted fromdata["eventSourceARN"].sent_datetime: Return thedata["attributes"]["SentTimestamp"]converted todatetime.API UtilitiesThis utility is a wrapper to simplify working with lambda handlers. The decoratorapi.handlerwill decorate a function that will process a lambda and this function will receive arequestargument (from type api.Request).fromserpensimportapi@api.handlerdeflambda_handler(request:api.Request):# Code to process the lambdaprint(request.body)Request classThe function that will process the lambda will receive an instance ofsqs.Requestdataclass. This class has the follow structure:fromserpens.apiimportAttrDictclassRequest:authorizer:AttrDictbody:Union[str,dict]path:AttrDictquery:AttrDictheaders:AttrDictidentity:AttrDictNote: the objects from typeAttrDictare objects built by a dict where the dict's key is an attribute of object. For example:fromserpens.apiimportAttrDictobj=AttrDict({"foo":"bar"})obj.foo# barSchemaThe Schema is a base class for create new classes with follow features:Static type checkMethod to convert an object to dictMethod to create an object from jsonMethod to create an object from dictMethod to dump an object to stringCreate a schemafromserpens.schemaimportSchemafromdataclassesimportdataclass@dataclassclassPersonSchema(Schema):name:strage:intCreate a schema objectperson=PersonSchema('Mike',30)print(person.name)print(person.age)Create a schema object from a dict.person_obj=PersonSchema.load({'name':'Mike','age':18})print(person_obj.name)print(person_obj.age)Create a schema object from a json string.importjsondata=json.dumps({'name':'mike','age':20})person_obj=PersonSchema.loads(data)print(person_obj.name)print(person_obj.age)Convert a schema object to dict.p1=PersonSchema('Mike',30)person_dct=PersonSchema.dump(p1)print(person_dct['name'])print(person_dct['age'])Convert a schema object to json string.p1=PersonSchema('Mike',30)person_str=PersonSchema.dumps(p1)print(person_str)CSV UtilsUtility for read and write csv. This utility is useful for read csv with BOM or read csv encoded as ISO-8859.Read CSVfromserpensimportcsvutilsascsvdict_reader=csv.open_csv_reader('fruits_iso8859.csv')forrecordindict_reader:print(record)Write CSVfromserpensimportcsvutilsascsvwriter=csv.open_csv_writer('out.csv')writer.writerow(["id","name"])writer.writerow(["1","Açaí"])delwriterDatabaseThis utilities are useful for working with database.Migrate databasesThis migrations use yoyo-migration.fromserpensimportdatabasedatabase_url="postgres://user:password@host/db"path="/path/to/migrations"# yoyo migrationsdatabase.migrate(database_url,path)Create a Pony Database instance"The Database object manages database connections using a connection pool."fromserpensimportdatabasedatabase_url="postgres://user:password@host/db"db=database.setup(database_url)print(db.provider_name)DynamoDB DocumentsSerpens provides a base class (calledBaseDocument) for working with tables from DynamoDB.Create a document mapping a DynamoDB tablefromserpens.documentimportBaseDocumentfromdataclassesimportdataclass@dataclassclassPersonDocument(BaseDocument):_table_name_='person'id:strname:strSave data in DynamoDB tableperson=PersonDocument(id="1",name="Ana")person.save()Get data from keyObs: If the search doesn't find an item by its key, the return isNoneperson=PersonDocument.get_by_key({"id":"1"})person.id# 1person.name# AnaGet tableperson_table=PersonDocument.get_table()person_table# dynamodb.Table(name='person')