Skip to content

Commit e6aa17c

Browse files
wholmgrencwhanse
authored andcommitted
specify user-agent in tmy3 remote request (#494)
Closes #493
1 parent fff1131 commit e6aa17c

File tree

2 files changed

+24
-9
lines changed

2 files changed

+24
-9
lines changed

docs/sphinx/source/whatsnew/v0.6.0.rst

+2
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@ Bug fixes
2323
(:issue:`464`)
2424
* ModelChain.prepare_inputs failed to pass solar_position and airmass to
2525
Location.get_clearsky. Fixed. (:issue:`481`)
26+
* Add User-Agent specification to TMY3 remote requests to avoid rejection.
27+
(:issue:`493`)
2628

2729

2830
Documentation

pvlib/tmy.py

+22-9
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,9 @@
77
import dateutil
88
import io
99
try:
10-
from urllib2 import urlopen
10+
from urllib2 import urlopen, Request
1111
except ImportError:
12-
from urllib.request import urlopen
12+
from urllib.request import urlopen, Request
1313

1414
import pandas as pd
1515

@@ -164,14 +164,23 @@ def readtmy3(filename=None, coerce_year=None, recolumn=True):
164164

165165
head = ['USAF', 'Name', 'State', 'TZ', 'latitude', 'longitude', 'altitude']
166166

167-
try:
168-
csvdata = open(filename, 'r')
169-
except IOError:
170-
response = urlopen(filename)
167+
if filename.startswith('http'):
168+
request = Request(filename, headers={'User-Agent':
169+
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) '
170+
'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 '
171+
'Safari/537.36'})
172+
response = urlopen(request)
171173
csvdata = io.StringIO(response.read().decode(errors='ignore'))
174+
else:
175+
# assume it's accessible via the file system
176+
csvdata = open(filename, 'r')
177+
178+
# read in file metadata, advance buffer to second line
179+
firstline = csvdata.readline()
180+
if 'Request Rejected' in firstline:
181+
raise IOError('Remote server rejected TMY file request')
172182

173-
# read in file metadata
174-
meta = dict(zip(head, csvdata.readline().rstrip('\n').split(",")))
183+
meta = dict(zip(head, firstline.rstrip('\n').split(",")))
175184

176185
# convert metadata strings to numeric types
177186
meta['altitude'] = float(meta['altitude'])
@@ -180,8 +189,12 @@ def readtmy3(filename=None, coerce_year=None, recolumn=True):
180189
meta['TZ'] = float(meta['TZ'])
181190
meta['USAF'] = int(meta['USAF'])
182191

192+
# use pandas to read the csv file/stringio buffer
193+
# header is actually the second line in file, but tell pandas to look for
194+
# header information on the 1st line (0 indexing) because we've already
195+
# advanced past the true first line with the readline call above.
183196
data = pd.read_csv(
184-
filename, header=1,
197+
csvdata, header=0,
185198
parse_dates={'datetime': ['Date (MM/DD/YYYY)', 'Time (HH:MM)']},
186199
date_parser=lambda *x: _parsedate(*x, year=coerce_year),
187200
index_col='datetime')

0 commit comments

Comments
 (0)