connection¶
-
aiomyorm.connection.Connection()¶ A async context manager to run a custom sql statement.
Creates new connection.Returns a Connection instance. You can also use this connection in ORM by specifying the conn parameter. If you have not set autocommit=True, you should commit manual by use
conn.commit().
-
aiomyorm.connection.Transaction()¶ Get a connection to do atomic transaction.
This is a subclass of Connection and they have the same usage, and on exit, this connection will automatically commit or roll back on error. You can also use this connection in ORM by specifying the conn parameter. Example:
async whit connection.Transaction() as conn: await Table(tl1='abc',tl2=123).save(conn=conn)
-
aiomyorm.connection.close_db_connection()¶ Close connection with database.You may sometime need it.
-
aiomyorm.connection.execute(sql: str, args: Union[list, tuple, None] = (), conn: Optional[aiomyorm.connection.Connection] = None) → int¶ Execute a insert,update or delete query, and return the number of affected rows.You can use this method when you encounter a query that ORM cannot complete.
Parameters: - sql (str) – a sql statement, use ? as placeholder.
- args (list or tuple) – argument in placeholder.
- conn – use this parameter to specify a custom connection.
Returns: (int) affected rows.
-
aiomyorm.connection.select(sql: str, args: Union[list, tuple, None] = (), conn: Optional[aiomyorm.connection.Connection] = None) → list¶ Execute a select query, and return a list of result.You can use this method when you encounter a query that ORM cannot complete
Parameters: - sql (str) – a sql statement, use ? as placeholder.
- args (list or tuple) – argument in placeholder.
- conn – use this parameter to specify a custom connection.
Returns: (list) a list of result.
field¶
-
class
aiomyorm.field.BigIntField(primary_key=False, default=0, null=False, comment='', unsigned=False)¶ Bases:
aiomyorm.field.FieldA bigint field.
-
class
aiomyorm.field.BoolField(primary_key=False, default=0, null=False, comment='')¶ Bases:
aiomyorm.field.FieldA bool field.
-
class
aiomyorm.field.DateField(primary_key=False, default=datetime.date(2022, 6, 19), null=False, comment='')¶ Bases:
aiomyorm.field.FieldA datetime field, default value is today.
-
class
aiomyorm.field.DatetimeField(primary_key=False, default=datetime.datetime(2022, 6, 19, 14, 58, 47), null=False, comment='')¶ Bases:
aiomyorm.field.FieldA datetime field, default value is now.
-
class
aiomyorm.field.DecimalField(total_digits: int = 65, decimal_digits: int = 30, primary_key=False, default=0.0, null=False, comment='')¶ Bases:
aiomyorm.field.FieldA decimal field which is more precise than float or double.
Parameters: - total_digits (int) – total digit for this float, default by 65.
- decimal_digits (int) – total decimal digit, default by 30.
-
class
aiomyorm.field.DoubleField(total_digits: int = 255, decimal_digits: int = 30, primary_key=False, default=0.0, null=False, comment='')¶ Bases:
aiomyorm.field.FieldA double field.
Parameters: - total_digits (int) – total digit for this float, default by 255.
- decimal_digits (int) – total decimal digit, default by 30.
-
class
aiomyorm.field.Field(column_type, default, primary_key=False, null=False, comment=None, unsigned=None)¶ Bases:
objectA field is a mapping of a column in mysql table.
-
column_type¶ Type of this column.
Type: str
-
primary_key¶ Whether is a primary key.
Type: bool
-
default¶ The default value of this column, it can be a real value or a function.
Type: any
-
belong_model¶ The model(table) this field(column) belongs to.
Type: str
-
comment¶ Comment of this field.
Type: str
-
null¶ Allow null value or not.
Type: bool
-
unsigned¶ Whether unsigned. Only useful in Integer.
Type: bool
-
belong_model
-
between(val1, val2)¶ Limit the value of this field between val1 and val2, Both sides of the border will be taken.
-
column_type
-
comment
-
default
-
end_with(val)¶ Constrain a string field end whit the val.
-
has(val)¶ Constrain Val in a string field.
-
like(val)¶ Fuzzy query of a string field, the format is the same as MySQL
-
null
-
primary_key
-
start_with(val)¶ Constrain a string field start whit the val.
-
unsigned
-
-
class
aiomyorm.field.FixedStringField(length: int = 255, primary_key=False, default='', null=False, comment='')¶ Bases:
aiomyorm.field.FieldA fixed length string field.
-
class
aiomyorm.field.FloatField(total_digits: int = 255, decimal_digits: int = 30, primary_key=False, default=0.0, null=False, comment='')¶ Bases:
aiomyorm.field.FieldA float field.
Parameters: - total_digits (int) – total digit for this float, default by 255.
- decimal_digits (int) – total decimal digit, default by 30.
-
class
aiomyorm.field.IntField(primary_key=False, default=0, null=False, comment='', unsigned=False)¶ Bases:
aiomyorm.field.FieldA int field.
-
class
aiomyorm.field.LongTextField(primary_key=False, default='', null=False, comment='')¶ Bases:
aiomyorm.field.FieldA long text field.
-
class
aiomyorm.field.MediumIntField(primary_key=False, default=0, null=False, comment='', unsigned=False)¶ Bases:
aiomyorm.field.FieldA mediumint field.
-
class
aiomyorm.field.MediumTextField(primary_key=False, default='', null=False, comment='')¶ Bases:
aiomyorm.field.FieldA medium text field.
-
class
aiomyorm.field.SmallIntField(primary_key=False, default=0, null=False, comment='', unsigned=False)¶ Bases:
aiomyorm.field.FieldA smallint field.
-
class
aiomyorm.field.StringField(length: int = 255, primary_key=False, default='', null=False, comment='')¶ Bases:
aiomyorm.field.FieldA string field.
Parameters: length (int) – Maximum length of string in this field, default by 255.
-
class
aiomyorm.field.TextField(primary_key=False, default='', null=False, comment='')¶ Bases:
aiomyorm.field.FieldA text field.
-
class
aiomyorm.field.TimeField(primary_key=False, default=datetime.timedelta(seconds=53927), null=False, comment='')¶ Bases:
aiomyorm.field.FieldA time field, default value is now time.
-
class
aiomyorm.field.TimestampField(primary_key=False, default=datetime.datetime(2022, 6, 19, 14, 58, 47), null=False, comment='')¶ Bases:
aiomyorm.field.FieldA timestamp field, default value is now.
-
aiomyorm.field.auto_increment()¶ Set default value to auto increment.
If you use this as default value, you should make sure this field in your database has a auto increment constrain. If you use aiomyorm to create table, auto increment constrain will be set to database.
-
aiomyorm.field.table_default(val: str = None)¶ Let default as same as table.
Parameters: - val (str) – default value in table.
- e.g. – ‘ON UPDATE CURRENT_TIMESTAMP(0)’
model¶
-
aiomyorm.model.Avg(field: aiomyorm.field.Field = None)¶
-
aiomyorm.model.Count(field=None)¶
-
aiomyorm.model.Max(field: aiomyorm.field.Field = None)¶
-
aiomyorm.model.Min(field: aiomyorm.field.Field = None)¶
-
class
aiomyorm.model.Model(_new_created: bool = True, _pk_value=None, **kwargs)¶ Bases:
dictThe basic model class.
-
__table__¶ The table name of this model.If you do not set this attribute, class name will be used by default.
-
__auto__¶ If true, fields will automatically retrieved from the table, default False. Warnings: __auto__ dose not support sqlite.
-
the field you define All the fields you define. In class it will be field while in instance it is the value of this field.
-
classmethod
aggregate(*args, group_by: Union[str, aiomyorm.field.Field, None] = None, conn=None, **kwargs) → Union[List[Dict[KT, VT]], Dict[KT, VT], NoReturn]¶ Aggregate query.
Parameters: - args –
aggregate function, it’s alias will be taken as
(function)__(field name), e.g.MAX__age. you can use the follow aggregate function:Max(), Min(), Count(), Avg(), Sum()
- group_by (str) – Same as sql, and only allow one field.
- kwargs – key is the alias of this aggregate field,and value is the aggregate function.
- conn – custom connection (this parameter is optional)
Returns: If the group_by parameter is not specified, will return a dict which key is it’s alias and value is it’s result. If the group_by parameter is specified, will return a dict which key is the result of the group_by field in each group, and value is a dict as same as the first situation.
- Sample:
you can run this code:
from model import Max,Count,Min,Avg async def run(): rs = await Test.filter(grade=3).aggregate(Max('age'), minage=Min('age'), avgage=Avg('age'), groupnum=Count(), group_by='birth_place') import pprint pprint.pprint(rs) asyncio.get_event_loop().run_until_complete(run())
you will get the result:
{'someplace': {'MAX__age': 20, 'avgage': 20.0, 'groupnum': 1, 'minage': 20}, 'someplace1': {'MAX__age': 23, 'avgage': 20.5, 'groupnum': 2, 'minage': 18}, 'someplace3': {'MAX__age': 17, 'avgage': 17.0, 'groupnum': 1, 'minage': 17}}
- args –
-
classmethod
change_db(db: str)¶ Change the database this model belongs to.
Warnings: not support sqlite
-
classmethod
change_db_one_time(db: str)¶ Change the database one time.
You can use this method temporarily change the database this model belongs in the next query or modification.
e.g.:
r = await Model.change_db_one_time(newdb).find()
This query will be performed in newdb.
Warnings: not support sqlite
-
classmethod
create_table()¶ Create this table in current database.
-
classmethod
delete(conn=None) → int¶ Delete objects from database.
You can use
filter()and other method to filter the objects that want to delete, just as you did infind().Parameters: conn – custom connection (this parameter is optional) Returns: (int) Total number of objects deleted.
-
classmethod
distinct()¶ Add DISTINCT condition for your query.
-
classmethod
exclude(**kwargs) → None¶ Exclude filter your query.
Parameters: kwargs – the field you wang to exclude and it’s value. Raises: ValueError– An error occurred when argument is not a Field.
-
classmethod
execute(sql: str, args: Union[list, tuple, None] = (), conn=None) → int¶ Execute a insert,update or delete query, and return the number of affected rows.You can use this method when you encounter a query that ORM cannot complete.
Parameters: - sql (str) – a sql statement, use ? as placeholder.
- args (list or tuple) – argument in placeholder.
- conn – use this parameter to specify a custom connection.
Returns: (int) affected rows.
-
classmethod
filter(**kwargs) → None¶ Filter your query,correspond to where key=value in sql.
Parameters: Kwargs – The field you wang to filter and it’s value. Raises: ValueError– An error occurred when argument is not a Field.
-
classmethod
find(conn=None)¶ Do select.This method will return a list of YourModel objects.
Parameters: conn – custom connection (this parameter is optional) Returns: (list) A list of YourModel objects.If no record can be found, will return an empty list.
-
classmethod
find_first(conn=None)¶ Do select.This method will directly return one YourModel object instead of a list.
Parameters: conn – custom connection (this parameter is optional) Returns: (Model) One YourModel object.If no record can be found, will return None.
-
classmethod
flex_exclude(*conditions)¶ Exclude your query flexibly, such as ‘>’ ‘<’ and so on.
Parameters: field you wang to exclude and it's value. (The) – - You can use the following methods:
- same as
flex_filtter()
Raises: ValueError– An error occurred when you use it in the wrong way.
-
classmethod
flex_filter(*conditions)¶ Filter your query flexibly, such as ‘>’ ‘<’ and so on.
Parameters: conditions – The field you wang to filter and it’s value. You can use the following methods:
flex_filter(Table.Field>100) --in sql--> where Table.Field>100 flex_filter(Table.Field>=100) --in sql--> where Table.Field>=100 flex_filter(Table.Field==100) --in sql--> where Table.Field=100 flex_filter(Table.Field<=100) --in sql--> where Table.Field<=100 flex_filter(Table.Field<100) --in sql--> where Table.Field<100 flex_filter(Table.Field.like('%abc%')) --in sql--> where Table.Field LIKE '%abc%' flex_filter(Table.Field.start_with(abc)) --in sql--> where Table.Field LIKE 'abc%' flex_filter(Table.Field.end_with(abc)) --in sql--> where Table.Field LIKE '%abc' flex_filter(Table.Field.has('abc')) --in sql--> where Table.Field LIKE '%abc%'
Raises: ValueError– An error occurred when you use it in the wrong way.
-
classmethod
get_db()¶ Get the database this model belongs to.
-
classmethod
get_fields()¶ Get the names of all fields
-
classmethod
get_mapping()¶ Get the fields mapping.
-
classmethod
get_primary_key()¶ Get the name of the primary key
-
classmethod
insert(*insert_objects, conn=None) → int¶ Insert objects to database.
This method can insert multiple objects and access the database only once.
Parameters: - insert_objects (Model) – One or more object of this Model.They must have the same format.
- conn – custom connection (this parameter is optional)
- Raise:
- ValueError: An error occurred when argument is not the object of this model. RuntimeError: An error occurred when arguments do not have the same format.
Returns: (int) Affected rows.
-
classmethod
limit(num, offset: int = 0)¶
-
classmethod
or_connect()¶ Connect your filter br ‘OR’ rather than ‘AND’.
-
classmethod
order_by(*args)¶ Sort query results.
By default, it will be sorted from small to large. You can sort it from large to small by adding ‘-‘.
Parameters: args – (str) The sorting basis you specified. Example:
User.query('id').order_by('id').find() # will sort by id from small to large User.query('id').order_by('-id').find() # will sort by id from large to small
-
classmethod
pk_find(pk_value, conn=None)¶ Get one object by primary key.
You should specify the primary key in this method. All the restrictions you have made before, except “
query()”, will not take effect. This method will directly return one YourModel object.Parameters: - pk_value – value of primary key.
- conn – custom connection (this parameter is optional)
Returns: (Model) One YourModel object.If no record can be found, will return None.
-
classmethod
query(*args) → None¶ Choice the field you want to query.
All the query method such as
find()will query all the fields by default, so if you want to query all fields, just do not use this method.Parameters: args – The field you wang to query.You can use Model.Field or the name of field. e.g.:
r = await User.query(User.id).find() r = await User.query('id').find()
Raises: ValueError– An error occurred when argument is not a Field.
-
remove(conn=None) → NoReturn¶ Remove this object from database.
Parameters: conn – custom connection (this parameter is optional) - Raise:
- RuntimeError: An error occurred when can not find a primary key of this object.
since every object queried from the database will query primary key explicitly
or implicitly, this error will only appear when the newly created object calls
the
remove()method, which itself is the wrong use. To delete an object without querying in advance, usedelete()method.
Returns: None
-
save(conn=None) → NoReturn¶ Save this object to database.
Parameters: conn – custom connection (this parameter is optional) - Raise:
- RuntimeError: An error occurred when failed to save this object.
AttributeError: An error occurred when primary key has been changed, which
is not allowed in this method, use
update().
Returns: None
-
classmethod
select(sql: str, args: Union[list, tuple, None] = (), conn=None) → list¶ Execute a select query, and turn the result into a model object. You can use this method when you encounter a query that ORM cannot complete
Parameters: - sql (str) – a sql statement, use ? as placeholder.
- args (list or tuple) – argument in placeholder.
- conn – use this parameter to specify a custom connection.
Returns: (list) a list of model objects.
-
classmethod
update(conn=None, **kwargs) → int¶ Update objects to database.
You can use
filter()and other method to filter the objects that want to update, just as you did infind().Parameters: conn – custom connection (this parameter is optional) Returns: (int) Total number of objects updated.
-
classmethod
use(conn=None)¶ Specify a connection.
-
-
class
aiomyorm.model.ModelMetaClass¶ Bases:
typeMetaclass for Model class
-
aiomyorm.model.Sum(field: aiomyorm.field.Field = None)¶
set_config¶
Config your database.
The best way is to include a config.py file in your project, and then a dict named aiomyorm, which contains your database configuration, as follow:
aiomyorm = {
'maxsize': 3,
'user': 'root',
'password': '123456',
'db': 'test',
'engine': 'mysql'
}
By default, you need to include the config.py file in the same level directory of your main file. You can call the set_config_model() method to specify the location of the config file again, as follow:
set_config_model('myconfigdirectory.myconfig')
If you don’t want to configure the config.py file, you can also call the set_config() method to configure your database connection, as follow:
set_config(engine='sqlite',
db='test.db')
- configuration options:
- common:
- engine (str) : database engine (
'mysql', 'sqlite')
- engine (str) : database engine (
- for sqlite:
- db (str) : the database file for sqlite.
- other options : same as sqlite3.
- for mysql:
- db (str) : database to use, None to not use a particular one.
- minsize (int) : minimum sizes of the pool.
- maxsize (int) : maximum sizes of the pool.
- echo (bool) : executed log SQL queryes default : False.
- debug (bool) : echo the debug log default : False.
- host (str) : host where the database server is located, default : localhost.
- port (str) : MySQL port to use, default : 3306.
- user (str) : username to log in as.
- password (str) : password to use.
- unix_socket (str) :optionally, you can use a unix socket rather than TCP/IP.
- charset (str) : charset you want to use, for example ‘utf8’.
- sql_mode: default sql-mode to use, like ‘NO_BACKSLASH_ESCAPES’
- read_default_file : specifies my.cnf file to read these parameters from under the [client] section.See aiomysql.
- conv : decoders dictionary to use instead of the default one. This is used to provide custom marshalling of types. See pymysql.converters.
- client_flag : custom flags to send to MySQL. Find potential values in pymysql.constants.CLIENT.
- use_unicode : whether or not to default to unicode strings.
- connect_timeout : Timeout in seconds before throwing an exception when connecting.
- autocommit : Autocommit mode. None means use server default. (default: False)
- ssl : Optional SSL Context to force SSL
- server_public_key : SHA256 authenticaiton plugin public key value.
- read_default_group (str) : Group to read from in the configuration file.
- no_delay (bool) : disable Nagle’s algorithm on the socket
- auth_plugin: String to manually specify the authentication plugin to use, i.e you will want to use
- mysql_clear_password when using IAM authentication with Amazon RDS. (default: Server Default)
- program_name: Program name string to provide when handshaking with MySQL. (default: sys.argv[0])
- server_public_key: SHA256 authenticaiton plugin public key value.
- loop : is an optional event loop instance, asyncio.get_event_loop() is used if loop is not specified.
- init_command (str) : initial SQL statement to run when connection is established.
default:
minsize=1,
maxsize=10,
echo=False,
debug=False,
host="localhost",
port=3306,
user=None,
password="",
db=None,
unix_socket=None,
charset='',
sql_mode=None,use_unicode=None,
read_default_file=None,
connect_timeout=None,
autocommit=False,
ssl=None,
server_public_key=None,
loop=None,
auth_plugin='',
program_name='',
read_default_group=None,
no_delay=False,
init_command=None
-
aiomyorm.set_config.set_config(**kwargs)¶ Set configs manually.
Parameters: kwargs – see module’s __doc__ configuration options.
-
aiomyorm.set_config.set_config_model(config_model)¶ Set a custom model as config model.
-
aiomyorm.set_config.set_loop(loop)¶ set a event loop.
-
aiomyorm.set_config.unset_loop(loop)¶ unset the event loop.