Skip to content

Commit

Permalink
Merge ee366a5 into e0d1e31
Browse files Browse the repository at this point in the history
  • Loading branch information
liampauling committed Oct 21, 2019
2 parents e0d1e31 + ee366a5 commit e4c8ea7
Show file tree
Hide file tree
Showing 36 changed files with 831 additions and 631 deletions.
1 change: 1 addition & 0 deletions HISTORY.rst
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ Release History

- async removed from streaming (force user to handle thread)
- Black formatting on all files
- python 'Typing' added

**Bug Fixes**

Expand Down
18 changes: 9 additions & 9 deletions betfairlightweight/apiclient.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@
class APIClient(BaseClient):
def __init__(
self,
username,
password=None,
app_key=None,
certs=None,
locale=None,
cert_files=None,
lightweight=False,
username: str,
password: str = None,
app_key: str = None,
certs: str = None,
locale: str = None,
cert_files: list = None,
lightweight: bool = False,
):
"""
Creates API client for API operations.
Expand Down Expand Up @@ -47,8 +47,8 @@ def __init__(
self.race_card = endpoints.RaceCard(self)
self.historic = endpoints.Historic(self)

def __repr__(self):
def __repr__(self) -> str:
return "<APIClient [%s]>" % self.username

def __str__(self):
def __str__(self) -> str:
return "APIClient"
38 changes: 21 additions & 17 deletions betfairlightweight/baseclient.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from .exceptions import PasswordError, AppKeyError, CertsError


class BaseClient(object):
class BaseClient:
"""
Base API client
"""
Expand Down Expand Up @@ -38,13 +38,13 @@ class BaseClient(object):

def __init__(
self,
username,
password=None,
app_key=None,
certs=None,
locale=None,
cert_files=None,
lightweight=False,
username: str,
password: str = None,
app_key: str = None,
certs: str = None,
locale: str = None,
cert_files: list = None,
lightweight: bool = False,
):
"""
Creates base client for API operations.
Expand Down Expand Up @@ -76,7 +76,7 @@ def __init__(
self.get_password()
self.get_app_key()

def set_session_token(self, session_token):
def set_session_token(self, session_token: str) -> None:
"""
Sets session token and new login time.
Expand All @@ -85,7 +85,7 @@ def set_session_token(self, session_token):
self.session_token = session_token
self._login_time = datetime.datetime.now()

def get_password(self):
def get_password(self) -> str:
"""
If password is not provided will look in environment variables
for username+'password'.
Expand All @@ -95,8 +95,9 @@ def get_password(self):
self.password = os.environ.get(self.username + "password")
else:
raise PasswordError(self.username)
return self.password

def get_app_key(self):
def get_app_key(self) -> str:
"""
If app_key is not provided will look in environment
variables for username.
Expand All @@ -106,16 +107,17 @@ def get_app_key(self):
self.app_key = os.environ.get(self.username)
else:
raise AppKeyError(self.username)
return self.app_key

def client_logout(self):
def client_logout(self) -> None:
"""
Resets session token and login time.
"""
self.session_token = None
self._login_time = None

@property
def session_expired(self):
def session_expired(self) -> bool:
"""
Returns True if login_time not set or seconds since
login time is greater than 200 mins.
Expand All @@ -125,9 +127,11 @@ def session_expired(self):
or (datetime.datetime.now() - self._login_time).total_seconds() > 12000
):
return True
else:
return False

@property
def cert(self):
def cert(self) -> list:
"""
The betfair certificates, by default it looks for the
certificates in /certs/.
Expand Down Expand Up @@ -158,15 +162,15 @@ def cert(self):
return [cert, key]

@property
def login_headers(self):
def login_headers(self) -> dict:
return {
"Accept": "application/json",
"X-Application": self.app_key,
"content-type": "application/x-www-form-urlencoded",
}

@property
def keep_alive_headers(self):
def keep_alive_headers(self) -> dict:
return {
"Accept": "application/json",
"X-Application": self.app_key,
Expand All @@ -175,7 +179,7 @@ def keep_alive_headers(self):
}

@property
def request_headers(self):
def request_headers(self) -> dict:
return {
"X-Application": self.app_key,
"X-Authentication": self.session_token,
Expand Down
13 changes: 7 additions & 6 deletions betfairlightweight/compat.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import datetime
from typing import Optional
from datetime import datetime

basestring = (str, bytes)
numeric_types = (int, float)
Expand All @@ -9,21 +10,21 @@
try:
import ujson as json

def json_loads(s, **kwargs):
def json_loads(s: str, **kwargs) -> dict:
return json.loads(s, precise_float=True, **kwargs)


except ImportError:
import json

def json_loads(s, **kwargs):
def json_loads(s: str, **kwargs) -> dict:
return json.loads(s, **kwargs)


try:
import ciso8601

def parse_datetime(datetime_string):
def parse_datetime(datetime_string: str) -> Optional[datetime]:
try:
return ciso8601.parse_datetime_as_naive(datetime_string)
except ValueError:
Expand All @@ -32,8 +33,8 @@ def parse_datetime(datetime_string):

except ImportError:

def parse_datetime(datetime_string):
def parse_datetime(datetime_string: str) -> Optional[datetime]:
try:
return datetime.datetime.strptime(datetime_string, "%Y-%m-%dT%H:%M:%S.%fZ")
return datetime.strptime(datetime_string, "%Y-%m-%dT%H:%M:%S.%fZ")
except ValueError:
return
43 changes: 29 additions & 14 deletions betfairlightweight/endpoints/account.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import requests
from typing import Union, List

from .baseendpoint import BaseEndpoint
from .. import resources
from ..utils import clean_locals
Expand All @@ -12,7 +15,12 @@ class Account(BaseEndpoint):
URI = "AccountAPING/v1.0/"
connect_timeout = 6.05

def get_account_funds(self, wallet=None, session=None, lightweight=None):
def get_account_funds(
self,
wallet: str = None,
session: requests.Session = None,
lightweight: bool = None,
) -> Union[dict, resources.AccountFunds]:
"""
Get available to bet amount.
Expand All @@ -29,7 +37,9 @@ def get_account_funds(self, wallet=None, session=None, lightweight=None):
response, resources.AccountFunds, elapsed_time, lightweight
)

