Skip to content

Instantly share code, notes, and snippets.

@danizen
Created August 6, 2020 03:36
Show Gist options
  • Save danizen/5cefe26c918b36f1a1064818aebcdac0 to your computer and use it in GitHub Desktop.
Save danizen/5cefe26c918b36f1a1064818aebcdac0 to your computer and use it in GitHub Desktop.
import json
import sys
from argparse import ArgumentParser, ArgumentTypeError
from copy import deepcopy
from datetime import datetime, timedelta
import attr
import requests
from dateutil import parser as date_parser
URL = 'https://visual-crossing-weather.p.rapidapi.com/history'
DFLT_PARAMS = {
'contentType': 'csv',
'shortColumnNames': 'true',
'unitGroup': 'us',
'dayStartTime': '0:0:00',
'dayEndTime': '0:0:00',
'aggregateHours': '24',
}
def new_session():
session = requests.Session()
session.headers.update({
'x-rapidapi-host': 'visual-crossing-weather.p.rapidapi.com',
# NOTE: replace this with your own key from rapidapi.com for Visual Crossing Weather
'x-rapidapi-key': '999999999999999999999999999999999999999999999'
})
return session
def get_params(stime, etime, location='San Francisco, CA'):
params = deepcopy(DFLT_PARAMS)
params['location'] = location
params['startDateTime'] = stime.isoformat()
params['endDateTime'] = etime.isoformat()
return params
def download_weather(stime, days, location='San Francisco, CA'):
etime = stime + timedelta(days=days)
session = new_session()
params = get_params(stime, etime, location=location)
r = session.get(URL, params=params)
r.raise_for_status()
print(r.text)
def positive_number_type(rawvalue):
try:
value = int(rawvalue)
except ValueError:
raise ArgumentTypeError('should be a positive number')
if value <= 0:
raise ArgumentTypeError('should be a positive number')
return value
def date_type(rawvalue):
try:
value = date_parser.parse(rawvalue)
except date_parser.ParseError:
raise ArgumentTypeError('should be a datetime')
return value
def create_parser(program_name):
parser = ArgumentParser(prog=program_name, description='Weather commands')
parser.add_argument('stime', metavar='DATE', type=date_type)
parser.add_argument('days', metavar='COUNT', type=positive_number_type)
parser.add_argument('--location', metavar='LOCATION', default='San Francisco, US')
return parser
def main():
parser = create_parser(sys.argv[0])
opts = parser.parse_args(sys.argv[1:])
download_weather(opts.stime, opts.days - 1, location=opts.location)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment