Skip to content

v1.1.x - Introduce async functionality #39

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 7 commits into
base: dev
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 2 additions & 5 deletions .github/workflows/library-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,14 @@ on:
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ['3.10']
env:
VALPY_KEY: ${{ secrets.VALPY_KEY }}
steps:
- uses: actions/checkout@v3
- name: Setup Python v${{ matrix.python-version }}
- name: Setup Python v3.10
uses: actions/setup-python@v3
with:
python-version: ${{ matrix.python-version }}
python-version: '3.10'
- name: Install missing dependencies
run: |
python3 -m pip install --upgrade pip
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/python-package.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: [3.8, 3.9]
python-version: ['3.8', '3.9', '3.10']

steps:
- uses: actions/checkout@v2
Expand Down
13 changes: 7 additions & 6 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
name="valorant",
license="MIT",
author="frissyn",

description=valorant.__doc__,
version=valorant.__version__,

Expand All @@ -16,23 +17,23 @@
"Source Code": url,
"Pull Requests": url + "/pulls",
"Issue Tracker": url + "/issues",
"Documentation": "https://valorantpy.readthedocs.io/"
"Documentation": "https://valorantpy.readthedocs.io/",
},

long_description=readme,
long_description_content_type="text/markdown",

python_requires=">=3.8.0",

zip_safe=False,
packages=["valorant", "valorant/local", "valorant/objects"],

packages=["valorant", "valorant/local", "valorant/objects", "valorant/callers"],

classifiers=[
"License :: OSI Approved :: MIT License",
"Intended Audience :: Developers",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Topic :: Software Development"
]
)
"Topic :: Software Development",
],
)
3 changes: 2 additions & 1 deletion valorant/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import typing as t

from .aio import AsyncClient
from .client import Client
from .lexicon import Lex
from .local import LocalClient
Expand All @@ -20,7 +21,7 @@ class Version(t.NamedTuple):
release: t.Literal["alpha", "beta", "dev"]


version_info = Version(major=1, minor=0, micro=3, release="")
version_info = Version(major=1, minor=1, micro=0, release="dev")

tag = f"-{version_info.release}" if version_info.release else ""
__version__ = ".".join(str(i) for i in version_info[:3]) + tag
44 changes: 44 additions & 0 deletions valorant/aio.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import typing as t
import urllib.parse

from .lexicon import Lex

from .callers import AsyncCaller

from .objects import (
DTO,
ActDTO,
AccountDTO,
ContentDTO,
ContentItemDTO,
LeaderboardDTO,
LeaderboardIterator,
PlatformDataDTO,
MatchDTO,
)


class AsyncClient(object):
def __init__(
self,
key: t.Text,
locale: t.Optional[t.Text] = Lex.LOCALE,
region: t.Text = "na",
route: t.Text = "americas",
):
self.key = key
self.route = route
self.locale = locale
self.region = region
self.handle = AsyncCaller(key, locale=locale, region=region, route=route)

async def _content_from_cache(self, from_cache=True):
if from_cache and getattr(self, "content", False):
return self.content
else:
self.content = ContentDTO(await self.handle.call("GET", "content"))

return self.content

async def get_content(self, cache: bool=False) -> ContentDTO:
return await self._content_from_cache(from_cache=cache)
57 changes: 0 additions & 57 deletions valorant/caller.py

This file was deleted.

11 changes: 11 additions & 0 deletions valorant/callers/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import aiohttp
import requests
import typing as t

from .async_ import AsyncCaller
from .sync import WebCaller

SessionType = t.Union[requests.Session, aiohttp.ClientSession]
CallerType = t.Union[AsyncCaller, WebCaller]

__all__ = ["AsyncCaller", "CallerType", "SessionType", "WebCaller"]
28 changes: 28 additions & 0 deletions valorant/callers/async_.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import aiohttp
import typing as t

from .base import BaseCaller


class AsyncCaller(BaseCaller):
def __init__(self, key: t.Text, **options):
self.params = {"locale": options.get("locale")}

super().__init__(key, aiohttp.ClientSession, async_=True, **options)

