izzylib-http-async/barkshark_http_async/server/transport.py
2022-02-18 16:45:32 -05:00

66 lines
1.4 KiB
Python

import asyncio
from ..dotdict import DotDict
class Transport:
def __init__(self, app, reader, writer):
self.app = app
self.reader = reader
self.writer = writer
@property
def client_address(self):
return self.writer.get_extra_info('peername')[0]
@property
def client_port(self):
return self.writer.get_extra_info('peername')[1]
@property
def closed(self):
return self.writer.is_closing()
async def read(self, length=2048, timeout=None):
return await asyncio.wait_for(self.reader.read(length), timeout or self.app.cfg.timeout)
async def readuntil(self, bytes, timeout=None):
return await asyncio.wait_for(self.reader.readuntil(bytes), timeout or self.app.cfg.timeout)
async def write(self, data):
if isinstance(data, DotDict):
data = data.to_json()
elif any(map(isinstance, [data], [dict, list, tuple])):
data = json.dumps(data)
# not sure if there's a better type to use, but this should be fine for now
elif any(map(isinstance, [data], [float, int])):
data = str(data)
elif isinstance(data, bytearray):
data = str(data)
elif not any(map(isinstance, [data], [bytes, str])):
raise TypeError('Data must be or a str, bytes, bytearray, float, it, dict, list, or tuple')
if isinstance(data, str):
data = data.encode('utf-8')
self.writer.write(data)
await self.writer.drain()
async def close(self):
if self.closed:
return
self.writer.close()
await self.writer.wait_closed()