我已经有一段时间没遇到这个问题了。声明异步函数时:
async def init(loop):
然后我调用它返回的函数:
NameError: name 'init' is not defined
以下是代码的外观:
class Server:
def __init__(self, port):
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
loop = asyncio.get_event_loop()
server = loop.run_until_complete(init(loop))
print("Serving on {}".format(server.sockets[0].getsockname()))
try:
loop.run_forever()
except KeyboardInterrupt:
print("\rclosing the server")
pass
server.close()
loop.run_until_complete(server.wait_closed())
loop.close()
async def init(loop):
server = await loop.create_server(handle_request, '127.0.0.1', 8881)
return server
async def handle_request():
你可以指出我的任何方向都会有所帮助。 谢谢!
答案 0 :(得分:0)
似乎def init()
就在你的班级里面。通过unindenting将它移出课堂:
class Server:
def __init__(self, port):
#....
loop.close()
# IT SHOULD NOT BE HERE
#IT SHOULD BE HERE!!!
async def init(loop):
server = await loop.create_server(handle_request, '127.0.0.1', 8881)
return server