asyncpg_simpleorm package¶
Subpackages¶
Submodules¶
asyncpg_simpleorm.abstract module¶
-
class
asyncpg_simpleorm.abstract.AsyncContextManagerABC[source]¶ Bases:
objectAbstract representation of an async context manager.
Ensures a class has
__aenter__and__aexit__methods.
-
class
asyncpg_simpleorm.abstract.AsyncModelABC[source]¶ Bases:
objectAbstract representation of an async database model.
-
abstractmethod classmethod
connection()[source]¶ Return an async context manager, that returns an
asyncpg.Connectioninstance.Return type: AsyncContextManagerABC
-
abstractmethod classmethod
from_record()[source]¶ Return an instance of the class from an
asyncpg.Recordinstance.Return type: AsyncModelABC
-
abstractmethod classmethod
asyncpg_simpleorm.async_model module¶
-
class
asyncpg_simpleorm.async_model.AsyncModel(**kwargs)[source]¶ Bases:
asyncpg_simpleorm.async_model.BaseModelExtends the
BaseModelclass to include helpful database queries.By default
getandget_onemethods returnasyncpg.Recordinstances. This option can be toggled class wide, by setting a class attribute_return_recordstoFalseon a subclass, or can be toggled during a single method call (seegetmethods for details).This class uses the
__init_subclass__syntax new inpython-3.6. That allowskwargsto be passed into the class declaration.A user should subclass this providing a
ConnectionManagerorPoolManagerto provide the database connection.Raises: RuntimeError – If subclass does not provide a connectionkwarg in the class declaration.Example:
''' The following example would be for a postgres table created by. CREATE TABLE users ( _id uuid PRIMARY KEY, name varchar(100) NOT NULL ) ''' import uuid DBURI = 'postgres://user:password@localhost:5432/database' class User(AsyncModel, connection=ConnectionManager(DBURI)): __tablename__ = 'users' id = Column('_id', primary_key=True, default=uuid.uuid4) name = Column() # Or using a ``PoolManager``. class User(AsyncModel, connection=PoolManager(DBURI)): ... # Create an instance using ``kwargs`` user = User(name='foo') print(user) # User(id=95ccbcd3-2ded-4ad8-9f68-d60f0b9590a9, name='foo')
-
classmethod
connection()[source]¶ Obtain the connection manager that was registered with the subclass during creation.
This is typically used with
async withto gain access to anasyncpg.Connectioninstance.Example:
>>> async with User.connection() as conn: # do something with the connection.
Return type: Union[ConnectionManager,PoolManager]
-
await
delete()[source]¶ Delete an instance from the database.
Raises: exceptions.ExecutionFailure – If no records were deleted from the database. Return type: None
-
classmethod
from_record()[source]¶ Return an instance of the class from an
asyncpg.Recordobject.Return type: Any
-
classmethod await
get(**kwargs)[source]¶ Get a list of the table items from the database.
Parameters: - records (
Optional[bool]) – Optional bool. IfTruethen we returnasyncpg.Record’s. IfFalsethen we will return instances of theAsyncModelsubclass. IfNone, then we default to what’s set on the subclass at the _return_records attribute (default isTrue). - kwargs – Optional kwargs that are passed into a
whereclause.
Example:
>>> await User.get(records=False) [User(id=95ccbcd3-2ded-4ad8-9f68-d60f0b9590a9, name='foo'), ...] >>> await User.get() [<Record(_id=UUID('95ccbcd3-2ded-4ad8-9f68-d60f0b9590a9'), name='foo'>, ...]
Return type: Iterable[Any]- records (
-
classmethod await
get_one(**kwargs)[source]¶ Get a single item from the database.
Parameters: - record (
Optional[bool]) – Optional bool. IfTruethen we returnasyncpg.Record’s. IfFalsethen we will return instances of theAsyncModelsubclass. IfNone, then we default to what’s set on the subclass at the _return_records attribute (default isTrue). - kwargs – Optional kwargs that are passed into a
whereclause.
Example:
>>> await User.get_one(name='foo') <Record _id=UUID('95ccbcd3-2ded-4ad8-9f68-d60f0b9590a9'), name='foo'> >>> await User.get_one(record=False, name='foo') User(id=456, name='bar')
Return type: Any- record (
-
await
save()[source]¶ Update or insert an instance to the database.
Raises: exceptions.ExecutionFailure – If no records were updated or saved to the database. Example:
>>> user = User(name='foo') >>> await user.save()
Return type: None
-
classmethod
-
class
asyncpg_simpleorm.async_model.BaseModel(**kwargs)[source]¶ Bases:
objectImplementation of
ModelABC. This class should typically not be used directly, unless building a custom statement generating class.This class allows column instance values to be set either by the attribute name the column was declared as, or the database column name (which are not always the same).
Example:
>>> class User(BaseModel): id = Column('_id', primary_key=True) name = Column() >>> u1 = User(id=123, name='foo') >>> u2 = User(_id=456, name='bar') >>> print(u1.id, u2.id) (123, 456)
Parameters: kwargs – Key word args that are set on an instance. These would typically be the same keysas the declaredColumn’s on a subclass.-
classmethod
attr_name_for_column()[source]¶ Get the class attribute name for a given database column name.
This is used when setting instance values for :class`Column`’s, and allows access to the attribute name, whether the
column_namewas parsed using the actual database column name, or the attribute name (which can be different depending on theColumn).Example:
>>> class User(BaseModel): id = Column('_id', primary_key=True) name = Column() >>> User.attr_name_for_column('_id') 'id' >>> User.attr_name_for_column('id') 'id'
Parameters: column_name ( str) – The database column name to get the attribute name for.Raises: ValueError – If no Columnis found for that column name.Return type: str
-
classmethod
column_names()[source]¶ Returns a tuple of the column names for the class.
Return type: Tuple[str]
-
classmethod
ensured_column_name()[source]¶ This is helper to always return the database column name for the input.
This is essentially the opposite of
attr_name_for_column().Example:
>>> class User(BaseModel): id = Column('_id', primary_key=True) name = Column() >>> User.ensured_column_name('_id') '_id' >>> User.ensured_column_name('id') '_id'
Parameters: column_name – The attribute name to get the column name for. Raises: ValueError – If no Columnis found for that attribute name.Return type: str
-
classmethod
-
class
asyncpg_simpleorm.async_model.Column(key: str = None, default=None, primary_key=False)[source]¶ Bases:
objectA descriptor class that represents a table column.
Parameters: - key (
Optional[str]) – The table column name in the database. If not set, then this will be set to the attribute name used on theAsyncModelsubclass the column was declared on. - default – A value or callable that is used for a default value. If this is callable, then it should recieve no input and return a value when called.
- primary_key – Set’s if the column is a primary key column. Primary
key columns are used in certain query statements, such
as
AsyncModel.save()
-
default¶
-
key¶
-
primary_key¶
- key (
-
class
asyncpg_simpleorm.async_model.ModelMeta[source]¶ Bases:
typeMeta class for
BaseModel, which ensures the column’s keys for the model are set, or will default to the attribute name aColumnwas declared for.This allows the
keyattribute of aColumnto be optional.Example:
>>> class User(BaseModel): id = Column('_id', primary_key=True) name = Column() >>> User.id.key '_id' >>> User.name.key 'name'
asyncpg_simpleorm.connection_managers module¶
-
class
asyncpg_simpleorm.connection_managers.ConnectionManager(*args, **kwargs)[source]¶ Bases:
asyncpg_simpleorm.abstract.AsyncContextManagerABCAn async context manager that mimics the
asyncpg.connect()function, used with subclasses ofAsyncModel.Parameters: - args – Passed to
asyncpg.connect()function. - kwargs – Passed to
asyncpg.connect()function.
- args – Passed to
-
class
asyncpg_simpleorm.connection_managers.PoolManager(*args, **kwargs)[source]¶ Bases:
asyncpg_simpleorm.abstract.AsyncContextManagerABCAn async context manager that mimics the
asyncpg.create_pool()function, used with subclasses ofAsyncModel.Parameters: - args – Passed to
asyncpg.create_pool()function. - kwargs – Passed to
asyncpg.create_pool()function.
- args – Passed to
asyncpg_simpleorm.exceptions module¶
-
exception
asyncpg_simpleorm.exceptions.BaseException[source]¶ Bases:
ExceptionThe base exception class.
-
exception
asyncpg_simpleorm.exceptions.ExecutionFailure[source]¶ Bases:
asyncpg_simpleorm.exceptions.BaseException,ValueErrorRaised if execution of a database statement fails.
-
exception
asyncpg_simpleorm.exceptions.InvalidModel[source]¶ Bases:
asyncpg_simpleorm.exceptions.BaseException,TypeErrorRaised if a model does not pass an
issubclassorisinstancecheck againstModelABC.
Module contents¶
-
class
asyncpg_simpleorm.AsyncModelABC[source]¶ Bases:
objectAbstract representation of an async database model.
-
abstractmethod classmethod
connection()[source]¶ Return an async context manager, that returns an
asyncpg.Connectioninstance.Return type: AsyncContextManagerABC
-
abstractmethod classmethod
from_record()[source]¶ Return an instance of the class from an
asyncpg.Recordinstance.Return type: AsyncModelABC
-
abstractmethod classmethod
-
class
asyncpg_simpleorm.AsyncContextManagerABC[source]¶ Bases:
objectAbstract representation of an async context manager.
Ensures a class has
__aenter__and__aexit__methods.
-
class
asyncpg_simpleorm.ModelABC[source]¶ Bases:
objectAbstract reperesentation of a database model.
-
class
asyncpg_simpleorm.StatementABC[source]¶ Bases:
objectAbstract representation of a database query statement.
-
model¶ Return the model set on an instance.
-
abstractmethod
query()[source]¶ Return an iterable that can be used in an
asyncpgquery. The first value should be thequery_string, followed by the flattened query args.Return type: Iterable[Any]
-
abstractmethod
query_args()[source]¶ Return the query arguments set on an instance.
Return type: Iterable[Any]
-
-
class
asyncpg_simpleorm.AsyncModel(**kwargs)[source]¶ Bases:
asyncpg_simpleorm.async_model.BaseModelExtends the
BaseModelclass to include helpful database queries.By default
getandget_onemethods returnasyncpg.Recordinstances. This option can be toggled class wide, by setting a class attribute_return_recordstoFalseon a subclass, or can be toggled during a single method call (seegetmethods for details).This class uses the
__init_subclass__syntax new inpython-3.6. That allowskwargsto be passed into the class declaration.A user should subclass this providing a
ConnectionManagerorPoolManagerto provide the database connection.Raises: RuntimeError – If subclass does not provide a connectionkwarg in the class declaration.Example:
''' The following example would be for a postgres table created by. CREATE TABLE users ( _id uuid PRIMARY KEY, name varchar(100) NOT NULL ) ''' import uuid DBURI = 'postgres://user:password@localhost:5432/database' class User(AsyncModel, connection=ConnectionManager(DBURI)): __tablename__ = 'users' id = Column('_id', primary_key=True, default=uuid.uuid4) name = Column() # Or using a ``PoolManager``. class User(AsyncModel, connection=PoolManager(DBURI)): ... # Create an instance using ``kwargs`` user = User(name='foo') print(user) # User(id=95ccbcd3-2ded-4ad8-9f68-d60f0b9590a9, name='foo')
-
classmethod
connection()[source]¶ Obtain the connection manager that was registered with the subclass during creation.
This is typically used with
async withto gain access to anasyncpg.Connectioninstance.Example:
>>> async with User.connection() as conn: # do something with the connection.
Return type: Union[ConnectionManager,PoolManager]
-
await
delete()[source]¶ Delete an instance from the database.
Raises: exceptions.ExecutionFailure – If no records were deleted from the database. Return type: None
-
classmethod
from_record()[source]¶ Return an instance of the class from an
asyncpg.Recordobject.Return type: Any
-
classmethod await
get(**kwargs)[source]¶ Get a list of the table items from the database.
Parameters: - records (
Optional[bool]) – Optional bool. IfTruethen we returnasyncpg.Record’s. IfFalsethen we will return instances of theAsyncModelsubclass. IfNone, then we default to what’s set on the subclass at the _return_records attribute (default isTrue). - kwargs – Optional kwargs that are passed into a
whereclause.
Example:
>>> await User.get(records=False) [User(id=95ccbcd3-2ded-4ad8-9f68-d60f0b9590a9, name='foo'), ...] >>> await User.get() [<Record(_id=UUID('95ccbcd3-2ded-4ad8-9f68-d60f0b9590a9'), name='foo'>, ...]
Return type: Iterable[Any]- records (
-
classmethod await
get_one(**kwargs)[source]¶ Get a single item from the database.
Parameters: - record (
Optional[bool]) – Optional bool. IfTruethen we returnasyncpg.Record’s. IfFalsethen we will return instances of theAsyncModelsubclass. IfNone, then we default to what’s set on the subclass at the _return_records attribute (default isTrue). - kwargs – Optional kwargs that are passed into a
whereclause.
Example:
>>> await User.get_one(name='foo') <Record _id=UUID('95ccbcd3-2ded-4ad8-9f68-d60f0b9590a9'), name='foo'> >>> await User.get_one(record=False, name='foo') User(id=456, name='bar')
Return type: Any- record (
-
await
save()[source]¶ Update or insert an instance to the database.
Raises: exceptions.ExecutionFailure – If no records were updated or saved to the database. Example:
>>> user = User(name='foo') >>> await user.save()
Return type: None
-
classmethod
-
class
asyncpg_simpleorm.BaseModel(**kwargs)[source]¶ Bases:
objectImplementation of
ModelABC. This class should typically not be used directly, unless building a custom statement generating class.This class allows column instance values to be set either by the attribute name the column was declared as, or the database column name (which are not always the same).
Example:
>>> class User(BaseModel): id = Column('_id', primary_key=True) name = Column() >>> u1 = User(id=123, name='foo') >>> u2 = User(_id=456, name='bar') >>> print(u1.id, u2.id) (123, 456)
Parameters: kwargs – Key word args that are set on an instance. These would typically be the same keysas the declaredColumn’s on a subclass.-
classmethod
attr_name_for_column()[source]¶ Get the class attribute name for a given database column name.
This is used when setting instance values for :class`Column`’s, and allows access to the attribute name, whether the
column_namewas parsed using the actual database column name, or the attribute name (which can be different depending on theColumn).Example:
>>> class User(BaseModel): id = Column('_id', primary_key=True) name = Column() >>> User.attr_name_for_column('_id') 'id' >>> User.attr_name_for_column('id') 'id'
Parameters: column_name ( str) – The database column name to get the attribute name for.Raises: ValueError – If no Columnis found for that column name.Return type: str
-
classmethod
column_names()[source]¶ Returns a tuple of the column names for the class.
Return type: Tuple[str]
-
classmethod
ensured_column_name()[source]¶ This is helper to always return the database column name for the input.
This is essentially the opposite of
attr_name_for_column().Example:
>>> class User(BaseModel): id = Column('_id', primary_key=True) name = Column() >>> User.ensured_column_name('_id') '_id' >>> User.ensured_column_name('id') '_id'
Parameters: column_name – The attribute name to get the column name for. Raises: ValueError – If no Columnis found for that attribute name.Return type: str
-
classmethod
-
class
asyncpg_simpleorm.Column(key: str = None, default=None, primary_key=False)[source]¶ Bases:
objectA descriptor class that represents a table column.
Parameters: - key (
Optional[str]) – The table column name in the database. If not set, then this will be set to the attribute name used on theAsyncModelsubclass the column was declared on. - default – A value or callable that is used for a default value. If this is callable, then it should recieve no input and return a value when called.
- primary_key – Set’s if the column is a primary key column. Primary
key columns are used in certain query statements, such
as
AsyncModel.save()
-
default¶
-
key¶
-
primary_key¶
- key (
-
class
asyncpg_simpleorm.ConnectionManager(*args, **kwargs)[source]¶ Bases:
asyncpg_simpleorm.abstract.AsyncContextManagerABCAn async context manager that mimics the
asyncpg.connect()function, used with subclasses ofAsyncModel.Parameters: - args – Passed to
asyncpg.connect()function. - kwargs – Passed to
asyncpg.connect()function.
- args – Passed to
-
class
asyncpg_simpleorm.PoolManager(*args, **kwargs)[source]¶ Bases:
asyncpg_simpleorm.abstract.AsyncContextManagerABCAn async context manager that mimics the
asyncpg.create_pool()function, used with subclasses ofAsyncModel.Parameters: - args – Passed to
asyncpg.create_pool()function. - kwargs – Passed to
asyncpg.create_pool()function.
- args – Passed to
-
class
asyncpg_simpleorm.BaseStatement(model, kwargs={}, arg_count: int = 1)[source]¶ Bases:
asyncpg_simpleorm.statements.abstract.StatementABCImplementation of the
StatementABC.-
count¶
-
kwargs¶
-
model¶ Return the database model set on an instance. And ensures that the model is derived from
ModelABC.Raises: .exceptions.InvalidModel – If trying to set an invalid model on an instance.
-
query_args()[source]¶ Get the query args set on the instance. This will return an empty tuple if no args have been set on the instance yet.
If args are set on the instance, then they will be returned in the order corresponding to their place holder in the
query_string.Return type: Iterable[Any]
-
query_string(sep='n')[source]¶ Get the query string set on the instance.
Parameters: sep – A seperator used to join the statement and the clauses. Defaults to ‘n’. Raises: TypeError – If a statement has not yet been set on an instance. Return type: str
-
set_count(count)[source]¶ Reset’s the counter for an instance.
Parameters: count ( int) – The number to reset the counter to.Return type: None
-
set_statement(key, query_string, args=None)[source]¶ Set the statement for an instance, and return
selffor method chaining.Return type: BaseStatement
-
-
class
asyncpg_simpleorm.Statement(model, kwargs={}, arg_count: int = 1)[source]¶ Bases:
asyncpg_simpleorm.statements.base_statement.BaseStatementExtends the
BaseStatementclass. This class is normally not instantiated directly, but returned from one of the statement factory functions.-
count¶
-
delete()[source]¶ Set’s the statement as a
DELETEstatement. This will automatically set awherestatement, using the primary keys.
-
insert(**kwargs)[source]¶ Set’s the statement as an
INSERTstatement.Parameters: kwargs – Values to use as (column names, query args) for the statement. These are probably not used much as you should normally just set the model to an instance of ModelABCfor the column names and values.
-
kwargs¶
-
update(**kwargs)[source]¶ Set’s the statement as an
UPDATEstatement. This will automatically set awherestatement, using the primary keys.Parameters: kwargs – Values to use as column names, query args for the statement. These are probably not used much as you should normally just set the model to an instance of ModelABCfor the column names and values.Raises: TypeError – If no args were able to be parsed for the statement.
-
where(primary_keys=False, safe_call=False, **kwargs)[source]¶ Add’s the
wherestring to the statement.Parameters: - primary_keys – If
True, only parse primary keys for thewherestring and args. This is primarily an implementation detail used in conjunction with other statement callbacks, and typically not necessarily set by a caller. - safe_call – An optional boolean to suppress errors. Default is
False. - kwargs – An optional mapping of column names and values to use for the where statement.
Raises: - ValueError – If not using the primary keys and the
kwargsset on the instance include an invalid key. - TypeError – If nothing was able to be parsed.
- primary_keys – If
-
-
asyncpg_simpleorm.delete(model, **kwargs)[source]¶ Delete statement factory.
Parameters: - model – A
ModelABCsubclass instance to create the statement for. - kwargs – Used for instance values, if the statement is created with a class, not an instance.
- model – A
-
asyncpg_simpleorm.insert(model=None, **kwargs)[source]¶ Insert statement factory.
Parameters: - model – A
ModelABCsubclass instance to create the statement for. - kwargs – Used for instance values, if the statement is created with a class, not an instance.
- model – A
-
asyncpg_simpleorm.select(model)[source]¶ Select statement factory.
Parameters: model – A ModelABCsubclass to create the statement for.
-
asyncpg_simpleorm.update(model=None, **kwargs)[source]¶ Update statement factory.
Parameters: - model – A
ModelABCsubclass instance to create the statement for. - kwargs – Used for instance values, if the statement is created with a class, not an instance.
- model – A
-
exception
asyncpg_simpleorm.ExecutionFailure[source]¶ Bases:
asyncpg_simpleorm.exceptions.BaseException,ValueErrorRaised if execution of a database statement fails.
-
exception
asyncpg_simpleorm.InvalidModel[source]¶ Bases:
asyncpg_simpleorm.exceptions.BaseException,TypeErrorRaised if a model does not pass an
issubclassorisinstancecheck againstModelABC.