def get_account_details(self, session=None, lightweight=None):
def get_account_details(
self, session: requests.Session = None, lightweight: bool = None
) -> Union[dict, resources.AccountDetails]:
"""
Returns the details relating your account, including your discount
rate and Betfair point balance.
Expand All @@ -48,15 +58,15 @@ def get_account_details(self, session=None, lightweight=None):

def get_account_statement(
self,
locale=None,
from_record=None,
record_count=None,
item_date_range=time_range(),
include_item=None,
wallet=None,
session=None,
lightweight=None,
):
locale: str = None,
from_record: int = None,
record_count: int = None,
item_date_range: dict = time_range(),
include_item: str = None,
wallet: str = None,
session: requests.Session = None,
lightweight: bool = None,
) -> Union[dict, resources.AccountStatementResult]:
"""
Get account statement.
Expand All @@ -78,7 +88,12 @@ def get_account_statement(
response, resources.AccountStatementResult, elapsed_time, lightweight
)

def list_currency_rates(self, from_currency=None, session=None, lightweight=None):
def list_currency_rates(
self,
from_currency: str = None,
session: requests.Session = None,
lightweight: bool = None,
) -> Union[dict, List[resources.CurrencyRate]]:
"""
Returns a list of currency rates based on given currency
Expand All @@ -95,7 +110,7 @@ def list_currency_rates(self, from_currency=None, session=None, lightweight=None
response, resources.CurrencyRate, elapsed_time, lightweight
)

def transfer_funds(self, session=None):
def transfer_funds(self, session: requests.Session = None) -> None:
"""
Transfer funds between the UK Exchange and other wallets
Expand All @@ -109,5 +124,5 @@ def transfer_funds(self, session=None):
)

@property
def url(self):
def url(self) -> str:
return "%s%s" % (self.client.api_uri, "account/json-rpc/v1")
33 changes: 23 additions & 10 deletions betfairlightweight/endpoints/baseendpoint.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,29 @@
import datetime
from requests import ConnectionError
import requests
from typing import Union, Type

from ..baseclient import BaseClient
from ..exceptions import APIError, InvalidResponse
from ..utils import check_status_code
from ..compat import json, json_loads
from ..resources import BaseResource


class BaseEndpoint(object):
class BaseEndpoint:

connect_timeout = 3.05
read_timeout = 16
_error = APIError

def __init__(self, parent):
def __init__(self, parent: BaseClient):
"""
:param parent: API client.
"""
self.client = parent

def request(self, method, params, session):
def request(
self, method: str, params: dict, session: requests.Session
) -> (dict, float):
"""
:param str method: Betfair api-ng method to be used.
:param dict params: Params to be used in request
Expand All @@ -34,8 +39,8 @@ def request(self, method, params, session):
headers=self.client.request_headers,
timeout=(self.connect_timeout, self.read_timeout),
)
except ConnectionError:
raise APIError(None, method, params, "ConnectionError")
except requests.ConnectionError as e:
raise APIError(None, method, params, e)
except Exception as e:
raise APIError(None, method, params, e)
elapsed_time = (datetime.datetime.utcnow() - date_time_sent).total_seconds()
Expand All @@ -51,7 +56,7 @@ def request(self, method, params, session):
return response_data, elapsed_time

@staticmethod
def create_req(method, params):
def create_req(method: str, params: dict) -> str:
"""
:param method: Betfair api-ng method to be used.
:param params: Params to be used in request.
Expand All @@ -61,7 +66,9 @@ def create_req(method, params):
{"jsonrpc": "2.0", "method": method, "params": params, "id": 1}
)

def _error_handler(self, response, method=None, params=None):
def _error_handler(
self, response: dict, method: str = None, params: dict = None
) -> None:
"""
:param response: Json response.
:param params: Params to be used in request.
Expand All @@ -73,7 +80,13 @@ def _error_handler(self, response, method=None, params=None):
elif response.get("error"):
raise self._error(response, method, params)

def process_response(self, response_json, resource, elapsed_time, lightweight):
def process_response(
self,
response_json: Union[dict, list],
resource: Type[BaseResource],
elapsed_time: float,
lightweight: bool,
) -> Union[BaseResource, dict, list]:
"""
:param dict/list response_json: Response in dict format
:param BaseResource resource: Resource data structure
Expand Down Expand Up @@ -101,5 +114,5 @@ def process_response(self, response_json, resource, elapsed_time, lightweight):
raise InvalidResponse(response=result)

@property
def url(self):
def url(self) -> str:
return "%s%s" % (self.client.api_uri, "betting/json-rpc/v1")

0 comments on commit e4c8ea7

Please sign in to comment.