Skip to content

Instantly share code, notes, and snippets.

@zmalltalker
Created July 30, 2008 14:06
Show Gist options
  • Save zmalltalker/3265 to your computer and use it in GitHub Desktop.
Save zmalltalker/3265 to your computer and use it in GitHub Desktop.
Spike for getting weather forecasts from Yr
def openAnything(source):
"""URI, filename, or string --> stream
This function lets you define parsers that take any input source
(URL, pathname to local or network file, or actual data as a string)
and deal with it in a uniform manner. Returned object is guaranteed
to have all the basic stdio read methods (read, readline, readlines).
Just .close() the object when you're done with it.
Examples:
>>> from xml.dom import minidom
>>> sock = openAnything("http://localhost/kant.xml")
>>> doc = minidom.parse(sock)
>>> sock.close()
>>> sock = openAnything("c:\\inetpub\\wwwroot\\kant.xml")
>>> doc = minidom.parse(sock)
>>> sock.close()
>>> sock = openAnything("<ref id='conjunction'><text>and</text><text>or</text></ref>")
>>> doc = minidom.parse(sock)
>>> sock.close()
"""
if hasattr(source, "read"):
return source
if source == '-':
import sys
return sys.stdin
# try to open with urllib (if source is http, ftp, or file URL)
import urllib
try:
return urllib.urlopen(source)
except (IOError, OSError):
pass
# try to open with native open function (if source is pathname)
try:
return open(source)
except (IOError, OSError):
pass
# treat source as string
return StringIO.StringIO(str(source))
from xml.dom import minidom
class Forecast:
def __init__(self,a_node):
self.node = a_node
self.parse_xml_tree()
def parse_xml_tree(self):
pass
class Location:
def __init__(self, lat, lng):
self.forecasts = []
url = "http://api.yr.no/weatherapi/locationforecast/1.5/?lat=%f;lon=%f" % (lat, lng)
sock = openAnything(url)
doc = minidom.parse(sock)
sock.close
forecast = Forecast(doc)
self.forecasts.append(forecast)
f = Location(10.99, 11.22)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment