2022-10-12 13:39:47 +00:00
|
|
|
import asyncio
|
2022-10-13 13:01:45 +00:00
|
|
|
|
2022-10-12 13:39:47 +00:00
|
|
|
import uvicorn
|
|
|
|
from fastapi import FastAPI
|
|
|
|
|
2022-10-28 07:11:14 +00:00
|
|
|
from core.config import (
|
|
|
|
BotConfig,
|
|
|
|
config as botConfig,
|
|
|
|
)
|
2022-10-12 13:39:47 +00:00
|
|
|
from core.service import Service
|
|
|
|
|
|
|
|
__all__ = ["webapp", "WebServer"]
|
|
|
|
|
|
|
|
webapp = FastAPI(debug=botConfig.debug)
|
|
|
|
|
|
|
|
|
|
|
|
@webapp.get("/")
|
|
|
|
def index():
|
|
|
|
return {"Hello": "Paimon"}
|
|
|
|
|
|
|
|
|
|
|
|
class WebServer(Service):
|
|
|
|
debug: bool
|
|
|
|
|
|
|
|
host: str
|
|
|
|
port: int
|
|
|
|
|
|
|
|
server: uvicorn.Server
|
|
|
|
|
|
|
|
_server_task: asyncio.Task
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def from_config(cls, config: BotConfig) -> Service:
|
2022-10-28 07:11:14 +00:00
|
|
|
return cls(debug=config.debug, host=config.webserver.host, port=config.webserver.port)
|
2022-10-12 13:39:47 +00:00
|
|
|
|
|
|
|
def __init__(self, debug: bool, host: str, port: int):
|
|
|
|
self.debug = debug
|
|
|
|
self.host = host
|
|
|
|
self.port = port
|
|
|
|
|
|
|
|
self.server = uvicorn.Server(
|
2022-10-13 13:01:45 +00:00
|
|
|
uvicorn.Config(app=webapp, port=port, use_colors=False, host=host, log_config=None)
|
2022-10-12 13:39:47 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
async def start(self):
|
|
|
|
"""启动 service"""
|
|
|
|
|
|
|
|
# 暂时只在开发环境启动 webserver 用于开发调试
|
|
|
|
if not self.debug:
|
|
|
|
return
|
|
|
|
|
|
|
|
# 防止 uvicorn server 拦截 signals
|
|
|
|
self.server.install_signal_handlers = lambda: None
|
|
|
|
self._server_task = asyncio.create_task(self.server.serve())
|
|
|
|
|
|
|
|
async def stop(self):
|
|
|
|
"""关闭 service"""
|
|
|
|
if not self.debug:
|
|
|
|
return
|
|
|
|
|
|
|
|
self.server.should_exit = True
|
|
|
|
|
|
|
|
# 等待 task 结束
|
|
|
|
await self._server_task
|