asyncio - python3.5 中使用chain coroutine
怪我咯
怪我咯 2017-04-17 17:54:10
0
1
841

想在python3.5实现chain coroutine

#!/usr/bin/env python3.5

import sqlite3
import myslice
import json
import asyncio

conn = sqlite3.connect('db.sqlite')
cursor = conn.cursor()

def user():
    cursor.execute("SELECT user_id, config, password from user")
    for row in cursor:
        item = yield row[0], json.loads(row[1]), row[2]

@asyncio.coroutine
def account():
    item = yield from user()
    user_id = item[0]
    # print(user_id)
    # c = yield cursor.execute("SELECT config from account WHERE user_id=%s" %(user_id,))
    # print(c)

def main():
    loop = asyncio.get_event_loop()
    loop.run_until_complete(account())

if __name__ == '__main__':
    main()

但是错误是RuntimeError: Task got bad yield:, 不知道怎么解决

怪我咯
怪我咯

走同样的路,发现不同的人生

Antworte allen(1)
左手右手慢动作

官方chain coroutine的例子是这样的

import asyncio

async def compute(x, y):
    print("Compute %s + %s ..." % (x, y))
    await asyncio.sleep(1.0)
    return x + y

async def print_sum(x, y):
    result = await compute(x, y)
    print("%s + %s = %s" % (x, y, result))
                
loop = asyncio.get_event_loop()
loop.run_until_complete(print_sum(1, 2))
loop.close()

async 相当于@acyncio.coroutine

很显然楼主的方法达不到实现chain coroutine, 因为协函数要把事情做完的,不能有yield
但可以这样做

#!/usr/bin/env python3.5

import sqlite3
import myslice
import json
import asyncio

conn = sqlite3.connect('db.sqlite')
cursor = conn.cursor()

@asyncio.coroutine
def user():
    ret = []
    cursor.execute("SELECT user_id, config, password from user")
    for row in cursor:
        item = row[0], json.loads(row[1]), row[2]
        ret.append(item)
    return ret

@asyncio.coroutine
def account():
    item = await user()
    user_id = item[0]
    # print(user_id)
    # c = yield cursor.execute("SELECT config from account WHERE user_id=%s" %(user_id,))
    # print(c)

def main():
    loop = asyncio.get_event_loop()
    loop.run_until_complete(account())

Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!