obs-portal/api/obs/bin/openbikesensor_api.py

67 lines
1.5 KiB
Python
Raw Normal View History

2021-11-04 17:13:24 +00:00
#!/usr/bin/env python3
import math
2021-11-04 17:13:24 +00:00
import sys
import os
import argparse
import asyncio
2021-11-17 18:56:40 +00:00
import logging
2021-11-04 17:13:24 +00:00
import coloredlogs
2021-11-04 17:13:24 +00:00
from obs.api.app import app
from obs.api.db import connect_db
log = logging.getLogger(__name__)
def format_size(n, b=1024):
if n == 0:
return "0 B"
if n < 0:
return "-" + format_size(n, b)
e = math.floor(math.log(n, b))
prefixes = ["", "Ki", "Mi", "Gi", "Ti"] if b == 1024 else ["", "K", "M", "G", "T"]
e = min(e, len(prefixes) - 1)
r = n / b**e
s = f"{r:0.2f}" if e > 0 else str(n)
return f"{s} {prefixes[e]}B"
class AccessLogFilter(logging.Filter):
def filter(self, record):
if not record.msg:
record.msg = (
f"{record.request} - {record.status} ({format_size(record.byte)})"
)
return True
2021-11-04 17:13:24 +00:00
def main():
2021-11-16 20:59:37 +00:00
debug = app.config.DEBUG
2021-11-17 18:56:40 +00:00
coloredlogs.install(
level=logging.DEBUG if app.config.get("VERBOSE", debug) else logging.INFO,
milliseconds=True,
isatty=True,
2021-11-17 18:56:40 +00:00
)
for ln in ["sanic.root", "sanic.error", "sanic.access"]:
l = logging.getLogger(ln)
for h in list(l.handlers):
l.removeHandler(h)
logging.getLogger("sanic.access").addFilter(AccessLogFilter())
2021-11-16 20:59:37 +00:00
app.run(
host=app.config.HOST,
port=app.config.PORT,
debug=debug,
auto_reload=app.config.get("AUTO_RELOAD", debug),
# access_log=False,
2021-11-16 20:59:37 +00:00
)
2021-11-04 17:13:24 +00:00
if __name__ == "__main__":
main()