On 12/3/15, Vincent Michel <[email protected]> wrote:
> there might be other, more powerful tools around to serve this purpose. So
> I'm also interested in comments from people with a wider view of the
> asyncio ecosystem.

Regarding the "stream style", I can share some of my
experience:

For code below, other than some limited portion
and awaits, can you see any line specific to asyncio? No?

Well that's the point. With some little search replace,
and tweaks it can easily be transformed into
equivalent multithreaded version. Even to a C++ version.

I think current form of python asyncio documentation
leads to "unnecessarily asyncio" nized projects.
With lots of "protocols, callbacks, futures, transports"..

Regards,
Imran

from lib.http import Httpd
from lib.tcp import Tcpd
from handler.man import man

handlers = [('/man/', man)]
servers = [('127.0.0.1', 90, Httpd(handlers))]
Tcpd().run(servers)


class Tcpd:
    def __init__(self):
        self.loop = l = get_event_loop()
        l.add_signal_handler(SIGINT, l.stop)
        l.add_signal_handler(SIGTERM, l.stop)

    def run(self, servers):
        for ip, port, s in servers:
            self.loop.create_task(start_server(s.handle, ip, port,
family=AF_INET, limit=4096))
        try:
            self.loop.run_forever()
        finally:
            self.loop.close()


class TcpStream:

    def __init__(self, r, w):
        self.r = r
        self.w = w

    # Read Functions
    async def read(self, l, b):
        e = b.extend
        while l:
            try:
                rd = await wait_for(self.r.read(min(l, bsize)), 20)
            except:
                rd = None
            if not rd:
                self.w.close()
                return 1
            e(rd)
            l -= len(rd)

    async def readline(self, tout=20):
        try:
            rd = await wait_for(self.r.readline(), tout)
        except:
            rd = None
        if not rd:
            self.w.close()
        return rd


class Httpd:

    def __init__(self, handlers):
        self.handlers = handlers

    async def handle(self, r, w):
        s = TcpStream(r, w)
        hs = self.handlers
        while 1:
            req = HttpReq(s)
            try:
                if await req.read():
                    return

                path = req.url.path
                for mp, h in hs:
                    l = len(mp)
                    if path[0:l] == mp:
                        req.hpath = path[l:]
                        await h(req)
                        break
                else:
                    async with req.send():
                        pass
            except:
                s.w.close()
                print_exc()
                return

Reply via email to