connexion_sql_utils package¶
Submodules¶
connexion_sql_utils.base_mixin_abc module¶
base_mixin_abc.py¶
This module contains an abc class that can be used to check that the
correct interface is defined to use the crud methods. Nothing
actually inherits from this class as it breaks when making an
sqlalchemy.ext.declarative:declarative_base, but it is helpful
for issubclass and isinstance checks.
When inheriting from this package’s BaseMixin then one only
needs to implement a session_maker method.
-
class
connexion_sql_utils.base_mixin_abc.BaseMixinABC[source]¶ Bases:
objectUsed to test validity of a mixin. The mixin can not directly inherit from this abc class because of inheritance conflicts with sqlalchemy’s declarative base class, however if a mixin declares all the required methods, then it will pass an
isinstanceor anissubclasscheck.The mixin in this package declares all of the methods except the
session_makermethod which should be implemented once you create asqlalchemy.orm.sessionmakerExample:
engine = create_engine(DB_URI) session = scoped_session(sessionmaker(bind=engine)) class MyBase(BaseMixin): @staticmethod def session_maker(): return session() DbModel = declarative_base(cls=MyBase) assert issubclass(DbModel, BaseMixinABC) # True
Then all of your sqlalchemy models could inherit from the
DbModel.-
dump()[source]¶ Return a json representation of the instance. This is also used as the str() representation of an instance.
-
classmethod
query_by(**kwargs)[source]¶ Query the database model with the given criteria.
This is used as you would use
filter_byon an sqlalchemy query. And should always return a list of items.
-
connexion_sql_utils.crud module¶
crud.py¶
This module contains methods that can be used to query the database.
They are designed to be used in conjunction with the BaseMixin or
a class that passes a check for the BaseMixinABC methods.
These methods do work stand-alone, however they are designed to be used
with functools.partial and connexion. Connexion expects the
functions for it’s api calls to be module level functions. So this allows
one to declare an sqlalchemy model that typically derives from the
BaseMixin. Then one is able to just create partial’s of these
utility functions for the actual operations, providing the correct kwargs
needed by connexion.
The only caveat is that any of the functions that require an id, must
have ‘id’ in their kwarg key.
All of the functions in this module will fail if the asset does not
pass isinstance or an issubclass check for the BaseMixinABC.
A class does not need to directly inherit from BaseMixinABC, it just
must declare all the methods of that interface.
-
connexion_sql_utils.crud.get(asset, limit=1, **kwargs)[source]¶ Retrieves assets from the database. Assets are always returned as a list(array) of size
limit.Parameters: - asset – The database class to query. This must inherit from
Base - limit – The limit for the return values
- kwargs – Are query parameters to filter the assets by
Raises: TypeError – if the
assetdoes not inherit fromBase- asset – The database class to query. This must inherit from
-
connexion_sql_utils.crud.get_id(asset, **kwargs)[source]¶ Get an asset by the unique id.
The key for the id must have ‘id’ in the name in the kwargs.
Example:
get_id(Foo, foo_id=1) # works get_id(Foo, foo=1) # TypeError
-
connexion_sql_utils.crud.post(asset, **kwargs)[source]¶ Post an asset to the database.
Parameters: - asset – The database class to query. This must inherit from
Base - kwargs – This should be of length 1, the key only matters to
connexion, the value for the key is used as the kwargs to make anassetinstance to save to the database. This allows this to be used withfunctools.partial.
Raises: TypeError – if the
assetdoes not inherit fromBase- asset – The database class to query. This must inherit from
-
connexion_sql_utils.crud.put(asset, **kwargs)[source]¶ Update an asset. The kwargs should be of length 2, one of which is an id key (has ‘id’ in it’s name), used to look up the item in the database. The other key should not have ‘id’ in it’s name, and used as the data to update the asset.
Parameters: asset – The database asset. Raises: TypeError – If could not find a key with ‘id’ in it’s name or could not find a key without ‘id’ in it’s name.
connexion_sql_utils.decorators module¶
decorators.py¶
This module holds decorators either used by this package or for use
when creating sqlalchemy database models.
-
connexion_sql_utils.decorators.dump_method(fn)[source]¶ Allow’s the ability to create custom methods that are called during an
BaseMixindump method. The method should recieve on argument which is a dict of all the values so far. The method should then return a dict of the current state of the values passed in.This allows manipulation of existing values, or adding values that are not automatically added during the dump to json.
-
connexion_sql_utils.decorators.ensure_asset(fn)[source]¶ Ensure’s that an asset passes an
isinstanceor anissubclasscheck forBaseMixinABCbefore calling a function. The asset must be the first arg to the function.
-
connexion_sql_utils.decorators.event_func(*event_names)[source]¶ Declare a function to listen/register for an event. The wrapped method should have the correct signature for an
sqlalchemy.event. And should be declared as astaticmethodon the class that is registering for the event.See also
connexion_sql_utils.BaseMixin.create_id()method for an example.Parameters: event_name – The event name to register the function for. Example: ‘before_insert’
-
connexion_sql_utils.decorators.to_json(*keys)[source]¶ Marks a function to be called on
key, when converting an instance to json. This allows you to do work on an item to serialize it to json. A good example use is when you use theNumerictype, that returns aDecimalfrom the database, which is not json serializable, so you must convert it to a string, a float, or an int, before callingjson.dumps.Parameters: keys – The keys/attributes to call the method on when converting.
connexion_sql_utils.sqlmixins module¶
-
class
connexion_sql_utils.sqlmixins.BaseMixin[source]¶ Bases:
objectBase sqlalchemy mixin. Adds id column as a postgresql.UUID column, and will create the uuid before saving to the database.
A user must define a
session_makeron the mixin, to complete it as a classmethod or a staticmethod.All query methods, automatically create a session from the
session_makermethod that should be declared on a sub-class. Any method that creates, updates, or deletes automatically adds and commits the changes.-
static
create_id(mapper, connection, target)[source]¶ Automatically creates a
UUIDbefore inserting a new item.
-
delete(session=None)[source]¶ Delete an instance from the database.
Parameters: session – An optional sqlalchemy session, if one is not passed a session will be created for the query.
-
dump(_dict=None) → str[source]¶ Return a json serialized string or a dict representation of the instance.
Any methods that are wrapped with
to_jsondecorator will be called on the values before returning the json string.Parameters: _dict – If Truereturn a dict instead of a json string, or the class attributedump_dictis true on a sub-class.
-
dump_dict= False¶
-
classmethod
get_id(id, session=None)[source]¶ Get by id.
Parameters: - id – The unique identifier for the class.
- session – An optional sqlalchemy session, if one is not passed a session will be created for the query.
This is would be like:
>>> session.query(MyDbModel).filter_by(id=1234).first()
-
id= Column(None, UUID(), table=None, primary_key=True, nullable=False)¶
-
classmethod
query_by(session=None, **kwargs)[source]¶ Return a query statement for the class.
Parameters: - session – An optional sqlalchemy session, if one is not passed a session will be created for the query.
- kwargs – kwargs passed into the query to filter results.
This would be simalar to:
>>> session.query(MyDbModel).filter_by(id=1234)
-
save(session=None)[source]¶ Save an instance to the database.
Parameters: session – An optional sqlalchemy session, if one is not passed a session will be created for the query.
-
classmethod
session_scope()[source]¶ A context manager for a session. Which creates a session from the import
session_maker`()method that should be declared by sub-class. And is used in the database methods for a class/instance.The session will automatically try to commit any changes, rolling back on any errors, and finally closing the session.
-
static
Module contents¶
-
class
connexion_sql_utils.BaseMixinABC[source]¶ Bases:
objectUsed to test validity of a mixin. The mixin can not directly inherit from this abc class because of inheritance conflicts with sqlalchemy’s declarative base class, however if a mixin declares all the required methods, then it will pass an
isinstanceor anissubclasscheck.The mixin in this package declares all of the methods except the
session_makermethod which should be implemented once you create asqlalchemy.orm.sessionmakerExample:
engine = create_engine(DB_URI) session = scoped_session(sessionmaker(bind=engine)) class MyBase(BaseMixin): @staticmethod def session_maker(): return session() DbModel = declarative_base(cls=MyBase) assert issubclass(DbModel, BaseMixinABC) # True
Then all of your sqlalchemy models could inherit from the
DbModel.-
dump()[source]¶ Return a json representation of the instance. This is also used as the str() representation of an instance.
-
classmethod
query_by(**kwargs)[source]¶ Query the database model with the given criteria.
This is used as you would use
filter_byon an sqlalchemy query. And should always return a list of items.
-
-
class
connexion_sql_utils.BaseMixin[source]¶ Bases:
objectBase sqlalchemy mixin. Adds id column as a postgresql.UUID column, and will create the uuid before saving to the database.
A user must define a
session_makeron the mixin, to complete it as a classmethod or a staticmethod.All query methods, automatically create a session from the
session_makermethod that should be declared on a sub-class. Any method that creates, updates, or deletes automatically adds and commits the changes.-
static
create_id(mapper, connection, target)[source]¶ Automatically creates a
UUIDbefore inserting a new item.
-
delete(session=None)[source]¶ Delete an instance from the database.
Parameters: session – An optional sqlalchemy session, if one is not passed a session will be created for the query.
-
dump(_dict=None) → str[source]¶ Return a json serialized string or a dict representation of the instance.
Any methods that are wrapped with
to_jsondecorator will be called on the values before returning the json string.Parameters: _dict – If Truereturn a dict instead of a json string, or the class attributedump_dictis true on a sub-class.
-
dump_dict= False¶
-
classmethod
get_id(id, session=None)[source]¶ Get by id.
Parameters: - id – The unique identifier for the class.
- session – An optional sqlalchemy session, if one is not passed a session will be created for the query.
This is would be like:
>>> session.query(MyDbModel).filter_by(id=1234).first()
-
id= Column(None, UUID(), table=None, primary_key=True, nullable=False)¶
-
classmethod
query_by(session=None, **kwargs)[source]¶ Return a query statement for the class.
Parameters: - session – An optional sqlalchemy session, if one is not passed a session will be created for the query.
- kwargs – kwargs passed into the query to filter results.
This would be simalar to:
>>> session.query(MyDbModel).filter_by(id=1234)
-
save(session=None)[source]¶ Save an instance to the database.
Parameters: session – An optional sqlalchemy session, if one is not passed a session will be created for the query.
-
classmethod
session_scope()[source]¶ A context manager for a session. Which creates a session from the import
session_maker`()method that should be declared by sub-class. And is used in the database methods for a class/instance.The session will automatically try to commit any changes, rolling back on any errors, and finally closing the session.
-
static
-
connexion_sql_utils.ensure_asset(fn)[source]¶ Ensure’s that an asset passes an
isinstanceor anissubclasscheck forBaseMixinABCbefore calling a function. The asset must be the first arg to the function.
-
connexion_sql_utils.to_json(*keys)[source]¶ Marks a function to be called on
key, when converting an instance to json. This allows you to do work on an item to serialize it to json. A good example use is when you use theNumerictype, that returns aDecimalfrom the database, which is not json serializable, so you must convert it to a string, a float, or an int, before callingjson.dumps.Parameters: keys – The keys/attributes to call the method on when converting.
-
connexion_sql_utils.event_func(*event_names)[source]¶ Declare a function to listen/register for an event. The wrapped method should have the correct signature for an
sqlalchemy.event. And should be declared as astaticmethodon the class that is registering for the event.See also
connexion_sql_utils.BaseMixin.create_id()method for an example.Parameters: event_name – The event name to register the function for. Example: ‘before_insert’
-
connexion_sql_utils.dump_method(fn)[source]¶ Allow’s the ability to create custom methods that are called during an
BaseMixindump method. The method should recieve on argument which is a dict of all the values so far. The method should then return a dict of the current state of the values passed in.This allows manipulation of existing values, or adding values that are not automatically added during the dump to json.
-
connexion_sql_utils.get_id(asset, **kwargs)[source]¶ Get an asset by the unique id.
The key for the id must have ‘id’ in the name in the kwargs.
Example:
get_id(Foo, foo_id=1) # works get_id(Foo, foo=1) # TypeError
-
connexion_sql_utils.get(asset, limit=1, **kwargs)[source]¶ Retrieves assets from the database. Assets are always returned as a list(array) of size
limit.Parameters: - asset – The database class to query. This must inherit from
Base - limit – The limit for the return values
- kwargs – Are query parameters to filter the assets by
Raises: TypeError – if the
assetdoes not inherit fromBase- asset – The database class to query. This must inherit from
-
connexion_sql_utils.put(asset, **kwargs)[source]¶ Update an asset. The kwargs should be of length 2, one of which is an id key (has ‘id’ in it’s name), used to look up the item in the database. The other key should not have ‘id’ in it’s name, and used as the data to update the asset.
Parameters: asset – The database asset. Raises: TypeError – If could not find a key with ‘id’ in it’s name or could not find a key without ‘id’ in it’s name.
-
connexion_sql_utils.post(asset, **kwargs)[source]¶ Post an asset to the database.
Parameters: - asset – The database class to query. This must inherit from
Base - kwargs – This should be of length 1, the key only matters to
connexion, the value for the key is used as the kwargs to make anassetinstance to save to the database. This allows this to be used withfunctools.partial.
Raises: TypeError – if the
assetdoes not inherit fromBase- asset – The database class to query. This must inherit from