2021-12-22 16:53:55 +08:00
|
|
|
from nonebot.typing import overrides
|
|
|
|
from nonebot.drivers._block_driver import BlockDriver
|
|
|
|
from nonebot.drivers import (
|
|
|
|
Request,
|
|
|
|
Response,
|
|
|
|
WebSocket,
|
|
|
|
HTTPVersion,
|
|
|
|
ForwardMixin,
|
|
|
|
combine_driver,
|
|
|
|
)
|
|
|
|
|
2021-12-23 17:20:26 +08:00
|
|
|
try:
|
|
|
|
import httpx
|
|
|
|
except ImportError:
|
2021-12-25 14:04:53 +08:00
|
|
|
raise ImportError(
|
|
|
|
"Please install httpx by using `pip install nonebot2[httpx]`"
|
|
|
|
) from None
|
2021-12-23 17:20:26 +08:00
|
|
|
|
2021-12-22 16:53:55 +08:00
|
|
|
|
2021-12-23 17:20:26 +08:00
|
|
|
class Mixin(ForwardMixin):
|
2021-12-22 16:53:55 +08:00
|
|
|
@property
|
|
|
|
@overrides(ForwardMixin)
|
|
|
|
def type(self) -> str:
|
|
|
|
return "httpx"
|
|
|
|
|
|
|
|
@overrides(ForwardMixin)
|
|
|
|
async def request(self, setup: Request) -> Response:
|
|
|
|
async with httpx.AsyncClient(
|
2021-12-25 14:04:53 +08:00
|
|
|
http2=setup.version == HTTPVersion.H2,
|
|
|
|
proxies=setup.proxy,
|
|
|
|
follow_redirects=True,
|
2021-12-22 16:53:55 +08:00
|
|
|
) as client:
|
|
|
|
response = await client.request(
|
|
|
|
setup.method,
|
|
|
|
str(setup.url),
|
|
|
|
content=setup.content,
|
2021-12-24 23:15:28 +08:00
|
|
|
data=setup.data,
|
|
|
|
json=setup.json,
|
|
|
|
files=setup.files,
|
2021-12-22 16:53:55 +08:00
|
|
|
headers=tuple(setup.headers.items()),
|
|
|
|
timeout=setup.timeout,
|
|
|
|
)
|
|
|
|
return Response(
|
|
|
|
response.status_code,
|
|
|
|
headers=response.headers,
|
|
|
|
content=response.content,
|
|
|
|
request=setup,
|
|
|
|
)
|
|
|
|
|
|
|
|
@overrides(ForwardMixin)
|
|
|
|
async def websocket(self, setup: Request) -> WebSocket:
|
2021-12-23 17:20:26 +08:00
|
|
|
return await super(Mixin, self).websocket(setup)
|
2021-12-22 16:53:55 +08:00
|
|
|
|
|
|
|
|
2021-12-23 17:20:26 +08:00
|
|
|
Driver = combine_driver(BlockDriver, Mixin)
|