async def call(
self,
method: t.Text,
endpoint: t.Text,
escapes: t.Tuple[int, ...] = (),
params: t.Mapping = {},
route: t.Optional[t.Text] = False,
**extras,
) -> t.Optional[t.Mapping[str, t.Any]]:
url = self.build_url(endpoint, route, **extras)
r = await self.session.request(method, url, params=self.params.update(params))

if r.status in escapes:
return None

return r.raise_for_status() or (await r.json())
44 changes: 44 additions & 0 deletions valorant/callers/base.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import typing as t

from ..lexicon import Lex


class BaseCaller(object):
headers: t.Mapping[str, str] = {
"Accept-Charset": "application/x-www-form-urlencoded; charset=UTF-8",
"User-Agent": "Mozilla/5.0",
"X-Riot-Token": None,
}

def __init__(
self,
key: t.Text,
ctx: t.Any,
headers: t.Mapping = {},
async_: bool = False,
**options: t.Mapping,
):
self.token = key
self.async_ = async_
self.endpoints = Lex.ENDPOINTS["web"].copy()
self.base = "https://{code}.api.riotgames.com/"
self.headers["X-Riot-Token"] = key

try:
self.session = ctx(headers=self.headers)
except TypeError:
self.session = ctx()
self.session.headers = self.headers

valids = Lex.ROUTES + Lex.LOCALES + Lex.REGIONS

for name, value in options.items():
if value not in valids and not (value is None and name == 'locale'):
raise ValueError(f"'{value}' is not a valid {name}.")

self.__setattr__(name, value)

def build_url(self, endpoint: t.Text, route: t.Text, **extras) -> t.Text:
url = self.base.format(code=route if route else self.region)

return url + self.endpoints[endpoint].format(**extras)
28 changes: 28 additions & 0 deletions valorant/callers/sync.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import requests
import typing as t

from .base import BaseCaller


class WebCaller(BaseCaller):
def __init__(self, key, **options):
self.params = {"locale": options.get("locale")}

super().__init__(key, requests.Session, **options)

def call(
self,
method: t.Text,
endpoint: t.Text,
escapes: t.Tuple[int, ...] = (),
params: t.Mapping = {},
route: t.Optional[t.Text] = False,
**extras,
) -> t.Optional[t.Mapping[str, t.Any]]:
url = self.build_url(endpoint, route, **extras)
r = self.session.request(method, url, params=self.params.update(params))

if r.status_code in escapes:
return None

return r.raise_for_status() or r.json()
16 changes: 7 additions & 9 deletions valorant/client.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import requests
import typing as t
import urllib.parse

from .lexicon import Lex

from .caller import WebCaller
from .callers import WebCaller

from .objects import (
DTO,
Expand Down Expand Up @@ -66,22 +65,22 @@ def __init__(
self.route = route
self.locale = locale
self.region = region
self.handle = WebCaller(key, locale, region, route)
self.handle = WebCaller(key, locale=locale, region=region, route=route)

if load_content:
self.get_content(cache=True)
else:
self.content = None

def __getattribute__(self, name):
return super(Client, self).__getattribute__(name)

def _content_if_cache(self) -> ContentDTO:
if content := getattr(self, "content", None):
return content
else:
return ContentDTO(self.handle.call("GET", "content"))

def __getattribute__(self, name):
return super(Client, self).__getattribute__(name)

def asset(
self, **attributes: t.Mapping[t.Text, t.Any]
) -> t.Optional[t.Union[ActDTO, ContentItemDTO]]:
Expand Down Expand Up @@ -161,7 +160,7 @@ def get_chromas(self, strip: bool = False) -> t.List[ContentItemDTO]:

return chromas

def get_content(self, cache: bool = True) -> ContentDTO:
def get_content(self, cache: bool = False) -> ContentDTO:
"""Get complete content data from VALORANT.

:param cache: If set to ``True``, the Client will cache the response data,
Expand Down Expand Up @@ -377,8 +376,7 @@ def get_user_by_name(
:type route: str
:rtype: Optional[AccountDTO]
"""
vals = name.split("#")
vals = [urllib.parse.quote(v, safe=Lex.SAFES) for v in vals]
vals = [urllib.parse.quote(v, safe=Lex.SAFES) for v in name.split("#")]

r = self.handle.call(
"GET",
Expand Down
Loading