python web开发实战(3)--编写ORM

1、对象关系映射

ORM(英语:Object Relational Mapping,简称ORM,或O/RM,或O/R mapping),是一种程序设计技术,用于实现面向对象编程语言里不同类型系统的数据之间的转换。从效果上说,它其实是创建了一个可在编程语言里使用的“虚拟对象数据库”。
由于我们的网站基于异步io编程,系统的每一层都必须是异步。aiomysql为MySQL数据库提供了异步IO的驱动。

2、创建数据库连接池

www/orm.py

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# software: PyCharm
import logging
import aiomysql


# 打印sql执行的log
def log(sql):
    logging.info('SQL:%s ' % sql)


# 创建数据库连接池
async def create_pool(loop, **kw):
    logging.info("create the database connection pool...")
    # 双下划线开头的成员是私有的,全局变量
    global __pool
    # kw.get方法后面是默认值
    __pool = await aiomysql.create_pool(
        host=kw.get('host', 'localhost'),
        port=kw.get('port', 3306),
        user=kw['user'],
        password=kw['password'],
        db=kw['db'],
        charset=kw.get('charset', 'utf8'),
        autocommit=kw.get('autocommit', True),
        maxsize=kw.get('maxsize', 10),
        minsize=kw.get('minsize', 1),
        loop=loop
    )

3、数据库事务(增、删、改、查)封装

www/orm.py

数据库事务参考:https://aiomysql.readthedocs.io/en/latest/connection.html#connection

# 数据库操作-查找
async def select(sql, args, size=None):
    log(sql)
    # 从线程池获取数据库连接
    async with __pool.acquire() as conn:
        # 使用connection创建游标协程
        async with conn.cursor(aiomysql.DictCursor) as cur:
            # 执行指定的sql语句操作(args是元组或者列表)
            await cur.execute(sql.replace('?', '%s'), args or ())
            if size:
                rs = await cur.fetchmany(size)
            else:
                rs = await cur.fetchall()
            await cur.close()
        logging.info('rows returned: %s' % len(rs))
        return rs


# 数据库操作-增删改
async def execute(sql, args, autocommit=True):
    log(sql)
    async with __pool.acquire() as conn:
        if not autocommit:
            # 开始数据库操作(事务)的协程
            await conn.begin()
        try:
            async with conn.cursor(aiomysql.DictCursor) as cur:
                await cur.execute(sql.re
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值