Package: layabase
Database for layabQuery your databases easily and transparently thanks to this module providing helpers on top of most brilliant python
database modules (SQLAlchemyandPyMongo).Table of ContentsFeaturesHow to useTechnical documentationFeaturesFeatures:AuditAutomatic audit support (iflayabauthpython module is used, user will be logged as well)RollbackAutomatic rollback support (when history is activated)HistoryAutomatic history managementValidationEnforce proper values are received (type, restricted choices, required fields)ConversionConverting JSON received data to appropriate database data typeConverting Database data type to JSONHealth checkSmart queriesHTTP query parameters are extracted and converted from HTTP query argumentsSpecial parameter: order_by (Feature not available for mongo)Special parameter: limitSpecial parameter: offsetQuery on multiple equality viafield=value1&field=value2Query on excluded intervals viafield=>value1&field=<value2Query on included intervals viafield=>=value1&field=<=value2Query on restricted values viafield=!=value1&field=!=value2(Feature not yet available)Query via a mix of all those features if needed as long as it make sense to youQuery regex thanks to*character viafield=v*lue(Feature not yet available for mongo)UsageYou will define a class to help you with the manipulation of:A collection if this is a MongoDB you are connecting to.A table if this is a non-Mongo database you are connecting to.This class will describe:The document fields if this is a MongoDB you are connecting to.The table columns if this is a non-Mongo database you are connecting to.By providing this class to a layabase.CRUDController instance, you will automatically have all features described in the previous section.CRUD Controllerlayabase.CRUDController provides C.R.U.D. methods (and more, as listed in features) on a specified table or mongo collection.Controller definitionimportlayabase# This will be the class describing your table or collection as defined in Table or Collection sections afterwardstable_or_collection=Nonecontroller=layabase.CRUDController(table_or_collection)Controller featuresRetrieving dataYou can retrieve a list of rows or documents described as dictionaries:importlayabase# This will be the controller as created in Controller definition sectioncontroller:layabase.CRUDController=Noneall_rows_or_documents=controller.get({})filtered_rows_or_documents=controller.get({"value":'value1'})You can retrieve a single row or document described as dictionary:importlayabase# This will be the controller as created in Controller definition sectioncontroller:layabase.CRUDController=Nonerow_or_document=controller.get_one({"value":'value1'})Inserting dataYou can insert many rows or documents at once using dictionary representation:importlayabase# This will be the controller as created in Controller definition sectioncontroller:layabase.CRUDController=Noneinserted_rows_or_documents=controller.post_many([{'key':'key1','value':'value1'},{'key':'key2','value':'value2'},])You can insert a single row or document using dictionary representation:importlayabase# This will be the controller as created in Controller definition sectioncontroller:layabase.CRUDController=Noneinserted_row_or_document=controller.post({'key':'key1','value':'value1'})Updating dataYou can update many rows or documents at once using (partial) dictionary representation:importlayabase# This will be the controller as created in Controller definition sectioncontroller:layabase.CRUDController=Noneupdated_rows_or_documents=controller.put_many([{'key':'key1','value':'new value1'},{'key':'key2','value':'new value2'}])You can update a single row or document using (partial) dictionary representation:importlayabase# This will be the controller as created in Controller definition sectioncontroller:layabase.CRUDController=Noneupdated_row_or_document=controller.put({'key':'key1','value':'new value1'})Removing dataYou can remove a subset of rows or documents:importlayabase# This will be the controller as created in Controller definition sectioncontroller:layabase.CRUDController=Nonenb_removed_rows_or_documents=controller.delete({"key":'key1'})You can remove all rows or documents:importlayabase# This will be the controller as created in Controller definition sectioncontroller:layabase.CRUDController=Nonenb_removed_rows_or_documents=controller.delete({})Retrieving table or collection mappingimportlayabase# This will be the controller as created in Controller definition sectioncontroller:layabase.CRUDController=None# non mongo description = {'table': 'MyTable', 'key': 'key', 'value': 'value'}# mongo description = {'table': 'MyCollection', 'key': 'key', 'value': 'value'}description=controller.get_model_description()Auditingimportlayabase# This will be the controller as created in Controller definition sectioncontroller:layabase.CRUDController=Noneall_audit_models_as_dict_list=controller.get_audit({})filtered_audit_models_as_dict_list=controller.get_audit({"value":'value1'})Link to a databaseLink to a Mongo databaseimportlayabase# Should be a list of CRUDController inherited classesmy_controllers=[]layabase.load("mongodb://host:port/server_name",my_controllers)Link to a Mongo in-memory databaseimportlayabase# Should be a list of CRUDController inherited classesmy_controllers=[]layabase.load("mongomock",my_controllers)Link to a non Mongo databaseimportlayabase# Should be a list of CRUDController inherited classesmy_controllers=[]layabase.load("your_connection_string",my_controllers)Relational databases (non-Mongo)SQLAlchemyis the underlying framework used to manipulate relational databases.To create a representation of a table you will need to create aMixin.TableYou can add extra information to a column thanks to the info parameter.If the field should be required on queries:info={'marshmallow':{"required_on_query":True}}If*character in queries values should be interpreted as any characters:info={'marshmallow':{"interpret_star_character":True}}If the field can be queried with comparison signs such as >, <, >=, <=:info={'marshmallow':{"allow_comparison_signs":True}}When querying, provide a single value of a list of values.if provided inorder_byparameter, it will be considered as ascending order, adddescat the end of the value to explicitly order by in descending order.If the field allow comparison signs (allow_comparison_signs), you can add>,>=,<,<=in front of the value.fromsqlalchemyimportColumn,StringclassMyTable:__tablename__="my_table"key=Column(String,primary_key=True)value=Column(String)MongoDB (non-relational)PyMongois the underlying framework used to manipulate MongoDB.To create a representation of a collection you will need to create a Mixin class.To link your model to the underlying collection, you will need to provide a connection string.Collectionfromlayabase.mongoimportColumnclassMyCollection:__collection_name__="my_collection"key=Column(str,is_primary_key=True)dict_value=Column(dict)String fieldsFields containing string can be described using layabase.mongo.Columnfromlayabase.mongoimportColumnclassMyCollection:__collection_name__="my_collection"key=Column()As string is considered as the default field type, not providing the type explicitly when creating a column is valid.The following parameters can also be provided when creating a column of string type:DescriptionDefault valuechoicesRestrict valid values. Should be a list of string or a function (without parameters) returning a list of string.None (unrestricted)default_valueDefault field value returned to the client if field is not set. Should be a string or a function (with dictionary as parameter) returning a string.NonedescriptionField description used in OpenAPI definition and in error messages. Should be a string value.Noneindex_typeIf and how this field should be indexed. Value should be one of IndexType enum.None (not indexed)allow_none_as_filterIf None value should be kept in queries (GET/DELETE). Should be a boolean value.False (remove None from queries)is_primary_keyIf this field value is not allowed to be modified after insert. Should be a boolean value.False (field value can always be modified)is_nullableIf field value is optional. Should be a boolean value. Note that it is not allowed to force False if field has a default value.Default to True if field is not a primary key.
        Default to True if field has a default value.
        Otherwise default to False.is_requiredIf field value must be specified in client requests. Use it to avoid heavy requests. Should be a boolean value.False (optional)min_lengthMinimum value length.None (no minimum length)max_lengthMaximum value length.None (no maximum length)allow_comparison_signsIf field value should be interpreted to extract >, >=, <, <= prefix.False (value is kept as provided for equlity comparison)Dictionary fieldsFields containing a dictionary can be described using layabase.mongo.DictColumnfromlayabase.mongoimportDictColumnclassMyCollection:__collection_name__="my_collection"key=DictColumn()List fieldsFields containing a list can be described using layabase.mongo.ListColumnfromlayabase.mongoimportListColumn,ColumnclassMyCollection:__collection_name__="my_collection"key=ListColumn(Column())How to installpython 3.6+must be installedUse pip to install module:python-mpipinstalllayabaseNote that depending on what you want to connect to, you will have to use a different module name than layabase:Mongo database: layabase[mongo]Mongo in-memory database: layabase mongomockOther database: layabase[sqlalchemy]TechnicalRequirementsUsageDeveloper-RequirementsThe module requires the following to run:python 3.6+Developer-UsageInstallationDependencies can be installed viasetup.py:python-mpipinstall.TestingTest specific dependencies can be installed viasetup.pytestingoptional:python-mpipinstall.[testing]Then you can launch tests usingpytest.