| 1 | from urllib.request import Request, urlopen |
| 2 | from urllib.error import HTTPError |
| 3 | from bs4 import BeautifulSoup |
| 4 | |
| 5 | from meteoclimatic.exceptions import MeteoclimaticError, StationNotFound |
| 6 | from meteoclimatic import Observation |
| 7 | from meteoclimatic import __version__ |
| 8 | |
| 9 | |
| 10 | class MeteoclimaticClient(object): |
| 11 | """ |
| 12 | Entry point class providing clients for the Meteoclimatic service. |
| 13 | """ |
| 14 | |
| 15 | _base_url = "https://www.meteoclimatic.net/feed/rss/{station_code}" |
| 16 | |
| 17 | def weather_at_station(self, station_code): |
| 18 | url = self._base_url.format(station_code=station_code) |
| 19 | |
| 20 | req = Request(url, headers={"User-Agent": f"pymeteoclimatic/{__version__}"}) |
| 21 | |
| 22 | try: |
| 23 | parse_xml_url = urlopen(req) |
| 24 | except HTTPError as exc: |
| 25 | raise MeteoclimaticError( |
| 26 | "Error fetching station data [status_code=%d]" % (exc.getcode(),) |
| 27 | ) from exc |
| 28 | |
| 29 | xml_page = parse_xml_url.read() |
| 30 | parse_xml_url.close() |
| 31 | |
| 32 | soup_page = BeautifulSoup(xml_page, "xml") |
| 33 | items = soup_page.findAll("item") |
| 34 | |
| 35 | if len(items) == 0: |
| 36 | raise StationNotFound(station_code) |
| 37 | |
| 38 | observation = Observation.from_feed_item(items[0]) |
| 39 | return observation |