Skip to content
Snippets Groups Projects
baerparser.py 2.09 KiB
Newer Older
chrissi^'s avatar
chrissi^ committed
#!/usr/bin/python2
# -*- coding: utf-8 -*-

from bs4 import BeautifulSoup
import requests
import json
import os
import time
chrissi^'s avatar
chrissi^ committed

SmithChart's avatar
SmithChart committed
import cgitb
cgitb.enable()
print "Content-Type: application/json;charset=utf-8\n"

chrissi^'s avatar
chrissi^ committed
def tofloat(s, delim=" "):
    return float(s.split(delim)[0].replace(",", "."))

def pretty(value, unit, desc=""):
    d = {}
    d["value"] = tofloat(value)
    d["unit"] = unit
    d["desc"] = desc
    return d

def getNew():
    res = {}
    try:
        link = "http://www.wetterbaer.de/Daten/currenttm.html"
        fd = requests.get(link).text
chrissi^'s avatar
chrissi^ committed

SmithChart's avatar
SmithChart committed
        res["source"] = link
chrissi^'s avatar
chrissi^ committed

        soup = BeautifulSoup(fd, 'html.parser')
chrissi^'s avatar
chrissi^ committed

        tr = soup.find("table").find_all("tr")
chrissi^'s avatar
chrissi^ committed

        d = tr[2].find_all("td")[2].get_text().strip()
        t = tr[3].find_all("td")[2].get_text().strip()
        res["timestamp"] = d + " " + t
chrissi^'s avatar
chrissi^ committed

        res["t_curr"] =  pretty((tr[6].find_all("td")[2].find_all("font")[-1].get_text()), u"°C", "Current Temperature (+2m)")
        res["t_max"]  =  pretty(tr[6].find_all("td")[3].find_all("font")[-1].get_text(), u"°C", "Maximum Tempeature today (+2m)")
        res["t_min"]  =  pretty(tr[6].find_all("td")[4].find_all("font")[-1].get_text(), u"°C", "Minimum Tempeature today (+2m)")
chrissi^'s avatar
chrissi^ committed

        res["h_curr"] =  pretty((tr[15].find_all("td")[2].find_all("font")[-1].get_text()), u"%", "Current Humidity")
        res["h_max"]  =  pretty(tr[15].find_all("td")[4].find_all("font")[-1].get_text(), u"%", "Maximum Humidity today")
        res["h_min"]  =  pretty(tr[15].find_all("td")[3].find_all("font")[-1].get_text(), u"%", "Minimum Humidity today")
chrissi^'s avatar
chrissi^ committed

        res["error"] = "No Error"
    except requests.exceptions.ConnectionError:
        res["error"] = "Error: Could not connect to " + link
    return res

cache = "cache.json"
timeout = 15*60

curr = None
if not os.path.exists(cache) or (os.path.getmtime(cache) + timeout) < int(time.time()):
    # cache expired. getting new info
    curr = getNew()
    with open(cache, "w") as f:
        json.dump(curr, f)
else:
    # cache valid. delivering old info
    with open(cache, "r") as f:
        curr = json.load(f)



print json.dumps(curr)