-
Notifications
You must be signed in to change notification settings - Fork 24
/
utils.py
75 lines (63 loc) · 2.52 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import inspect
import json
import os
import re
import urllib.request
from functools import wraps
from ..errors import NotFoundError
class API:
def __init__(self, base_url, version=1):
self.BASE = base_url or 'https://api.brawlstars.com/v{}'.format(version)
self.PROFILE = self.BASE + '/players'
self.CLUB = self.BASE + '/clubs'
self.RANKINGS = self.BASE + '/rankings'
self.CONSTANTS = 'https://fourjr.herokuapp.com/bs/constants/'
path = os.path.join(os.path.dirname(__file__), os.path.pardir)
with open(os.path.join(path, '__init__.py')) as f:
self.VERSION = re.search(r'^__version__ = [\'"]([^\'"]*)[\'"]', f.read(), re.MULTILINE).group(1)
try:
data = json.loads(urllib.request.urlopen(self.CONSTANTS).read())
except (TypeError, urllib.error.HTTPError, urllib.error.URLError):
self.BRAWLERS = {}
else:
if data:
self.BRAWLERS = {b['tID'].lower(): str(b['scId'])[:2] + '0' + str(b['scId'])[2:] for b in data['characters'] if b['tID']}
else:
self.BRAWLERS = {}
def bstag(tag):
tag = tag.strip('#').upper().replace('O', '0')
allowed = '0289PYLQGRJCUV'
if len(tag) < 3:
raise NotFoundError('Tag less than 3 characters.', 404)
invalid = [c for c in tag if c not in allowed]
if invalid:
raise NotFoundError(invalid, 404)
if not tag.startswith('%23'):
tag = '%23' + tag
return tag
def typecasted(func):
'''Decorator that converts arguments via annotations.
Source: https://github.com/cgrok/clashroyale/blob/master/clashroyale/official_api/utils.py#L11'''
signature = inspect.signature(func).parameters.items()
@wraps(func)
def wrapper(*args, **kwargs):
args = list(args)
new_args = []
new_kwargs = {}
for _, param in signature:
converter = param.annotation
if converter is inspect._empty:
converter = lambda a: a # do nothing
if param.kind is param.POSITIONAL_OR_KEYWORD:
if args:
to_conv = args.pop(0)
new_args.append(converter(to_conv))
elif param.kind is param.VAR_POSITIONAL:
for a in args:
new_args.append(converter(a))
else:
for k, v in kwargs.items():
nk, nv = converter(k, v)
new_kwargs[nk] = nv
return func(*new_args, **new_kwargs)
return wrapper