Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python 3.6 coroutine was never awaited

So when ever I run my program and connect to it with the echo client it gives me this error.

Starting server
Serving on ('127.0.0.1', 8881)
Exception in callback UVTransport._call_connection_made
handle: <Handle UVTransport._call_connection_made>
Traceback (most recent call last):
File "uvloop/cbhandles.pyx", line 52, in uvloop.loop.Handle._run (uvloop/loop.c:48414)
File "uvloop/handles/tcp.pyx", line 141, in uvloop.loop.TCPTransport._call_connection_made (uvloop/loop.c:80488)
File "uvloop/handles/basetransport.pyx", line 140, in uvloop.loop.UVBaseTransport._call_connection_made (uvloop/loop.c:65774)
File "uvloop/handles/basetransport.pyx", line 137, in uvloop.loop.UVBaseTransport._call_connection_made (uvloop/loop.c:65671)
AttributeError: 'coroutine' object has no attribute 'connection_made'
/home/kenton/Programming/bridal/bridal-middle/middle/lib/server.py:16:RuntimeWarning: coroutine 'handle_request' was never awaited
loop.run_forever()

As far as I know I have everything that should be awaited awaited. Here is the code:

class Server:

    def __init__(self, port):
        asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
    loop = asyncio.get_event_loop()
    server = loop.run_until_complete(self.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(self, loop):
        server = await loop.create_server(self.handle_request, '127.0.0.1', 8881)
        return server

    async def handle_request(self):
        print(datetime.datetime.now())
        reader = asyncio.StreamReader()
        writer = asyncio.StreamWriter()
        data = await reader.read(100)
        message = data.decode()
        addr = writer.get_extra_info('peername')
        code = message.partition('-')
        if code[0].startswith("1") or code[0].startswith("5"):
            accounts = lib.settings.database.accounts
            if code[0] == "101":
                result = await self.login_101(code, accounts, writer)
            if code[0] == "501":
                result = await accounts.find_one({"username":code[2]})
                print("looking up", code[0])
            #code logic to keep asking for a valid username if one exists
                if result is None:
                    username = code[2]
                    print(username, " does not exist. Creating")
                    writer.write(b"0")
                    await writer.drain()
                    data = await reader.read(100)
                    message = data.decode()
                    code = message.partition('-')
                    post = {"username":username,"password":code[0],"email":code[2]}
                    post_id = await accounts.insert_one(post).inserted_id
                    writer.write(b(post_id))
                    await writer.drain()
        print("Closed the client socket")
        writer.close()
        print(datetime.datetime.now())
like image 750
Kenton Avatar asked Jul 09 '26 23:07

Kenton


1 Answers

Regarding your error message, the actual error is:

AttributeError: 'coroutine' object has no attribute 'connection_made'

And the line below is just a warning (RuntimeWarning: coroutine 'handle_request' was never awaited).

You might be mixing asyncio.start_server with loop.create_server().

loop.create_server()'s first parameter is protocol_factory which is a callable that returns an instance of a Protocol (and not a coroutine as in your code above):

import asyncio

class MyProtocol(asyncio.Protocol):
    def connection_made(self, transport):
        print("Connection made", transport)

    def data_received(self, data):
        print("Data received", data)

loop = asyncio.get_event_loop()
# Each client connection will create a new protocol instance
coro = loop.create_server(MyProtocol, '127.0.0.1', 8888)
server = loop.run_until_complete(coro)
loop.run_forever()

See full echo server example here.

like image 104
Udi Avatar answered Jul 13 '26 16:07

Udi