From 62ae5af58994b51a47974f8cfb369f0d595d67e4 Mon Sep 17 00:00:00 2001 From: eskerda Date: Wed, 15 Jan 2025 11:47:45 +0100 Subject: [PATCH] change bicmad auth request flow instead of patching scraper.request try to make a request and auth only when getting 401ed. auth token stored on headers, and gets reused if update was called with the same scraper instance --- pybikes/bicimad.py | 26 ++++++++++---------------- 1 file changed, 10 insertions(+), 16 deletions(-) diff --git a/pybikes/bicimad.py b/pybikes/bicimad.py index 573f05217..89b889c2b 100644 --- a/pybikes/bicimad.py +++ b/pybikes/bicimad.py @@ -14,8 +14,6 @@ AUTH_URL = 'https://openapi.emtmadrid.es/v2/mobilitylabs/user/login/' FEED_URL = 'https://openapi.emtmadrid.es/v2/transport/bicimad/stations/' -cache = TSTCache(delta=3600) - class Bicimad(BikeShareSystem): authed = True @@ -32,30 +30,26 @@ def __init__(self, tag, meta, key): @staticmethod def authorize(scraper, key): - request = scraper.request - headers = { 'passkey': key['passkey'], 'x-clientid': key['clientid'], } accesstoken_content = scraper.request(AUTH_URL, headers=headers) accesstoken = json.loads(accesstoken_content)['data'][0]['accessToken'] + scraper.headers.update({'accesstoken': accesstoken}) - def _request(*args, **kwargs): - headers = kwargs.get('headers', {}) - headers.update({'accesstoken': accesstoken}) - kwargs['headers'] = headers - return request(*args, **kwargs) - - scraper.request = _request + def request(self, scraper, * args, ** kwargs): + resp = scraper.request(* args, ** kwargs) - def update(self, scraper=None): - scraper = scraper or PyBikesScraper(cache) - - Bicimad.authorize(scraper, self.key) + if scraper.last_request.status_code == 401: + self.authorize(scraper, self.key) + return self.request(scraper, * args, ** kwargs) - scraper_content = scraper.request(FEED_URL, skip_cache=True) + return resp + def update(self, scraper=None): + scraper = scraper or PyBikesScraper() + scraper_content = self.request(scraper, FEED_URL) data = json.loads(scraper_content) self.stations = [BicimadStation(s) for s in data['data']]