zoukankan      html  css  js  c++  java
  • aioysql(异步操作MySQL)-python

    python异步IO初探

    探索异步IO执之前,先说说IO的种类

    1. 阻塞IO最简单,即读写数据时,需要等待操作完成,才能继续执行。进阶的做法就是用多线程来处理需要IO的部分,缺点是开销会有些大。
    2. 非阻塞IO,即读写数据时,如果暂时不可读写,则立刻返回,而不等待。因为不知道什么时候是可读写的,所以轮询时可能会浪费CPU时间。
    3. IO复用,即在读写数据前,先检查哪些描述符是可读写的,再去读写。select 和 poll 就是这样做的,它们会遍历所有被监视的描述符,查看是否满足,这个检查的过程是阻塞的。而 epoll、kqueue 和/dev/poll 则做了些改进,事先注册需要检查哪些描述符的哪些事件,当状态发生变化时,内核会调用对应的回调函数,将这些描述符保存下来;下次获取可用的描述符时,直接返回这些发生变化的描述符即可。
    4. 信号驱动,即描述符就绪时,内核发送SIGIO信号,再由信号处理程序处理这些信号即可。不过信号处理的时机是从内核态返回用户态时,感觉也得把这些事件收集起来才好处理,有点想模拟IO复用了。
    5. 最后时异步IO,即读写数据时,只注册事件,内核完成读写后(读取的数据会复制到用户态),再调用事件处理函数。这整个过程都不会阻塞调用线程。

    Python 3.4 开始,标准库里又新增了 asyncio 这个模块。
    从原理上来说,它和 Tornado 其实差不多,都是注册 IO 事件,然后在 IO loop 中等待事件发生,然后调用相应的处理函数。

    aiomysql说明

    1. poll

    此库提供一个简单的连接对象用法:

    import asyncio
    import aiomysql
    
    loop = asyncio.get_event_loop()
    
    @asyncio.coroutine
    def go()
        pool = yield from aiomysql.create_pool(host='127.0.0.1', port=3306,
                                               user='root', password='',
                                               db='mysql', loop=loop)
    
        with (yield from pool) as conn:
            cur = yield from conn.cursor()
            yield from cur.execute("SELECT 10")
            # print(cur.description)
            (r,) = yield from cur.fetchone()
           assert r == 10
        pool.close()
        yield from pool.wait_closed()
    
    loop.run_until_complete(go())

    解释:
    create_pool(minsize=1, maxsize=10, loop=None, **kwargs)
    一个协程,创建连接池,连接database
    参数:
    minsize(int)最小的池子 , 反之maxsize(int)
    loop一个可选的事件循环实例,若未循环,使用 asyncio.get_event_loop()
    echo(bool)默认log执行SQL查询
    kwargs

    Class pool:最重要的是获得连接:

    with (yield from pool) as conn:
        cur = yield from conn.cursor()

    2.  aiomysql — API Reference

    connection
    该库用来连接MySQL,使用简单的aiomysql.connect(),可以连接一个数据库或者关联池子以连接更多

    import asyncio   # 举例说明
    import aiomysql
    
    loop = asyncio.get_event_loop()
    
    @asyncio.coroutine
    def test_example():
        conn = yield from aiomysql.connect(host='127.0.0.1', port=3306,
                                           user='root', password='', db='mysql',
                                           loop=loop)
    
        cur = yield from conn.cursor()
        yield from cur.execute("SELECT Host,User FROM user")
        print(cur.description)
        r = yield from cur.fetchall()
        print(r)
        yield from cur.close()
        conn.close()
    
    loop.run_until_complete(test_example())

    3. Cursors 游标

    import asyncio
    import aiomysql
    
    loop = asyncio.get_event_loop()
    
    @asyncio.coroutine
    def test_example():
        conn = yield from aiomysql.connect(host='127.0.0.1', port=3306,
                                           user='root', password='',
                                           db='mysql', loop=loop)
    
        # create default cursor
        cursor = yield from conn.cursor()
    
        # execute sql query   # 执行sql查询
        yield from cursor.execute("SELECT Host, User FROM user")
    
        # fetch all results
        r = yield from cursor.fetchall()
    
        # detach cursor from connection
        yield from cursor.close()
    
        # close connection
        conn.close()
    
    loop.run_until_complete(test_example())



  • 相关阅读:
    android Fragment和FragmentActivity
    android 生成xml文件
    android:在ViewPager中使用Button
    android延迟执行
    android.os.NetworkOnMainThreadException 异常
    导入android工程没有R文件的解决办法
    20个常用的Java程序块
    Java中的==、equals、hasCode方法
    《head first java 》读书笔记
    【写给自己】2014-03-13
  • 原文地址:https://www.cnblogs.com/devils19/p/10689025.html
Copyright © 2011-2022 走看看