API¶
The public interface to connexion_sql_utils
.
BaseMixinABC¶
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.
BaseMixinABC
[source] Used 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
isinstance
or anissubclass
check.The mixin in this package declares all of the methods except the
session_maker
method which should be implemented once you create asqlalchemy.orm.sessionmaker
Example:
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
.-
delete
()[source] Delete an instance from the database.
-
dump
()[source] Return a json representation of the instance. This is also used as the str() representation of an instance.
-
classmethod
get_id
(id)[source] Query the database for a single item by it’s unique id.
-
classmethod
query_by
(**kwargs)[source] Query the database model with the given criteria.
This is used as you would use
filter_by
on an sqlalchemy query. And should always return a list of items.
-
save
()[source] Save an instance to the database.
-
static
session_maker
()[source] Return an
sqlalchemy.orm.Session
to be used in the other methods.
-
classmethod
session_scope
()[source] A context manager for a session, should yield a
sqlalchemy.orm.Session
-
update
(**kwargs)[source] Update an instance’s attributes and save to the database.
-
BaseMixin¶
The following can be found in the sqlmixins.py
module.
-
class
connexion_sql_utils.
BaseMixin
[source] Base 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_maker
on the mixin, to complete it as a classmethod or a staticmethod.All query methods, automatically create a session from the
session_maker
method 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
UUID
before 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_json
decorator will be called on the values before returning the json string.Parameters: _dict – If True
return a dict instead of a json string, or the class attributedump_dict
is true on a sub-class.
-
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()
-
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.
-
update
(session=None, **kwargs)[source] Update attributes on an instance.
Parameters: - kwargs – The attributes to update on the instance. Any attribute not declared on the class is ignored.
- session – An optional sqlalchemy session, if one is not passed a session will be created for the query.
-
static
Decorators¶
decorators.py¶
This module holds decorators either used by this package or for use
when creating sqlalchemy
database models.
-
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 astaticmethod
on 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.
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 theNumeric
type, that returns aDecimal
from 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.
dump_method
(fn)[source] Allow’s the ability to create custom methods that are called during an
BaseMixin
dump 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.
ensure_asset
(fn)[source] Ensure’s that an asset passes an
isinstance
or anissubclass
check forBaseMixinABC
before calling a function. The asset must be the first arg to the function.
CRUD¶
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.
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
asset
does not inherit fromBase
- asset – The database class to query. This must inherit from
-
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.
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 anasset
instance to save to the database. This allows this to be used withfunctools.partial
.
Raises: TypeError – if the
asset
does 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.
delete
(asset, **kwargs)[source] Delete an asset