BotZ/api/app.py

62 lines
1.4 KiB
Python
Raw Normal View History

2019-07-30 22:52:44 +02:00
# -*- encoding: utf-8 -*-
"""
The application entrypoint.
"""
from aiohttp import web
2019-08-01 00:29:28 +02:00
import base64
from cryptography import fernet
2019-07-30 22:52:44 +02:00
import logging
import os
import typing as T
2019-08-01 00:29:28 +02:00
import click
from aiohttp_session import setup, session_middleware
from aiohttp_session.cookie_storage import EncryptedCookieStorage
2019-07-30 22:52:44 +02:00
from bot_z.async_operator import AsyncOperator
from api.rest import routes
2019-08-01 00:29:28 +02:00
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))
2019-07-30 22:52:44 +02:00
def run(address: T.Text, port: int) -> None:
"""Application entrypoint."""
2019-08-01 00:29:28 +02:00
alog = setup_log()
2019-07-30 22:52:44 +02:00
app = web.Application(logger=alog)
2019-08-01 00:29:28 +02:00
setup_session(app)
2019-07-30 22:52:44 +02:00
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)