def get_data(ctx): """Get aux data from the database about this event.""" pgconn = get_dbconn("postgis") cursor = pgconn.cursor() table = "warnings_%s" % (ctx["year"], ) cursor.execute( """ SELECT max(report) as r, sumtxt(name::text || ', ') as cnties from """ + table + """ w JOIN ugcs u on (w.gid = u.gid) WHERE w.wfo = %s and phenomena = %s and significance = %s and eventid = %s """, ( ctx["wfo4"][-3:], ctx["phenomena"], ctx["significance"], ctx["eventid"], ), ) row = cursor.fetchone() ctx["report"] = ("" if row[0] is None else html_escape(row[0].replace( "\001", ""))) ctx["desc"] = "" if row[1] is None else html_escape(row[1][:-2])
def get_data(ctx): """Get aux data from the database about this event.""" pgconn = get_dbconn("postgis") cursor = pgconn.cursor() table = "warnings_%s" % (ctx["year"], ) cursor.execute( ("SELECT max(report) as r, sumtxt(name::text || ', ') as cnties, " "max(case when is_emergency then 1 else 0 end), " "max(case when is_pds then 1 else 0 end) from " f"{table} w JOIN ugcs u on (w.gid = u.gid) WHERE " "w.wfo = %s and phenomena = %s and significance = %s " "and eventid = %s"), ( ctx["wfo4"][-3:], ctx["phenomena"], ctx["significance"], int(ctx["eventid"]), ), ) row = cursor.fetchone() ctx["report"] = ("" if row[0] is None else html_escape(row[0].replace( "\001", ""))) ctx["desc"] = "" if row[1] is None else html_escape(row[1][:-2]) ctx["is_emergency"] = row[2] == 1 ctx["is_pds"] = row[3] == 1
def application(environ, start_response): """Answer request.""" fields = parse_formvars(environ) wfo = fields.get("wfo", "MPX") if len(wfo) == 4: wfo = wfo[1:] year = int(fields.get("year", 2015)) phenomena = fields.get("phenomena") significance = fields.get("significance") cb = fields.get("callback") combo = int(fields.get("combo", 0)) mckey = "/json/vtec_events/%s/%s/%s/%s/%s" % ( wfo, year, phenomena, significance, combo, ) mc = memcache.Client(["iem-memcached:11211"], debug=0) res = mc.get(mckey) if not res: res = run(wfo, year, phenomena, significance, combo) mc.set(mckey, res, 60) if cb is None: data = res else: data = "%s(%s)" % (html_escape(cb), res) headers = [("Content-type", "application/json")] start_response("200 OK", headers) return [data.encode("ascii")]
def application(environ, start_response): """Main()""" headers = [("Content-type", "application/json")] form = parse_formvars(environ) network = form.get("network", "IACLIMATE").upper() month = int(form.get("month", 1)) day = int(form.get("day", 1)) syear = int(form.get("syear", 1800)) eyear = int(form.get("eyear", datetime.datetime.now().year + 1)) cb = form.get("callback", None) mckey = "/geojson/climodat_dayclimo/%s/%s/%s/%s/%s" % ( network, month, day, syear, eyear, ) mc = memcache.Client(["iem-memcached:11211"], debug=0) res = mc.get(mckey) if not res: res = run(network, month, day, syear, eyear) mc.set(mckey, res, 86400) if cb is None: data = res else: data = "%s(%s)" % (html_escape(cb), res) start_response("200 OK", headers) return [data.encode("ascii")]
def application(environ, start_response): """Answer request.""" fields = parse_formvars(environ) state = fields.get("state", "IA")[:2] year = int(fields.get("year", 2015)) phenomena = fields.get("phenomena", "SV")[:2] significance = fields.get("significance", "W")[:1] cb = fields.get("callback") mckey = "/json/vtec_events_bystate/%s/%s/%s/%s" % ( state, year, phenomena, significance, ) mc = memcache.Client(["iem-memcached:11211"], debug=0) res = mc.get(mckey) if not res: res = run(state, year, phenomena, significance) mc.set(mckey, res, 60) if cb is None: data = res else: data = "%s(%s)" % (html_escape(cb), res) headers = [("Content-type", "application/json")] start_response("200 OK", headers) return [data.encode("ascii")]
def get_jabbers(self, _uri, _uri2=None): """ get jabber messages """ res = [] for report in self.reports: if report.is_duplicate or report.valid is None: continue jmsg = { "priority": "Urgent" if report.priority == Priority.UUA else "Routine", "ts": report.valid.strftime("%H%M"), "report": html_escape(report.text), "color": ( "#ff0000" if report.priority == Priority.UUA else "#00ff00" ), } plain = "%(priority)s pilot report at %(ts)sZ: %(report)s" % jmsg html = ( "<span style='color:%(color)s;'>%(priority)s pilot " "report</span> at %(ts)sZ: %(report)s" ) % jmsg xtra = { "channels": ( f"{report.priority}.{report.cwsu},{report.priority}.PIREP" ), "geometry": "POINT(%s %s)" % (report.longitude, report.latitude), "ptype": report.priority, "category": "PIREP", "twitter": plain[:140], "valid": report.valid.strftime("%Y%m%dT%H:%M:00"), } res.append([plain, html, xtra]) return res
def application(environ, start_response): """Answer request.""" fields = parse_formvars(environ) station = fields.get("station", "AMW") network = fields.get("network", "IA_ASOS") date = fields.get("date", "2016-01-01") cb = fields.get("callback", None) hostname = os.environ.get("SERVER_NAME", "") mckey = "/json/obhistory/%s/%s/%s" % (station, network, date) mc = memcache.Client(["iem-memcached:11211"], debug=0) res = mc.get(mckey) if hostname != "iem.local" else None if not res: res = workflow(station, network, date).replace("NaN", "null") mc.set(mckey, res, 3600) if cb is None: data = res else: data = "%s(%s)" % (html_escape(cb), res) headers = [("Content-type", "application/json")] start_response("200 OK", headers) return [data.encode("ascii")]
def application(environ, start_response): """Answer request.""" fields = parse_formvars(environ) pgconn = get_dbconn("afos") acursor = pgconn.cursor() pid = fields.get("product_id", "201302241937-KSLC-NOUS45-PNSSLC") cb = fields.get("callback") utc = datetime.datetime.strptime(pid[:12], "%Y%m%d%H%M") utc = utc.replace(tzinfo=pytz.UTC) pil = pid[-6:] root = {"products": []} acursor.execute( """ SELECT data from products where pil = %s and entered = %s """, (pil, utc), ) for row in acursor: root["products"].append({"data": row[0]}) if cb is None: data = json.dumps(root) else: data = "%s(%s)" % (html_escape(cb), json.dumps(root)) headers = [("Content-type", "application/json")] start_response("200 OK", headers) return [data.encode("ascii")]
def application(environ, start_response): """Answer request.""" fields = parse_formvars(environ) ts = fields.get("ts", None) lat = float(fields.get("lat", 0)) lon = float(fields.get("lon", 0)) if ts is None: ts = datetime.datetime.utcnow() else: ts = datetime.datetime.strptime(ts, "%Y%m%d%H%M") ts = ts.replace(tzinfo=pytz.UTC) cb = fields.get("callback") if lat != 0 and lon != 0: mckey = ("/json/spcwatch/%.4f/%.4f") % (lon, lat) else: mckey = "/json/spcwatch/%s" % (ts.strftime("%Y%m%d%H%M"),) mc = memcache.Client(["iem-memcached:11211"], debug=0) res = mc.get(mckey) if not res: if lat != 0 and lon != 0: res = pointquery(lon, lat) else: res = dowork(ts) mc.set(mckey, res) if cb is None: data = res else: data = "%s(%s)" % (html_escape(cb), res) headers = [("Content-type", "application/vnd.geo+json")] start_response("200 OK", headers) return [data.encode("ascii")]
def application(environ, start_response): """Answer request.""" fields = parse_formvars(environ) if environ["REQUEST_METHOD"] not in ["GET", "POST"]: headers = [("Content-type", "text/plain")] start_response("500 Internal Server Error", headers) data = "Invalid Request" return [data.encode("ascii")] cb = fields.get("callback") mckey = "/json/tms.json" mc = memcache.Client(["iem-memcached:11211"], debug=0) res = mc.get(mckey) if not res: res = run() mc.set(mckey, res, 15) if cb is None: data = res else: data = "%s(%s)" % (html_escape(cb), res) headers = [("Content-type", "application/json")] start_response("200 OK", headers) return [data.encode("ascii")]
def application(environ, start_response): """Answer request.""" fields = parse_formvars(environ) if environ["REQUEST_METHOD"] not in ["GET", "POST"]: headers = [("Content-type", "text/plain")] start_response("500 Internal Server Error", headers) data = "Invalid Request" return [data.encode("ascii")] operation = fields.get("operation", "list") callback = fields.get("callback") data = "" if callback is not None: data += "%s(" % (html_escape(callback), ) if operation == "list": data += json.dumps(list_files(fields)) elif operation == "available": data += json.dumps(available_radars(fields)) elif operation == "products": data += json.dumps(list_products(fields)) if callback is not None: data += ")" headers = [("Content-type", "application/json")] start_response("200 OK", headers) return [data.encode("ascii")]
def application(environ, start_response): """ see how we are called """ fields = parse_formvars(environ) dt = fields.get("dt", datetime.date.today().strftime("%Y-%m-%d")) ts = datetime.datetime.strptime(dt, "%Y-%m-%d") cb = fields.get("callback", None) fmt = fields.get("fmt", "geojson") headers = [] if fmt == "geojson": headers.append(("Content-type", "application/vnd.geo+json")) else: headers.append(("Content-type", "text/plain")) mckey = "/geojson/cli/%s?callback=%s&fmt=%s" % ( ts.strftime("%Y%m%d"), cb, fmt, ) mc = memcache.Client(["iem-memcached:11211"], debug=0) res = mc.get(mckey) if not res: res = get_data(ts, fmt) mc.set(mckey, res, 300) if cb is None: data = res else: data = "%s(%s)" % (html_escape(cb), res) start_response("200 OK", headers) return [data.encode("ascii")]
def application(environ, start_response): """Answer request.""" fields = parse_formvars(environ) year = int(fields.get("year", 2015)) fmt = fields.get("format", "json") if fmt not in ["json", "html"]: headers = [("Content-type", "text/plain")] start_response("500 Internal Server Error", headers) msg = "Invalid format provided." return [msg.encode("ascii")] cb = fields.get("callback", None) headers = [] if fmt == "json": headers.append(("Content-type", "application/json")) else: headers.append(("Content-type", "text/html")) mckey = "/json/vtec_max_etn/%s/%s" % (year, fmt) mc = memcache.Client(["iem-memcached:11211"], debug=0) res = mc.get(mckey) if res is None: res = run(year, fmt) mc.set(mckey, res, 3600) if cb is None: data = res else: data = "%s(%s)" % (html_escape(cb), res) start_response("200 OK", headers) return [data.encode("ascii")]
def application(environ, start_response): """Answer request.""" fields = parse_formvars(environ) sid = fields.get("station", "")[:4] if len(sid) == 3: sid = "K" + sid ts = parse_time(fields.get("ts")) pressure = int(fields.get("pressure", -1)) cb = fields.get("callback") mckey = "/json/raob/%s/%s/%s?callback=%s" % ( ts.strftime("%Y%m%d%H%M"), sid, pressure, cb, ) mc = memcache.Client(["iem-memcached:11211"], debug=0) res = mc.get(mckey) if not res: res = run(ts, sid, pressure) mc.set(mckey, res) if cb is None: data = res else: data = "%s(%s)" % (html_escape(cb), res) headers = [("Content-type", "application/json")] start_response("200 OK", headers) return [data.encode("ascii")]
def application(environ, start_response): """Do Workflow""" headers = [("Content-type", "application/vnd.geo+json")] form = parse_formvars(environ) group = form.get("group", "coop") cb = form.get("callback", None) dt = form.get("dt", datetime.date.today().strftime("%Y-%m-%d")) ts = datetime.datetime.strptime(dt, "%Y-%m-%d") ts = ts.replace(hour=12, tzinfo=pytz.utc) mckey = "/geojson/7am/%s/%s" % (dt, group) mc = memcache.Client(["iem-memcached:11211"], debug=0) res = mc.get(mckey) if not res: res = router(group, ts) mc.set(mckey, res, 15) if cb is None: data = res else: data = "%s(%s)" % (html_escape(cb), res) start_response("200 OK", headers) return [data.encode("ascii")]
def application(environ, start_response): """Answer request.""" fields = parse_formvars(environ) station = fields.get("station", "KDSM")[:4] year = int(fields.get("year", 2019)) cb = fields.get("callback") fmt = fields.get("fmt", "json") headers = [] if fmt == "json": headers.append(("Content-type", "application/json")) else: headers.append(("Content-type", "text/plain")) mckey = "/json/cli/%s/%s?callback=%s&fmt=%s" % (station, year, cb, fmt) mc = memcache.Client(["iem-memcached:11211"], debug=0) res = mc.get(mckey) if not res: res = get_data(station, year, fmt) mc.set(mckey, res, 300) if cb is None: data = res else: data = "%s(%s)" % (html_escape(cb), res) start_response("200 OK", headers) return [data.encode("ascii")]
def get_jabbers(self, uri, _uri2=None): """Return plain text and html variants for a Jabber msg Args: uri (str): URL number one needed for constructing the URI _uri2 (str): not used, but needed for the over-ride Returns: (list): List of lists, plain text, html text, xtra dict """ # convert htmlentities spcuri = html_escape(self.get_url()) center = "Storm Prediction Center" pextra = "" if self.afos == "FFGMPD": center = "Weather Prediction Center" pextra = "Precipitation " prob_extra = " " if self.watch_prob is not None: prob_extra = " [watch probability: %.0f%%] " % (self.watch_prob, ) concerning_text = "" if self.concerning is not None: concerning_text = f" concerning {self.concerning}" plain = ("%s issues Mesoscale %sDiscussion #%s%s%s%s") % ( center, pextra, self.discussion_num, concerning_text, prob_extra, spcuri, ) html = ('<p>%s issues <a href="%s">' "Mesoscale %sDiscussion #%s</a>%s%s" '(<a href="%s?pid=%s">View text</a>)</p>') % ( center, spcuri, pextra, self.discussion_num, concerning_text, prob_extra, uri, self.get_product_id(), ) channels = self.get_channels() channels.extend(["%s.%s" % (self.afos, w) for w in self.attn_wfo]) channels.extend(["%s.%s" % (self.afos, w) for w in self.attn_rfc]) channels.extend(["%s.%s" % (self.afos, w) for w in self.cwsus]) xtra = dict( channels=",".join(channels), product_id=self.get_product_id(), twitter=self.tweet(), ) return [[plain, html, xtra]]
def application(environ, start_response): """Answer request.""" fields = parse_formvars(environ) lat = float(fields.get("lat", 42.5)) lon = float(fields.get("lon", -95.5)) sdate = datetime.datetime.strptime(fields.get("sdate", "1986/1/1"), "%Y/%m/%d") edate = datetime.datetime.strptime(fields.get("edate", "2099/1/1"), "%Y/%m/%d") cb = fields.get("callback", None) fmt = fields.get("fmt", "json") df = get_df(lon, lat, sdate, edate) if fmt == "xlsx": fn = "vtec_%.4fW_%.4fN_%s_%s.xlsx" % ( 0 - lon, lat, sdate.strftime("%Y%m%d"), edate.strftime("%Y%m%d"), ) headers = [ ("Content-type", EXL), ("Content-disposition", "attachment; Filename=" + fn), ] start_response("200 OK", headers) bio = BytesIO() df.to_excel(bio, index=False) return [bio.getvalue()] if fmt == "csv": fn = "vtec_%.4fW_%.4fN_%s_%s.csv" % ( 0 - lon, lat, sdate.strftime("%Y%m%d"), edate.strftime("%Y%m%d"), ) headers = [ ("Content-type", "application/octet-stream"), ("Content-disposition", "attachment; Filename=" + fn), ] start_response("200 OK", headers) bio = StringIO() df.to_csv(bio, index=False) return [bio.getvalue().encode("utf-8")] res = to_json(df) if cb is None: data = res else: data = "%s(%s)" % (html_escape(cb), res) headers = [("Content-type", "application/json")] start_response("200 OK", headers) return [data.encode("ascii")]
def application(environ, start_response): """Answer request.""" fields = parse_formvars(environ) pgconn = get_dbconn("afos") acursor = pgconn.cursor() center = fields.get("center", "KOKX")[:4] cb = fields.get("callback") if fields.get("date") is not None: date = datetime.strptime(fields.get("date", "2020-03-15"), "%Y-%m-%d") sts = utc(date.year, date.month, date.day) ets = sts + timedelta(days=1) else: sts = datetime.strptime( fields.get("sts", "2020-03-15T00:00")[:16], "%Y-%m-%dT%H:%M" ) ets = datetime.strptime( fields.get("ets", "2020-03-16T00:00")[:16], "%Y-%m-%dT%H:%M" ) if (ets - sts) > timedelta(days=14): ets = sts + timedelta(days=14) sts = sts.replace(tzinfo=timezone.utc) ets = ets.replace(tzinfo=timezone.utc) root = {"products": []} pil_limiter = "" if int(fields.get("opt", 0)) == 1: pil_limiter = """ and substr(pil, 1, 3) in ('AQA', 'CFW', 'DGT', 'DSW', 'FFA', 'FFS', 'FFW', 'FLS', 'FLW', 'FWW', 'HLS', 'MWS', 'MWW', 'NPW', 'NOW', 'PNS', 'PSH', 'RER', 'RFW', 'RWR', 'RWS', 'SMW', 'SPS', 'SRF', 'SQW', 'SVR', 'SVS', 'TCV', 'TOR', 'TSU', 'WCN', 'WSW') """ acursor.execute( "SELECT data from products where source = %s and entered >= %s and " f"entered < %s {pil_limiter} ORDER by entered ASC", (center, sts, ets), ) for row in acursor: root["products"].append({"data": row[0]}) if cb is None: data = json.dumps(root) else: data = "%s(%s)" % (html_escape(cb), json.dumps(root)) headers = [("Content-type", "application/json")] start_response("200 OK", headers) return [data.encode("ascii")]
def application(environ, start_response): """Go Main Go.""" form = parse_formvars(environ) fn = escape(form.get("fn", "placefile_rings.txt")) headers = [ ("Content-type", "application/octet-stream"), ("Content-Disposition", f"attachment; filename={fn}"), ] start_response("200 OK", headers) # Things for the user to theoretically input: loc = html_escape(form.get("loc", "Jack Trice Stadium")) pointLat = float(form.get("lat", 42.014004)) pointLon = float(form.get("lon", -93.635773)) sio = StringIO() sio.write( ( "; This is a placefile to draw a range ring x miles from: %s\n" "; Created by Zach Hiris - 8/9/2019\n" "; Code adapted from Jonathan Scholtes (2016)\n\n\n" "Threshold: 999 \n" "Title: Rings @ %s\n" ) % (loc, loc) ) for i in range(3): distanceInMiles = float(form.get("m%s" % (i,), 100)) if distanceInMiles <= 0.00001: continue r = int(form.get("r%s" % (i,), 255)) g = int(form.get("g%s" % (i,), 255)) b = int(form.get("b%s" % (i,), 0)) a = int(form.get("a%s" % (i,), 255)) t = form.get("t%s" % (i,), "").replace("\n", "\\n") # Create the lon/lat pairs X, Y = createCircleAroundWithRadius( pointLat, pointLon, distanceInMiles ) sio.write( ("Color: %s %s %s %s\n" 'Line: 2, 0, "%s%s%.1f miles from %s" \n') % (r, g, b, a, t, "\\n" if t != "" else "", distanceInMiles, loc) ) for x, y in zip(X, Y): sio.write(" %s, %s\n" % (y, x)) sio.write("End:\n\n") return [sio.getvalue().encode("ascii")]
def application(environ, start_response): """Answer request.""" fields = parse_formvars(environ) operation = fields.get("operation", "list") callback = fields.get("callback") headers = [] data = "" if callback is not None: data = "%s(" % (html_escape(callback), ) if operation == "list": data += json.dumps(list_files(fields)) if callback is not None: data += ")" headers = [("Content-type", "application/json")] start_response("200 OK", headers) return [data.encode("ascii")]
def application(environ, start_response): """Main()""" headers = [("Content-type", "application/vnd.geo+json")] form = parse_formvars(environ) wfo = form.get("wfo", "MPX") if len(wfo) == 4: wfo = wfo[1:] year = int(form.get("year", 2015)) phenomena = form.get("phenomena", "SV")[:2] significance = form.get("significance", "W")[:1] etn = int(form.get("etn", 1)) sbw = int(form.get("sbw", 0)) lsrs = int(form.get("lsrs", 0)) cb = form.get("callback", None) mckey = ("/geojson/vtec_event/%s/%s/%s/%s/%s/%s/%s") % ( wfo, year, phenomena, significance, etn, sbw, lsrs, ) mc = memcache.Client(["iem-memcached:11211"], debug=0) res = mc.get(mckey) if not res: if lsrs == 1: res = run_lsrs(wfo, year, phenomena, significance, etn, sbw) else: if sbw == 1: res = run_sbw(wfo, year, phenomena, significance, etn) else: res = run(wfo, year, phenomena, significance, etn) mc.set(mckey, res, 3600) if cb is None: data = res else: data = "%s(%s)" % (html_escape(cb), res) start_response("200 OK", headers) return [data.encode("ascii")]
def application(environ, start_response): """Answer request.""" fields = parse_formvars(environ) count = int(fields.get("count", 10)) sort = fields.get("sort", "DESC").upper() if sort not in ["ASC", "DESC"]: return cb = fields.get("callback") res = dowork(count, sort) if cb is None: data = res else: data = "%s(%s)" % (html_escape(cb), res) headers = [("Content-type", "application/json")] start_response("200 OK", headers) return [data.encode("ascii")]
def application(environ, start_response): """Answer request.""" fields = parse_formvars(environ) cb = fields.get("callback", None) mckey = "/json/vtec_pds" mc = memcache.Client(["iem-memcached:11211"], debug=0) res = mc.get(mckey) if not res: res = run() mc.set(mckey, res, 3600) if cb is None: data = res else: data = "%s(%s)" % (html_escape(cb), res) headers = [("Content-type", "application/json")] start_response("200 OK", headers) return [data.encode("ascii")]
def application(environ, start_response): """Answer request.""" fields = parse_formvars(environ) lat = float(fields.get("lat", 42.5)) lon = float(fields.get("lon", -95.5)) sdate = datetime.datetime.strptime(fields.get("sdate", "1986/1/1"), "%Y/%m/%d") edate = datetime.datetime.strptime(fields.get("edate", "2099/1/1"), "%Y/%m/%d") cb = fields.get("callback", None) res = run(lon, lat, sdate, edate) if cb is None: data = res else: data = "%s(%s)" % (html_escape(cb), res) headers = [("Content-type", "application/json")] start_response("200 OK", headers) return [data.encode("ascii")]
def application(environ, start_response): """ see how we are called """ field = parse_formvars(environ) q = field.get("q", "snowdepth")[:10] cb = field.get("callback", None) headers = [("Content-type", "application/vnd.geo+json")] mckey = ("/geojson/recent_metar?callback=%s&q=%s") % (cb, q) mc = memcache.Client(["iem-memcached:11211"], debug=0) res = mc.get(mckey) if not res: res = get_data(q) mc.set(mckey, res, 300) if cb is None: data = res else: data = "%s(%s)" % (html_escape(cb), res) start_response("200 OK", headers) return [data.encode("ascii")]
def application(environ, start_response): """Do Main""" headers = [("Content-type", "application/vnd.geo+json")] form = parse_formvars(environ) cb = form.get("callback", None) mckey = "/geojson/sps.geojson" mc = memcache.Client(["iem-memcached:11211"], debug=0) res = mc.get(mckey) if not res: res = run() mc.set(mckey, res, 15) if cb is None: data = res else: data = "%s(%s)" % (html_escape(cb), res) start_response("200 OK", headers) return [data.encode("ascii")]
def application(environ, start_response): """Answer request.""" fields = parse_formvars(environ) wfo = fields.get("wfo", "DMX")[:4] year = int(fields.get("year", 2015)) cb = fields.get("callback") mckey = "/json/ibw_tags/v2/%s/%s" % (wfo, year) mc = memcache.Client(["iem-memcached:11211"], debug=0) res = mc.get(mckey) if not res: res = run(wfo, year) mc.set(mckey, res, 3600) if cb is None: data = res else: data = "%s(%s)" % (html_escape(cb), res) headers = [("Content-type", "application/json")] start_response("200 OK", headers) return [data.encode("ascii")]
def application(environ, start_response): """Answer request.""" fields = parse_formvars(environ) wfo = fields.get("wfo", "MPX") if len(wfo) == 4: wfo = wfo[1:] year = int(fields.get("year", 2015)) phenomena = fields.get("phenomena", "SV")[:2] significance = fields.get("significance", "W")[:1] try: etn = int(fields.get("etn", 1)) except ValueError: headers = [("Content-type", "text/plain")] start_response("500 Internal Server Error", headers) data = "Invalid ETN" return [data.encode("ascii")] cb = fields.get("callback", None) mckey = "/json/vtec_event/%s/%s/%s/%s/%s" % ( wfo, year, phenomena, significance, etn, ) mc = memcache.Client(["iem-memcached:11211"], debug=0) res = mc.get(mckey) if not res: res = run(wfo, year, phenomena, significance, etn) mc.set(mckey, res, 300) if cb is None: data = res else: data = "%s(%s)" % (html_escape(cb), res) headers = [("Content-type", "application/json")] start_response("200 OK", headers) return [data.encode("ascii")]
def application(environ, start_response): """Answer request.""" fields = parse_formvars(environ) network = fields.get("network", "IA_ASOS")[:10].upper() station = fields.get("station", "AMW")[:10].upper() cb = fields.get("callback", None) mckey = "/json/current/%s/%s" % (network, station) mc = memcache.Client(["iem-memcached:11211"], debug=0) res = mc.get(mckey) if not res: res = run(network, station) mc.set(mckey, res, 60) if cb is None: data = res else: data = "%s(%s)" % (html_escape(cb), res) headers = [("Content-type", "application/json")] start_response("200 OK", headers) return [data.encode("ascii")]