2022-01-22 15:23:07 +08:00
|
|
|
|
"""[Quart](https://pgjones.gitlab.io/quart/index.html) 驱动适配
|
|
|
|
|
|
|
|
|
|
```bash
|
|
|
|
|
nb driver install quart
|
|
|
|
|
# 或者
|
|
|
|
|
pip install nonebot2[quart]
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
:::tip 提示
|
|
|
|
|
本驱动仅支持服务端连接
|
|
|
|
|
:::
|
2021-02-06 10:46:17 +08:00
|
|
|
|
|
2022-01-22 15:23:07 +08:00
|
|
|
|
FrontMatter:
|
|
|
|
|
sidebar_position: 5
|
|
|
|
|
description: nonebot.drivers.quart 模块
|
2021-02-06 10:46:17 +08:00
|
|
|
|
"""
|
|
|
|
|
|
2021-12-30 12:11:31 +08:00
|
|
|
|
import asyncio
|
|
|
|
|
from functools import wraps
|
2023-07-17 15:56:27 +08:00
|
|
|
|
from typing_extensions import override
|
2023-12-10 18:12:10 +08:00
|
|
|
|
from typing import Any, Dict, List, Tuple, Union, Optional, cast
|
2021-02-06 10:34:52 +08:00
|
|
|
|
|
2024-01-26 11:12:57 +08:00
|
|
|
|
from pydantic import BaseModel
|
2021-02-06 09:41:17 +08:00
|
|
|
|
|
2021-09-18 16:11:03 +08:00
|
|
|
|
from nonebot.config import Env
|
2023-08-26 11:03:24 +08:00
|
|
|
|
from nonebot.drivers import ASGIMixin
|
2021-12-30 12:11:31 +08:00
|
|
|
|
from nonebot.exception import WebSocketClosed
|
2022-02-06 17:08:11 +08:00
|
|
|
|
from nonebot.internal.driver import FileTypes
|
2023-08-26 11:03:24 +08:00
|
|
|
|
from nonebot.drivers import Driver as BaseDriver
|
2021-09-18 16:11:03 +08:00
|
|
|
|
from nonebot.config import Config as NoneBotConfig
|
2021-12-20 15:46:23 +08:00
|
|
|
|
from nonebot.drivers import Request as BaseRequest
|
2021-09-18 16:11:03 +08:00
|
|
|
|
from nonebot.drivers import WebSocket as BaseWebSocket
|
2023-08-26 11:03:24 +08:00
|
|
|
|
from nonebot.drivers import HTTPServerSetup, WebSocketServerSetup
|
2021-02-06 09:41:17 +08:00
|
|
|
|
|
|
|
|
|
try:
|
2023-01-06 20:07:28 +08:00
|
|
|
|
import uvicorn
|
2021-02-06 09:41:17 +08:00
|
|
|
|
from quart import request as _request
|
2023-07-17 15:01:21 +08:00
|
|
|
|
from quart.ctx import WebsocketContext
|
|
|
|
|
from quart.globals import websocket_ctx
|
2021-06-10 21:52:20 +08:00
|
|
|
|
from quart import Quart, Request, Response
|
2021-12-24 23:15:28 +08:00
|
|
|
|
from quart.datastructures import FileStorage
|
2021-06-10 21:52:20 +08:00
|
|
|
|
from quart import Websocket as QuartWebSocket
|
2023-03-29 15:59:54 +08:00
|
|
|
|
except ModuleNotFoundError as e: # pragma: no cover
|
2022-04-04 10:35:14 +08:00
|
|
|
|
raise ImportError(
|
2023-06-24 14:47:35 +08:00
|
|
|
|
"Please install Quart first to use this driver. "
|
|
|
|
|
"Install with pip: `pip install nonebot2[quart]`"
|
2023-02-09 10:24:27 +08:00
|
|
|
|
) from e
|
2021-02-06 09:41:17 +08:00
|
|
|
|
|
|
|
|
|
|
2021-12-30 12:11:31 +08:00
|
|
|
|
def catch_closed(func):
|
|
|
|
|
@wraps(func)
|
|
|
|
|
async def decorator(*args, **kwargs):
|
|
|
|
|
try:
|
|
|
|
|
return await func(*args, **kwargs)
|
2021-12-30 12:50:30 +08:00
|
|
|
|
except asyncio.CancelledError:
|
2021-12-30 12:11:31 +08:00
|
|
|
|
raise WebSocketClosed(1000)
|
|
|
|
|
|
|
|
|
|
return decorator
|
|
|
|
|
|
|
|
|
|
|
2024-01-26 11:12:57 +08:00
|
|
|
|
class Config(BaseModel):
|
2022-01-22 15:23:07 +08:00
|
|
|
|
"""Quart 驱动框架设置"""
|
2021-11-22 23:21:26 +08:00
|
|
|
|
|
2021-12-28 15:19:53 +08:00
|
|
|
|
quart_reload: bool = False
|
2022-01-22 15:23:07 +08:00
|
|
|
|
"""开启/关闭冷重载"""
|
2021-10-02 15:35:15 +08:00
|
|
|
|
quart_reload_dirs: Optional[List[str]] = None
|
2022-01-22 15:23:07 +08:00
|
|
|
|
"""重载监控文件夹列表,默认为 uvicorn 默认值"""
|
2022-08-04 14:14:50 +08:00
|
|
|
|
quart_reload_delay: float = 0.25
|
2022-01-22 15:23:07 +08:00
|
|
|
|
"""重载延迟,默认为 uvicorn 默认值"""
|
2021-10-02 15:35:15 +08:00
|
|
|
|
quart_reload_includes: Optional[List[str]] = None
|
2022-01-22 15:23:07 +08:00
|
|
|
|
"""要监听的文件列表,支持 glob pattern,默认为 uvicorn 默认值"""
|
2021-10-02 15:35:15 +08:00
|
|
|
|
quart_reload_excludes: Optional[List[str]] = None
|
2022-01-22 15:23:07 +08:00
|
|
|
|
"""不要监听的文件列表,支持 glob pattern,默认为 uvicorn 默认值"""
|
2023-01-04 12:58:26 +08:00
|
|
|
|
quart_extra: Dict[str, Any] = {}
|
|
|
|
|
"""传递给 `Quart` 的其他参数。"""
|
2021-06-10 21:52:20 +08:00
|
|
|
|
|
|
|
|
|
|
2023-08-26 11:03:24 +08:00
|
|
|
|
class Driver(BaseDriver, ASGIMixin):
|
2022-01-22 15:23:07 +08:00
|
|
|
|
"""Quart 驱动框架"""
|
2021-02-06 09:41:17 +08:00
|
|
|
|
|
|
|
|
|
def __init__(self, env: Env, config: NoneBotConfig):
|
|
|
|
|
super().__init__(env, config)
|
|
|
|
|
|
2021-06-10 21:52:20 +08:00
|
|
|
|
self.quart_config = Config(**config.dict())
|
|
|
|
|
|
2023-01-04 12:58:26 +08:00
|
|
|
|
self._server_app = Quart(
|
|
|
|
|
self.__class__.__qualname__, **self.quart_config.quart_extra
|
|
|
|
|
)
|
2023-12-10 18:12:10 +08:00
|
|
|
|
self._server_app.before_serving(self._lifespan.startup)
|
|
|
|
|
self._server_app.after_serving(self._lifespan.shutdown)
|
2021-02-06 09:41:17 +08:00
|
|
|
|
|
|
|
|
|
@property
|
2023-07-17 15:56:27 +08:00
|
|
|
|
@override
|
2021-02-06 09:41:17 +08:00
|
|
|
|
def type(self) -> str:
|
2022-01-12 18:19:21 +08:00
|
|
|
|
"""驱动名称: `quart`"""
|
2021-06-10 21:52:20 +08:00
|
|
|
|
return "quart"
|
2021-02-06 09:41:17 +08:00
|
|
|
|
|
|
|
|
|
@property
|
2023-07-17 15:56:27 +08:00
|
|
|
|
@override
|
2021-02-06 09:41:17 +08:00
|
|
|
|
def server_app(self) -> Quart:
|
2022-01-12 18:19:21 +08:00
|
|
|
|
"""`Quart` 对象"""
|
2021-02-06 09:41:17 +08:00
|
|
|
|
return self._server_app
|
|
|
|
|
|
|
|
|
|
@property
|
2023-07-17 15:56:27 +08:00
|
|
|
|
@override
|
2021-02-06 09:41:17 +08:00
|
|
|
|
def asgi(self):
|
2022-01-12 18:19:21 +08:00
|
|
|
|
"""`Quart` 对象"""
|
2021-02-06 09:41:17 +08:00
|
|
|
|
return self._server_app
|
|
|
|
|
|
|
|
|
|
@property
|
2023-07-17 15:56:27 +08:00
|
|
|
|
@override
|
2021-02-06 10:34:52 +08:00
|
|
|
|
def logger(self):
|
2021-06-10 21:52:20 +08:00
|
|
|
|
"""Quart 使用的 logger"""
|
2021-02-06 09:41:17 +08:00
|
|
|
|
return self._server_app.logger
|
|
|
|
|
|
2023-07-17 15:56:27 +08:00
|
|
|
|
@override
|
2021-12-20 15:46:23 +08:00
|
|
|
|
def setup_http_server(self, setup: HTTPServerSetup):
|
2021-12-22 18:50:03 +08:00
|
|
|
|
async def _handle() -> Response:
|
|
|
|
|
return await self._handle_http(setup)
|
|
|
|
|
|
2021-12-20 15:46:23 +08:00
|
|
|
|
self._server_app.add_url_rule(
|
|
|
|
|
setup.path.path,
|
2021-12-22 18:50:03 +08:00
|
|
|
|
endpoint=setup.name,
|
2021-12-20 15:46:23 +08:00
|
|
|
|
methods=[setup.method],
|
2021-12-22 18:50:03 +08:00
|
|
|
|
view_func=_handle,
|
2021-12-20 15:46:23 +08:00
|
|
|
|
)
|
|
|
|
|
|
2023-07-17 15:56:27 +08:00
|
|
|
|
@override
|
2021-12-20 15:46:23 +08:00
|
|
|
|
def setup_websocket_server(self, setup: WebSocketServerSetup) -> None:
|
2021-12-22 18:50:03 +08:00
|
|
|
|
async def _handle() -> None:
|
|
|
|
|
return await self._handle_ws(setup)
|
|
|
|
|
|
2021-12-20 15:46:23 +08:00
|
|
|
|
self._server_app.add_websocket(
|
|
|
|
|
setup.path.path,
|
2021-12-22 18:50:03 +08:00
|
|
|
|
endpoint=setup.name,
|
|
|
|
|
view_func=_handle,
|
2021-12-20 15:46:23 +08:00
|
|
|
|
)
|
|
|
|
|
|
2023-07-17 15:56:27 +08:00
|
|
|
|
@override
|
2021-11-22 23:21:26 +08:00
|
|
|
|
def run(
|
|
|
|
|
self,
|
|
|
|
|
host: Optional[str] = None,
|
|
|
|
|
port: Optional[int] = None,
|
|
|
|
|
*,
|
|
|
|
|
app: Optional[str] = None,
|
|
|
|
|
**kwargs,
|
|
|
|
|
):
|
2022-01-12 18:19:21 +08:00
|
|
|
|
"""使用 `uvicorn` 启动 Quart"""
|
2021-02-06 10:34:52 +08:00
|
|
|
|
super().run(host, port, app, **kwargs)
|
|
|
|
|
LOGGING_CONFIG = {
|
|
|
|
|
"version": 1,
|
|
|
|
|
"disable_existing_loggers": False,
|
|
|
|
|
"handlers": {
|
|
|
|
|
"default": {
|
|
|
|
|
"class": "nonebot.log.LoguruHandler",
|
|
|
|
|
},
|
|
|
|
|
},
|
|
|
|
|
"loggers": {
|
2021-11-22 23:21:26 +08:00
|
|
|
|
"uvicorn.error": {"handlers": ["default"], "level": "INFO"},
|
2021-02-06 10:34:52 +08:00
|
|
|
|
"uvicorn.access": {
|
|
|
|
|
"handlers": ["default"],
|
|
|
|
|
"level": "INFO",
|
|
|
|
|
},
|
|
|
|
|
},
|
|
|
|
|
}
|
2021-07-23 00:51:19 +08:00
|
|
|
|
uvicorn.run(
|
|
|
|
|
app or self.server_app, # type: ignore
|
|
|
|
|
host=host or str(self.config.host),
|
|
|
|
|
port=port or self.config.port,
|
2021-12-28 15:19:53 +08:00
|
|
|
|
reload=self.quart_config.quart_reload,
|
2021-10-02 15:35:15 +08:00
|
|
|
|
reload_dirs=self.quart_config.quart_reload_dirs,
|
|
|
|
|
reload_delay=self.quart_config.quart_reload_delay,
|
|
|
|
|
reload_includes=self.quart_config.quart_reload_includes,
|
|
|
|
|
reload_excludes=self.quart_config.quart_reload_excludes,
|
2021-07-23 00:51:19 +08:00
|
|
|
|
log_config=LOGGING_CONFIG,
|
2021-11-22 23:21:26 +08:00
|
|
|
|
**kwargs,
|
|
|
|
|
)
|
2021-02-06 09:41:17 +08:00
|
|
|
|
|
2021-12-20 15:46:23 +08:00
|
|
|
|
async def _handle_http(self, setup: HTTPServerSetup) -> Response:
|
2021-02-06 09:41:17 +08:00
|
|
|
|
request: Request = _request
|
2021-12-20 15:46:23 +08:00
|
|
|
|
|
2023-06-24 14:47:35 +08:00
|
|
|
|
json = await request.get_json() if request.is_json else None
|
2021-12-24 23:15:28 +08:00
|
|
|
|
|
|
|
|
|
data = await request.form
|
|
|
|
|
files_dict = await request.files
|
|
|
|
|
files: List[Tuple[str, FileTypes]] = []
|
|
|
|
|
key: str
|
|
|
|
|
value: FileStorage
|
|
|
|
|
for key, value in files_dict.items():
|
|
|
|
|
files.append((key, (value.filename, value.stream, value.content_type)))
|
|
|
|
|
|
2021-12-20 15:46:23 +08:00
|
|
|
|
http_request = BaseRequest(
|
2021-11-22 23:21:26 +08:00
|
|
|
|
request.method,
|
2021-12-20 15:46:23 +08:00
|
|
|
|
request.url,
|
2022-05-14 21:06:57 +08:00
|
|
|
|
headers=list(request.headers.items()),
|
2021-12-20 15:46:23 +08:00
|
|
|
|
cookies=list(request.cookies.items()),
|
|
|
|
|
content=await request.get_data(
|
|
|
|
|
cache=False, as_text=False, parse_form_data=False
|
|
|
|
|
),
|
2021-12-24 23:15:28 +08:00
|
|
|
|
data=data or None,
|
|
|
|
|
json=json,
|
|
|
|
|
files=files or None,
|
2021-12-20 15:46:23 +08:00
|
|
|
|
version=request.http_version,
|
2021-11-22 23:21:26 +08:00
|
|
|
|
)
|
2021-02-06 10:34:52 +08:00
|
|
|
|
|
2021-12-20 15:46:23 +08:00
|
|
|
|
response = await setup.handle_func(http_request)
|
|
|
|
|
|
2021-11-22 23:21:26 +08:00
|
|
|
|
return Response(
|
2021-12-20 15:46:23 +08:00
|
|
|
|
response.content or "",
|
|
|
|
|
response.status_code or 200,
|
|
|
|
|
headers=dict(response.headers),
|
2021-11-22 23:21:26 +08:00
|
|
|
|
)
|
2021-02-06 09:41:17 +08:00
|
|
|
|
|
2021-12-20 15:46:23 +08:00
|
|
|
|
async def _handle_ws(self, setup: WebSocketServerSetup) -> None:
|
2023-07-17 15:01:21 +08:00
|
|
|
|
ctx = cast(WebsocketContext, websocket_ctx.copy())
|
|
|
|
|
websocket = websocket_ctx.websocket
|
2021-06-10 21:52:20 +08:00
|
|
|
|
|
2021-12-20 15:46:23 +08:00
|
|
|
|
http_request = BaseRequest(
|
|
|
|
|
websocket.method,
|
|
|
|
|
websocket.url,
|
2022-05-14 21:06:57 +08:00
|
|
|
|
headers=list(websocket.headers.items()),
|
2021-12-20 15:46:23 +08:00
|
|
|
|
cookies=list(websocket.cookies.items()),
|
|
|
|
|
version=websocket.http_version,
|
2021-11-22 23:21:26 +08:00
|
|
|
|
)
|
2021-12-20 15:46:23 +08:00
|
|
|
|
|
2023-07-17 15:01:21 +08:00
|
|
|
|
ws = WebSocket(request=http_request, websocket_ctx=ctx)
|
2021-12-20 15:46:23 +08:00
|
|
|
|
|
|
|
|
|
await setup.handle_func(ws)
|
|
|
|
|
|
|
|
|
|
|
2021-02-06 09:41:17 +08:00
|
|
|
|
class WebSocket(BaseWebSocket):
|
2022-01-22 15:23:07 +08:00
|
|
|
|
"""Quart WebSocket Wrapper"""
|
|
|
|
|
|
2023-07-17 15:01:21 +08:00
|
|
|
|
def __init__(self, *, request: BaseRequest, websocket_ctx: WebsocketContext):
|
2021-12-20 15:46:23 +08:00
|
|
|
|
super().__init__(request=request)
|
2023-07-17 15:01:21 +08:00
|
|
|
|
self.websocket_ctx = websocket_ctx
|
|
|
|
|
|
|
|
|
|
@property
|
|
|
|
|
def websocket(self) -> QuartWebSocket:
|
|
|
|
|
return self.websocket_ctx.websocket
|
2021-02-06 09:41:17 +08:00
|
|
|
|
|
|
|
|
|
@property
|
2023-07-17 15:56:27 +08:00
|
|
|
|
@override
|
2021-02-06 09:41:17 +08:00
|
|
|
|
def closed(self):
|
2021-12-21 18:22:14 +08:00
|
|
|
|
# FIXME
|
|
|
|
|
return True
|
2021-02-06 09:41:17 +08:00
|
|
|
|
|
2023-07-17 15:56:27 +08:00
|
|
|
|
@override
|
2021-02-06 09:41:17 +08:00
|
|
|
|
async def accept(self):
|
|
|
|
|
await self.websocket.accept()
|
|
|
|
|
|
2023-07-17 15:56:27 +08:00
|
|
|
|
@override
|
2021-12-21 18:22:14 +08:00
|
|
|
|
async def close(self, code: int = 1000, reason: str = ""):
|
|
|
|
|
await self.websocket.close(code, reason)
|
2021-02-06 09:41:17 +08:00
|
|
|
|
|
2023-07-17 15:56:27 +08:00
|
|
|
|
@override
|
2021-12-30 12:11:31 +08:00
|
|
|
|
@catch_closed
|
2022-05-14 21:06:57 +08:00
|
|
|
|
async def receive(self) -> Union[str, bytes]:
|
|
|
|
|
return await self.websocket.receive()
|
|
|
|
|
|
2023-07-17 15:56:27 +08:00
|
|
|
|
@override
|
2022-05-14 21:06:57 +08:00
|
|
|
|
@catch_closed
|
|
|
|
|
async def receive_text(self) -> str:
|
2021-12-20 15:46:23 +08:00
|
|
|
|
msg = await self.websocket.receive()
|
|
|
|
|
if isinstance(msg, bytes):
|
|
|
|
|
raise TypeError("WebSocket received unexpected frame type: bytes")
|
|
|
|
|
return msg
|
2021-06-10 21:52:20 +08:00
|
|
|
|
|
2023-07-17 15:56:27 +08:00
|
|
|
|
@override
|
2021-12-30 12:11:31 +08:00
|
|
|
|
@catch_closed
|
2021-06-10 21:52:20 +08:00
|
|
|
|
async def receive_bytes(self) -> bytes:
|
2021-12-20 15:46:23 +08:00
|
|
|
|
msg = await self.websocket.receive()
|
|
|
|
|
if isinstance(msg, str):
|
|
|
|
|
raise TypeError("WebSocket received unexpected frame type: str")
|
|
|
|
|
return msg
|
2021-06-10 21:52:20 +08:00
|
|
|
|
|
2023-07-17 15:56:27 +08:00
|
|
|
|
@override
|
2022-05-14 21:06:57 +08:00
|
|
|
|
async def send_text(self, data: str):
|
2021-06-10 21:52:20 +08:00
|
|
|
|
await self.websocket.send(data)
|
2021-02-06 09:41:17 +08:00
|
|
|
|
|
2023-07-17 15:56:27 +08:00
|
|
|
|
@override
|
2021-06-10 21:52:20 +08:00
|
|
|
|
async def send_bytes(self, data: bytes):
|
|
|
|
|
await self.websocket.send(data)
|
2022-01-22 15:23:07 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
__autodoc__ = {"catch_closed": False}
|