Merge pull request #1 from Crussader/Crussader-patch-1

using orjson instead of json
This commit is contained in:
Crussader 2022-03-04 18:13:06 +04:00 committed by GitHub
commit 94ba52bfc0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 15 additions and 11 deletions

View File

@ -1,7 +1,7 @@
from __future__ import annotations from __future__ import annotations
import asyncio import asyncio
import json import orjson
import random import random
import re import re
from typing import Dict, Optional, TYPE_CHECKING from typing import Dict, Optional, TYPE_CHECKING
@ -46,7 +46,8 @@ URL_REGEX = re.compile(
r"https?://(?:www\.)?.+" r"https?://(?:www\.)?.+"
) )
JSON_ENCODER = orjson.dumps
JSON_DECODER = orjson.loads
class Node: class Node:
"""The base class for a node. """The base class for a node.
@ -85,7 +86,7 @@ class Node:
self._websocket_uri = f"{'wss' if self._secure else 'ws'}://{self._host}:{self._port}" self._websocket_uri = f"{'wss' if self._secure else 'ws'}://{self._host}:{self._port}"
self._rest_uri = f"{'https' if self._secure else 'http'}://{self._host}:{self._port}" self._rest_uri = f"{'https' if self._secure else 'http'}://{self._host}:{self._port}"
self._session = session or aiohttp.ClientSession() self._session = session or aiohttp.ClientSession(json_serialize=JSON_ENCODER)
self._websocket: aiohttp.ClientWebSocketResponse = None self._websocket: aiohttp.ClientWebSocketResponse = None
self._task: asyncio.Task = None self._task: asyncio.Task = None
@ -194,7 +195,7 @@ class Node:
if not self.is_connected: if not self.is_connected:
self._bot.loop.create_task(self.connect()) self._bot.loop.create_task(self.connect())
else: else:
self._bot.loop.create_task(self._handle_payload(msg.json())) self._bot.loop.create_task(self._handle_payload(msg.json(loads=JSON_DECODER)))
async def _handle_payload(self, data: dict): async def _handle_payload(self, data: dict):
op = data.get("op", None) op = data.get("op", None)
@ -219,7 +220,7 @@ class Node:
f"The node '{self._identifier}' is unavailable." f"The node '{self._identifier}' is unavailable."
) )
await self._websocket.send_str(json.dumps(data)) await self._websocket.send_str(orjson.dumps(data))
def get_player(self, guild_id: int): def get_player(self, guild_id: int):
"""Takes a guild ID as a parameter. Returns a pomice Player object.""" """Takes a guild ID as a parameter. Returns a pomice Player object."""
@ -284,7 +285,7 @@ class Node:
f"Failed to build track. Check if the identifier is correct and try again." f"Failed to build track. Check if the identifier is correct and try again."
) )
data: dict = await resp.json() data: dict = await resp.json(loads=JSON_DECODER)
return Track(track_id=identifier, ctx=ctx, info=data) return Track(track_id=identifier, ctx=ctx, info=data)
async def get_tracks( async def get_tracks(
@ -372,7 +373,7 @@ class Node:
url=f"{self._rest_uri}/loadtracks?identifier={quote(query)}", url=f"{self._rest_uri}/loadtracks?identifier={quote(query)}",
headers={"Authorization": self._password} headers={"Authorization": self._password}
) as response: ) as response:
data: dict = await response.json() data: dict = await response.json(loads=JSON_DECODER)
track: dict = data["tracks"][0] track: dict = data["tracks"][0]
info: dict = track.get("info") info: dict = track.get("info")
@ -397,7 +398,7 @@ class Node:
url=f"{self._rest_uri}/loadtracks?identifier={quote(query)}", url=f"{self._rest_uri}/loadtracks?identifier={quote(query)}",
headers={"Authorization": self._password} headers={"Authorization": self._password}
) as response: ) as response:
data = await response.json() data = await response.json(loads=JSON_DECODER)
load_type = data.get("loadType") load_type = data.get("loadType")

View File

@ -1,5 +1,6 @@
import re import re
import time import time
import orjson
from base64 import b64encode from base64 import b64encode
import aiohttp import aiohttp
@ -15,6 +16,8 @@ SPOTIFY_URL_REGEX = re.compile(
r"https?://open.spotify.com/(?P<type>album|playlist|track)/(?P<id>[a-zA-Z0-9]+)" r"https?://open.spotify.com/(?P<type>album|playlist|track)/(?P<id>[a-zA-Z0-9]+)"
) )
JSON_ENCODER = orjson.dumps
JSON_DECODER = orjson.loads
class Client: class Client:
"""The base client for the Spotify module of Pomice. """The base client for the Spotify module of Pomice.
@ -26,7 +29,7 @@ class Client:
self._client_id = client_id self._client_id = client_id
self._client_secret = client_secret self._client_secret = client_secret
self.session = aiohttp.ClientSession() self.session = aiohttp.ClientSession(json_serialize=JSON_ENCODER)
self._bearer_token: str = None self._bearer_token: str = None
self._expiry = 0 self._expiry = 0
@ -68,7 +71,7 @@ class Client:
f"Error while fetching results: {resp.status} {resp.reason}" f"Error while fetching results: {resp.status} {resp.reason}"
) )
data: dict = await resp.json() data: dict = await resp.json(loads=JSON_DECODER)
if spotify_type == "track": if spotify_type == "track":
return Track(data) return Track(data)
@ -93,7 +96,7 @@ class Client:
f"Error while fetching results: {resp.status} {resp.reason}" f"Error while fetching results: {resp.status} {resp.reason}"
) )
next_data: dict = await resp.json() next_data: dict = await resp.json(JSON_DECODER)
tracks += [ tracks += [
Track(track["track"]) Track(track["track"])