michaelliao / awesome-python3-webapp

小白的Python入门教程实战篇:网站+iOS App源码→ http://t.cn/R2PDyWN 赞助→ http://t.cn/R5bhVpf
GNU General Public License v3.0
2.37k stars 2.81k forks source link

day4测试代码出现'yield from' inside async function #47

Open ruin1990 opened 6 years ago

ruin1990 commented 6 years ago

clone工程变切换branch到day4运行以下测试代码 ` import orm from models import User, Blog, Comment

def test(): yield from orm.create_pool(user='www-data', password='www-data', database='awesome')

u = User(name='Test', email='test@example.com', passwd='1234567890', image='about:blank')

yield from u.save()

for x in test(): pass 出现了这个错误在windows上,python3.6.2 $ python test_model.py Traceback (most recent call last): File "test_model.py", line 1, in import orm File "C:\Users\Administrator\Desktop\github\awesome-python3-webapp\www\orm.py", line 16 __pool = yield from aiomysql.create_pool( ^ SyntaxError: 'yield from' inside async function ` 查了2天资料没找到问题出在哪,不知道是不是python版本的问题

Qing1998 commented 5 years ago

python 版本3.6以上才能在async里面使用yield 参考:https://stackoverflow.com/questions/47376408/why-cant-i-yield-from-inside-an-async-function?noredirect=1&lq=1 3.6以后async里面也不能用yield from,貌似是因为编译起来太费时了。 参考:https://stackoverflow.com/questions/47376408/why-cant-i-yield-from-inside-an-async-function?noredirect=1&lq=1 关于test.py原网页有学员在评论了提供了测试成功的代码 import orm from models import User,Blog,Comment import asyncio

async def test(loop): await orm.create_pool(loop,user='root',password='password',db ='python') u = User(name='Test',email ='test@example.com',passwd='123456',image='about.blank') await u.save()

if name == 'main': loop = asyncio.get_event_loop() loop.run_until_complete(test(loop)) print('Test finished.') loop.close() 但是orm.py里面也有async里面使用yield from的写法,这个我在尝试解决、、等我测试好了分享

Qing1998 commented 5 years ago

接上文、主方法里面if name == ‘main’:需改为if name == 'main': orm.py里面所有的yield from我都改成了await,测试代码可运行,但不知道会不会有隐性bug、、

Qing1998 commented 5 years ago

前面的name是前后加双下划线、github给我自动转换了、

Qing1998 commented 5 years ago

main前后也要双下划线、、

jiuxiaxixi commented 5 years ago

/Users/jiuxiaxixi/.conda/envs/webapp/bin/python /Users/jiuxiaxixi/PycharmProjects/webapp/www/testModel.py Test finished. Exception ignored in: <bound method Connection.del of <aiomysql.connection.Connection object at 0x108d77c88>> Traceback (most recent call last): File "/Users/jiuxiaxixi/.conda/envs/webapp/lib/python3.6/site-packages/aiomysql/connection.py", line 1057, in del File "/Users/jiuxiaxixi/.conda/envs/webapp/lib/python3.6/site-packages/aiomysql/connection.py", line 300, in close File "/Users/jiuxiaxixi/.conda/envs/webapp/lib/python3.6/asyncio/selector_events.py", line 621, in close File "/Users/jiuxiaxixi/.conda/envs/webapp/lib/python3.6/asyncio/base_events.py", line 580, in call_soon File "/Users/jiuxiaxixi/.conda/envs/webapp/lib/python3.6/asyncio/base_events.py", line 366, in _check_closed RuntimeError: Event loop is closed

运行你说的代码出现如下错误

jiuxiaxixi commented 5 years ago

发现代码没有关闭 数据库的连接 已经解决