Discuss / Python / @get('/api/users') 错误

@get('/api/users') 错误

Topic source

老师,您handlers.py文件里面:

@get('/api/users')
def api_get_users():
    users = yield from User.findAll(orderBy='created_at desc')
    for u in users:
        u.passwd = '******'
    return dict(users=users)

可是函数findAll是用 async修饰的,yield from 不可以用,当我改成 await之后出现这种错误,老是改不了

INFO:root:create database connection pool...
INFO:root:init jinja2...
INFO:root:set jinja2 template path: D:\python_code\awesome-python3-webapp\www\templates
Traceback (most recent call last):
  File "D:\python_code\awesome-python3-webapp\www\app.py", line 128, in <module>
    loop.run_until_complete(init(loop))
  File "C:\Users\THINK\AppData\Local\Programs\Python\Python35\lib\asyncio\base_events.py", line 337,
 in run_until_complete
    return future.result()
  File "C:\Users\THINK\AppData\Local\Programs\Python\Python35\lib\asyncio\futures.py", line 274, in
result
    raise self._exception
  File "C:\Users\THINK\AppData\Local\Programs\Python\Python35\lib\asyncio\tasks.py", line 239, in _s
tep
    result = coro.send(None)
  File "D:\python_code\awesome-python3-webapp\www\app.py", line 121, in init
    add_routes(app, 'handlers')
  File "D:\python_code\awesome-python3-webapp\www\coroweb.py", line 160, in add_routes
    mod = __import__(module_name, globals(), locals())
  File "D:\python_code\awesome-python3-webapp\www\handlers.py", line 28
    users = await User.findAll(orderBy='created_at desc')
                     ^
SyntaxError: invalid syntax

您能帮忙看看是什么原因吗?谢谢!

首先handlers.pyapi_get_users()函数也需要添加:async,如下:

@get('/api/users')
async def api_get_users():
    users = await User.findAll(orderBy='created_at desc')
    for u in users:
        u.passwd = '*****'
    return dict(users=users)

后面执行后。我的情况再次报错,这次的错误来源,我将数据库的created_at设置为datetime使得app.pyresponse_factorydefault=lambda obj: obj.__dict__报错。需要人工将datetime.datetime转化为字符串

rTime=r['users'][0]['created_at'].strftime('%a, %b %d %H:%M')
r['users'][0]['created_at']=rTime

这是我的解决方案

@get('/api/users') @asyncio.coroutine def api_get_users(): users = yield from User.findAll(orderBy='created_at desc') for u in users: u.passwd = '**' return dict(users=users)


  • 1

Reply