forked from kjam/data-wrangling-video
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmultiprocessing_example.py
More file actions
63 lines (53 loc) · 2.11 KB
/
multiprocessing_example.py
File metadata and controls
63 lines (53 loc) · 2.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
from __future__ import unicode_literals, print_function
import requests
from multiprocessing import Pool
try:
from configparser import ConfigParser
except ImportError:
from ConfigParser import ConfigParser
try:
from urllib.parse import quote_plus
except ImportError:
from urllib import quote_plus
import logging
def get_config():
""" Return my config object. """
conf = ConfigParser()
conf.read('config/prod.cfg')
return conf
def get_lat_long(config, address):
""" Returns lat and long from Google geocode API based on address. """
qs_dict = {'address': quote_plus(address),
'key': config.get('google', 'api_key'),
}
logging.debug('Requesting weather data from google for %s', address)
resp = requests.get('https://maps.googleapis.com/maps/api/geocode/json',
params=qs_dict)
try:
lat, lon = resp.json().get('results')[0].get('geometry').get(
'location').values()
except KeyError:
raise Exception('Could not find address: %s', address)
return lat, lon
def upcoming_forecast(args):
""" Pulls upcoming forecast based on address. """
config, address = args
lat, lon = get_lat_long(config, address)
logging.debug('Have lat and long for %s', address)
resp = requests.get('http://api.openweathermap.org/data/2.5/forecast',
params={'lat': lat, 'lon': lon,
'appid': config.get('openweather', 'api_key'),
'units': 'metric'})
return (address, resp.json())
def get_city_forecasts(addresses):
""" Returns forecasts when given a list of string addresses based on
Google geocoding and openweather data. """
config = get_config()
pool = Pool(processes=2)
return pool.map(upcoming_forecast, [(config, addy) for
addy in addresses])
my_weather = get_city_forecasts(['Los Angeles, CA', 'New York, NY',
'Berlin, Germany'])
print(type(my_weather))
for item in my_weather:
print(item[0])