-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathweather_service.py
164 lines (121 loc) · 4.15 KB
/
weather_service.py
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
import os
import json
import sys
from urllib import quote
from nameko.rpc import rpc, RpcProxy
import requests
openweather_base_url = 'http://api.openweathermap.org/data/2.5/weather'
spotify_base_url = 'https://api.spotify.com/v1/'
def error(msg):
"""Return a Exception object
This function is a reuse function to handle exceptions
"""
raise Exception(msg)
def request(qstring, jwt):
"""
Return the result from a Request
"""
bearer = 'Bearer {}'.format(jwt)
# JWT necessary to the Spotify Authorization
if jwt is None:
return requests.request('GET', qstring)
else:
# If is not a Spotify call
return requests.request(
'GET', qstring, headers={
'Authorization': bearer})
def get_playlists(weather, jwt):
""" Return a list of Spotify playlists
From a Weather predict, we consult the
Spotify API to return results based on the
weather description.
"""
filtered = []
if weather is None:
error('Missing parameter')
if weather['weather'] is None:
error('Invalid location')
# Main attributte contains the temperature meassure
main = weather['main']
# Convert string to int
temperature = int(main['temp'])
# Default Genre
genre = 'classical'
# If temperature (celcius) is above 30 degrees, suggest tracks for party
# In case temperature is between 15 and 30 degrees, suggest pop music tracks
# If it's a bit chilly (between 10 and 14 degrees), suggest rock music tracks
# Otherwise, if it's freezing outside, suggests classical music tracks
if temperature > 30:
genre = 'party'
elif temperature >= 15 and temperature <= 30:
genre = 'pop'
elif temperature >= 10 and temperature <= 14:
genre = 'rock'
# Get current weather to check temperatury
current = weather['weather'][0]
qstring = '{}search?q=name:{}&type=playlist'.format(
spotify_base_url, quote(current['description']))
resp = request(qstring, jwt).json()
# Is receives nothing
if 'error' in resp:
e = resp['error']
error(e['message'])
# getting plalists itens
items = resp['playlists']['items']
# Build the list of the names
for playlist in items:
filtered.append(playlist['name'])
return filtered
def get_weather(args, appid):
"""Return a Weather object
This call consumes the open Weather Map API to retreive the weather information about some geographi coordinate or city name.
"""
# Check if seach by City
if 'city' not in args:
# Check if search by coordinates
if 'lat' not in args or 'lon' not in args:
error('Missing parameter')
else:
# Query string to coordinates
r_str = '{}?units=metric&lat={}&lon={}&appid={}'.format(
openweather_base_url, args['lat'], args['lon'], appid)
else:
# Query string to City
r_str = '{}?units=metric&q={}&appid={}'.format(
openweather_base_url, quote(
args['city']), appid)
# Requesting the API
resp = request(r_str, None)
# Returns a JSON object
return resp.json()
class PlaylistsService:
"""Playlists Srevice
Returns:
list: A list of playlists
"""
name = "playlists"
zipcode_rpc = RpcProxy('playlistsservice')
@rpc
def get_playlists(self, appid, jwt, args):
"""[summary]
Arguments:
appid (string): Open Weather Map AppID
jwt (string): Spotify Authorization Token
args (dict): A Dict (city, lat, long)
Returns:
list: A list of playlists
"""
try:
# Check if is passed args
if args is None:
error("Missing parameter")
# Consuming the OWM API
weather = get_weather(args, appid)
# Check response
if int(weather['cod']) != 200:
return weather
# Consuming Spotify API
playlists = get_playlists(weather, jwt)
return playlists
except Exception as e:
return str({'Error': str(e)})