#!/usr/bin/env python3
import asyncio
import jinja2
import aiohttp_jinja2
import os
import __py_include
from io import StringIO
from typing import Optional
from homekit.config import config, AppConfigUnit
from homekit.util import homekit_path
from aiohttp import web
from homekit import http
from homekit.modem import ModemsConfig
class WebKbnConfig(AppConfigUnit):
NAME = 'web_kbn'
@classmethod
def schema(cls) -> Optional[dict]:
return {
'listen_addr': cls._addr_schema(required=True),
'assets_public_path': {'type': 'string'}
}
STATIC_FILES = [
'bootstrap.min.css',
'bootstrap.min.js',
'polyfills.js',
'app.js',
'app.css'
]
def get_js_link(file, version) -> str:
if version:
file += f'?version={version}'
return f''
def get_css_link(file, version) -> str:
if version:
file += f'?version={version}'
return f''
def get_head_static() -> str:
buf = StringIO()
for file in STATIC_FILES:
v = 1
try:
q_ind = file.index('?')
v = file[q_ind+1:]
file = file[:file.index('?')]
except ValueError:
pass
if file.endswith('.js'):
buf.write(get_js_link(file, v))
else:
buf.write(get_css_link(file, v))
return buf.getvalue()
class WebSite(http.HTTPServer):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
aiohttp_jinja2.setup(
self.app,
loader=jinja2.FileSystemLoader(homekit_path('web', 'kbn_templates'))
)
self.app.router.add_static('/assets/', path=homekit_path('web', 'kbn_assets'))
self.get('/main.cgi', self.get_index)
self.get('/modems.cgi', self.get_modems)
async def render_page(self,
req: http.Request,
template_name: str,
title: Optional[str] = None,
context: Optional[dict] = None):
if context is None:
context = {}
context = {
**context,
'head_static': get_head_static()
}
if title is not None:
context['title'] = title
response = aiohttp_jinja2.render_template(template_name+'.j2', req, context=context)
return response
async def get_index(self, req: http.Request):
return await self.render_page(req, 'index',
title="Home web site")
async def get_modems(self, req: http.Request):
mc = ModemsConfig()
print(mc)
return await self.render_page(req, 'modems',
title='Состояние модемов',
context=dict(modems=ModemsConfig()))
if __name__ == '__main__':
config.load_app(WebKbnConfig)
loop = asyncio.get_event_loop()
# print(config.app_config)
print(config.app_config['listen_addr'].host)
server = WebSite(config.app_config['listen_addr'])
server.run()