Created
August 7, 2019 21:14
-
-
Save jbylund/ba7a2effd7f73c5a6ccf657827d186b9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from json import loads as json_loads | |
| import requests | |
| import time | |
| class Windfinder(object): | |
| def __init__(self): | |
| self.cache = {} | |
| self.threshold = 3 * 60 | |
| def get_uncached(self, location): | |
| url = "https://www.windfinder.com/forecast/{}".format(location) | |
| response = requests.get(url) | |
| linegen = (x for x in response.content.split("\n")) | |
| for line in linegen: | |
| if "spotheader:" in line: | |
| break | |
| parsed = {} | |
| for line in linegen: | |
| if '</script>' in line: | |
| break | |
| line = line.strip(' ,{}') | |
| key, _, val = line.partition(':') | |
| key = key.strip() | |
| val = val.strip() | |
| if key and val: | |
| try: | |
| val = json_loads(val) | |
| except: | |
| pass | |
| parsed[key] = val | |
| return parsed | |
| def get_data(self, location): | |
| last_fetch_and_data = self.cache.get(location, (0, None)) | |
| last_fetch, data = last_fetch_and_data | |
| if self.threshold < time.time() - last_fetch: | |
| data = self.get_uncached(location) | |
| self.cache[location] = time.time(), data | |
| return data | |
| def get_windspeed(self, location): | |
| return int(round(1.15 * self.get_data(location)['ws'])) | |
| def main(): | |
| helper = Windfinder() | |
| for _ in xrange(50): | |
| print helper.get_windspeed('charles_river_basin') | |
| if "__main__" == __name__: | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment