BotZ/api/app.py

62 lines
1.4 KiB
Python

# -*- encoding: utf-8 -*-
"""
The application entrypoint.
"""
from aiohttp import web
import base64
from cryptography import fernet
import logging
import os
import typing as T
import click
from aiohttp_session import setup, session_middleware
from aiohttp_session.cookie_storage import EncryptedCookieStorage
from bot_z.async_operator import AsyncOperator
from api.rest import routes
def setup_log() -> logging.Logger:
alog = logging.getLogger("api")
alog.setLevel(os.environ.get("BOTZ_LOGLEVEL", logging.INFO))
h = logging.StreamHandler()
f = logging.Formatter("%(levelname)s [%(name)s] -> %(message)s")
h.setFormatter(f)
alog.addHandler(h)
return alog
def init_secret() -> bytes:
fernet_key = fernet.Fernet.generate_key()
return base64.urlsafe_b64decode(fernet_key)
def setup_session(app: web.Application):
secret = init_secret()
setup(app, EncryptedCookieStorage(secret))
def run(address: T.Text, port: int) -> None:
"""Application entrypoint."""
alog = setup_log()
app = web.Application(logger=alog)
setup_session(app)
app.add_routes(routes)
web.run_app(app, host=address, port=port)
@click.command()
@click.option(
"-a",
"--address",
type=click.STRING,
help="Address to bind the server to.",
default="127.0.0.1",
)
@click.option("-p", "--port", type=click.INT, help="Port to bind to", default=3003)
def cli(address: T.Text, port: int) -> None:
run(address, port)