Skip to content

Commit

Permalink
change bicmad auth request flow
Browse files Browse the repository at this point in the history
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
  • Loading branch information
eskerda committed Jan 16, 2025
1 parent bbda1ba commit 62ae5af
Showing 1 changed file with 10 additions and 16 deletions.
26 changes: 10 additions & 16 deletions pybikes/bicimad.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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']]
Expand Down

0 comments on commit 62ae5af

Please sign in to comment.