Add license and docs
[pyxrad/.git] / pyxrad.py
1 # -*- coding: utf-8 -*-
2 # MIT License (c) 2017 Ethan Nelson
3
4 import os
5 import requests
6 import StringIO
7 import xml.etree.cElementTree as ElementTree
8
9
10 AWS_URL = "https://noaa-nexrad-level2.s3.amazonaws.com/"
11
12
13 def get_filenames(year, month, day, hour, site):
14     url = "%s?prefix=%s/%s/%s/%s/%s%s%s%s_%s" % \
15             (AWS_URL, year, month.zfill(2), day.zfill(2), site,
16              site, year, month.zfill(2), day.zfill(2), hour.zfill(2))
17     content = requests.get(url)
18     content = StringIO.StringIO(content.content)
19
20     return content
21
22
23 def parse_xml(content):
24     e = ElementTree.parse(content)
25     r = e.getroot()
26
27     filenames = []
28     for child in r:
29         if child.tag[-8:] == 'Contents':
30             for c in child:
31                 if c.tag[-3:] == 'Key':
32                     filenames.append(c.text)
33
34     return filenames
35
36 def get_files(filelist, save_path=''):
37     files = []
38     for filename in filelist:
39         content = requests.get(AWS_URL + filename)
40         c = content.content
41         name = os.path.basename(filename)
42         f = open(save_path + name,'w')
43         f.write(c)
44         f.close()
45         files.append(save_path + name)
46
47     return files
48
49
50 def example():
51     xml = get_filenames('2017','06','06','06','KMKX')
52     filenames = parse_xml(xml)
53     files = get_files(filenames)