def index(): geolocator = Nominatim(user_agent="MJGEo") location = geolocator.geocode("Patna") mloc = location API_KEY = 'e2fea81b36c2588f1315c4ad2b721989' darksky = DarkSky(API_KEY) latitude = location.latitude longitude = location.longitude forecast = darksky.get_forecast( latitude, longitude, extend=False, # default `False` lang=languages.HINDI, # default `ENGLISH` units=units.AUTO, # default `auto` exclude=[weather.MINUTELY, weather.ALERTS] # default `[]` ) icon = forecast.currently.icon temperature = forecast.currently.temperature print(temperature) print(forecast.timezone) forecast.latitude # 42.3601 forecast.longitude # -71.0589 forecast.timezone # timezone for coordinates. For exmaple: `America/New_York` forecast.currently # CurrentlyForecast. Can be finded at darksky/forecast.py forecast.minutely # MinutelyForecast. Can be finded at darksky/forecast.py forecast.hourly # HourlyForecast. Can be finded at darksky/forecast.py forecast.daily # DailyForecast. Can be finded at darksky/forecast.py forecast.alerts # [Alert]. Can be finded at darksky/forecast.py params = {'sloc': mloc} return render_template("index.html", name=mloc, icon=icon, temperature=temperature)
def get_hourly_weather_data(lat, long): """ Given a location, get the weather data for the next 48 hrs. :param lat: latitude :param long: longitude :return: list of hourly weather data for the given lat long """ darksky = DarkSky(DARKSKY) try: # get the data forecast = darksky.get_forecast( lat, long, exclude=[weather.CURRENTLY, weather.MINUTELY, weather.DAILY, weather.ALERTS, weather.FLAGS]) # add lat & long to the hourly weather data for composite key in db hourly_weather_data = [] for data in forecast['hourly']['data']: data['latitude'] = lat data['longitude'] = long hourly_weather_data.append(data) # Lets save the weather data while were at it # for data in hourly_weather_data: # db.weather_container.create_item(data) return hourly_weather_data except Exception as e: print(e) return None
def get_current_weather_data(lat, long): """ Given a location, get the weather data for the next 48 hrs. :param lat: latitude :param long: longitude :return: list of hourly weather data for the given lat long """ darksky = DarkSky(DARKSKY) try: # get the data forecast = darksky.get_forecast( lat, long, exclude=[weather.HOURLY, weather.MINUTELY, weather.DAILY, weather.ALERTS, weather.FLAGS]) # add lat & long to the hourly weather data for composite key in db data = forecast.currently data.latitude = lat data.longitude = long data = data.__dict__ data.pop("time") return data except Exception as e: print(e) return None
def get_weather(): darksky = DarkSky(DARKSKY_API_KEY) forecast = darksky.get_forecast(latitude, longitude) todays_forecast = forecast.daily.data[0] summary = todays_forecast.summary temp_high = str(round(todays_forecast.temperature_high)) temp_low = str(round(todays_forecast.temperature_low)) return summary, temp_high, temp_low
def get_weather(steps): API_KEY = 'X' darksky = DarkSky(API_KEY) for step in steps: a = darksky.get_time_machine_forecast(step.latitude, step.longitude, time=step.time) step.weather = a.currently
def weather_data(lat, long, api_key): darksky = DarkSky(api_key) logger.info("Powered by Dark Sky") forecast = darksky.get_forecast(lat, long, extend=False, lang=languages.ENGLISH, values_units=units.AUTO, exclude=[weather.ALERTS, weather.MINUTELY]) return forecast
def __init__(self, latitude=None, longitude=None, sampleRange=None): jsonObj = self.__get_config() apiKey = self.__get_api_secret(jsonObj) self.longitude = longitude or self.__get_longitude(jsonObj) self.latitude = latitude or self.__get_latitude(jsonObj) self.sampleRange = sampleRange or self.__get_sample_forecast_range( jsonObj) self.client = DarkSky(apiKey)
def __init__(self): self.conn = sqlite3.connect('project.db') c = self.conn.cursor() c.execute('''CREATE TABLE IF NOT EXISTS city_hourly (city_name text, hourly text)''') c.execute('''CREATE TABLE IF NOT EXISTS city_daily (city_name text, daily text)''') self.conn.commit() #darksky secret key secret_key = 'c59726c51f4df85958f9b9843e2c55c8' self.darksky = DarkSky(secret_key)
def dashboard(request): client_ip = get_client_ip(request) try: user = User.objects.get(client_ip=client_ip[0]) except: user = User() #Grabs the IP from api.ipify.org which can be found in GeoIP2's API remote_ip_cache = cache.get('remote_ip') # or user.last_ip remote_ip = requests.get(url='https://api.ipify.org') #Instead of storing in the database, we can just use the user's cache to store their content if (remote_ip_cache == None): cache.set('remote_ip', remote_ip) #If the ip that we get from api.ipify.org is different than the cache/data model #We can assume that they have relocated and we will try and update their location based #off the GeoIP API if (remote_ip_cache != remote_ip): cache.set('remote_ip', remote_ip) remote_ip_cache = remote_ip user.last_ip = remote_ip_cache.text g = GeoIP2() try: lat_lon = g.lat_lon(remote_ip_cache.text) user.last_latitude = lat_lon[0] user.last_longitude = lat_lon[1] except: raise Http404("Can not find Location.") #We could make some logic to only allow these users to get requests from Dark Sky API # every so often. user.last_request = timezone.now() user.save() geoCity = g.city(remote_ip.text) #Get Forecast from Dark Sky API with API_KEY DWD_API_KEY = '9e3ac71786112191eaed1cd8abbe4614' darksky = DarkSky(DWD_API_KEY) forecast = darksky.get_forecast( lat_lon[0], lat_lon[1], extend=False, # default `False` lang=languages.ENGLISH, # default `ENGLISH` units=units.AUTO, # default `auto` exclude=[weather.MINUTELY, weather.ALERTS] # default `[]` ) context = {'forecast': forecast, 'geoCity': geoCity} return render(request, 'weatherApp/dashboard.html', context)
def weatherinfo(lat,long_): api ='af654ddc453104adcc9b4d0818a7604d' # this is mine, its is possible to get your own if you ready have an darksky acc...or.. dsky = DarkSky(api) # its not possible coz...darksky stopped creating new APIs since it is aquired by apple forecast = dsky.get_forecast( lat,long_, extend=False, lang=languages.ENGLISH, values_units= units.SI, exclude=[weather.MINUTELY,weather.HOURLY,weather.ALERTS,weather.FLAGS] ) return forecast
def __init__(self, api_key, location, **kwargs): super(WeatherSummary, self).__init__(**kwargs) self._location = location # self._key = api_key self.location_label = self.name self._darksky = DarkSky(api_key) self._forecast = None self._hourly = None self.bx_forecast = self.ids.bx_forecast self.bx_hourly = self.ids.bx_hourly self.nextupdate = 0 self.timer = None
def get_weather_data(): # establish connection to dark sky darksky = DarkSky(API_KEY) stadium_locations = pd.read_csv( os.path.join(data_dir, 'stadium_locations.csv')) # list of timestamps to collect data for time_stamps = [] current_date = start_date while current_date < end_date: time_stamps.append(current_date) current_date += relativedelta(days=+1) # TODO: REMOVE THIS # time_stamps = time_stamps[:5] # get weather data weather_forecast = {} i = 0 for index, row in stadium_locations.iterrows(): try: print( f"Getting data for stadium number {i} / {stadium_locations.shape[0]}: {row['stadium_name']}" ) forecast_list = [] for time_stamp in time_stamps: forecast = darksky.get_time_machine_forecast( row['latitude'], row['longitude'], extend=False, # default `False` lang=languages.ENGLISH, # default `ENGLISH` values_units=units.AUTO, # default `auto` exclude=[weather.MINUTELY, weather.ALERTS], # default `[]`, timezone= 'UTC', # default None - will be set by DarkSky API automatically time=time_stamp) forecast_list.append(forecast) weather_forecast[row['stadium_name']] = forecast_list except Exception: print(f"We failed to get weather data for {row['stadium_name']}") traceback.print_exc() finally: i += 1 # save weather data pickle.dump(weather_forecast, open(os.path.join(data_dir, 'weather_forecast.p'), "wb")) print('Weather data has been obtained')
def get_DS_forecasts(latitude, longitude): darksky = DarkSky(API_KEY) forecast = darksky.get_forecast(latitude, longitude, exclude=[weather.MINUTELY, weather.FLAGS]) # weather now, +[3/6/9/12] hour forecasts everyThreeHours = {} everyThreeHours[str(0)] = forecast.currently for i in range(1, 5): idx = 3 * i everyThreeHours[str(i)] = forecast.hourly.data[idx] return (everyThreeHours, forecast.alerts)
def main(api_key, lat, long): # log in home dir logging.basicConfig( filename=PurePath(Path.home()).joinpath('logs/cloud.log'), level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') pi_led = RGBLED(red=17, green=27, blue=24, pin_factory=PiGPIOFactory()) darksky = DarkSky(api_key) forecast = darksky.get_forecast( lat, long, exclude=['minutely', 'hourly', 'daily', 'alerts', 'flags']).currently.icon logging.info('Icon: {}'.format(forecast)) weather_indicator(pi_led, WEATHER_COLOR_MAP.get(forecast, 'unknown_icon'))
def setValues(): location = str(city.get()) if location[-3:] == 'usa': usa = 1 else: usa = 0 # Geocoding the city using GoogleMaps API geocode_result = gmaps.geocode(location) lat = geocode_result[0]['geometry']['location']['lat'] lng = geocode_result[0]['geometry']['location']['lng'] # set up darksky API to retreave weather data darksky = DarkSky(skyAPI) forecast = darksky.get_forecast( lat, lng, extend=False, # default `False` lang=languages.ENGLISH, # default `ENGLISH` units=units.AUTO, # default `auto` exclude=[weather.MINUTELY, weather.ALERTS] # default `[]` ) # set the variables for display wind.set(str(round(forecast.currently.wind_speed, 2)) + 'mph') updated.set(str(forecast.currently.time)[:-6]) weathers.set(forecast.currently.summary) if usa == 0: tempC = round(forecast.currently.temperature) tempF = round(forecast.currently.temperature * 1.8 + 32) else: tempF = round(forecast.currently.temperature) tempC = round((forecast.currently.temperature - 32) / 1.8) temp.set(str(int(tempC)) + '℃ ' + str(int(tempF)) + '℉ ') relHum.set(str(int(forecast.currently.humidity * 100)) + '%') visibility.set(str(round(forecast.currently.visibility, 2)) + 'miles') if str(forecast.currently.precip_type) == 'None': prec.set(str(forecast.currently.precip_type)) else: prec.set( str(int(forecast.currently.precip_probability)) + "% " + str(forecast.currently.precip_type)) uv.set(str(int(forecast.currently.uv_index))) if usa == 0: dewC = round(forecast.currently.dew_point) dewF = round(forecast.currently.dew_point * 1.8 + 32) else: dewF = round(forecast.currently.dew_point) dewC = round((forecast.currently.dew_point - 32) / 1.8) dew.set(str(int(dewC)) + '℃ ' + str(int(dewF)) + '℉ ')
def get_temperature(location={"lat": 31.630000, "long": -8.008889}): # Synchronous way darksky = DarkSky(API_KEY) latitude = location['lat'] longitude = location['long'] forecast = darksky.get_forecast( latitude, longitude, extend=False, # default `False` lang=languages.ENGLISH, # default `ENGLISH` units=units.AUTO, # default `auto` exclude=[weather.MINUTELY, weather.ALERTS] # default `[]` ) return forecast.currently.temperature
class historicalWeather(): """Class to get historical weather data and write to postgres database """ def __init__(self, pg, ds_key): self.pg_username = pg['username'] self.pg_password = pg['password'] self.pg_host = pg['host'] self.pg_db = pg['database'] self.pg_port = pg['port'] self.ds_key = ds_key self.atx_lat = 30.267151 self.atx_lon = -97.743057 self.ds_key = ds_key self.init_ds_obj() def write_to_sql(self, times, temps, precips, rain_prob, humidities, wind, clouds, uv): with psycopg2.connect(dbname=self.pg_db, user=self.pg_username, password=self.pg_password, host=self.pg_host, port=self.pg_port) as conn: with conn.cursor() as curs: pg_query = """INSERT INTO weather VALUES (%s, %s, %s, %s, %s, %s, %s, %s) ON CONFLICT DO NOTHING""" curs.executemany( pg_query, zip(times, temps, precips, rain_prob, humidities, wind, clouds, uv)) conn.commit() def init_ds_obj(self): self.ds = DarkSky(self.ds_key) def fetch_day_history(self, day): try: hist = self.ds.get_time_machine_forecast( self.atx_lat, self.atx_lon, extend=False, lang=languages.ENGLISH, units=units.AUTO, exclude=[weather.MINUTELY, weather.ALERTS], timezone='UTC', time=day) times = [x.time for x in hist.hourly.data] temps = [x.temperature for x in hist.hourly.data] precips = [x.precip_intensity for x in hist.hourly.data] rain_prob = [x.precip_probability for x in hist.hourly.data] humidities = [x.humidity for x in hist.hourly.data] wind = [x.wind_speed for x in hist.hourly.data] clouds = [x.cloud_cover for x in hist.hourly.data] uv = [x.uv_index for x in hist.hourly.data] self.write_to_sql(times, temps, precips, rain_prob, humidities, wind, clouds, uv) except: pass
def extract_data(self, message): darksky = DarkSky("68a391b503f11aa6fa13d405bfefdaba") latitude = message['latitude'] longitude = message['longitude'] forecast = darksky.get_forecast( latitude, longitude, extend=False, lang=languages.ENGLISH, values_units=units.AUTO, exclude=[weather.MINUTELY, weather.ALERTS], timezone='UTC' ) current = forecast.currently mssg = {'summary':current.summary, 'windSpeed':current.wind_speed, 'humidity':current.humidity, 'temperature':current.temperature} return mssg
def execute(self, context): # Authenticate Socrata client self.log.info('Authenticate DarkSky client') darksky = DarkSky(self.dark_sky_api_token) # render macros to for date rendered_forecast_date_str = self.forecast_date_str.format(**context) forecast_date_obj = datetime.datetime.strptime( rendered_forecast_date_str, '%Y-%m-%d') # Get Daily Weather results from API endpoint self.log.info('Query API for hourly weather results') forecast = darksky.get_time_machine_forecast( self.latitude, self.longitude, forecast_date_obj, extend=False, # default `False` lang=languages.ENGLISH, # default `ENGLISH` units=units.AUTO, # default `auto` exclude=[ weather.CURRENTLY, weather.MINUTELY, weather.DAILY, weather.ALERTS ] # default `[]` ) forecast_hourly_data_object_list = forecast.hourly.data forecast_hourly_data_dict_list = [] for forecast_hourly_data_object in forecast_hourly_data_object_list: forecast_hourly_data_dict_list.append( vars(forecast_hourly_data_object)) self.log.info('Got {} results'.format( len(forecast_hourly_data_dict_list))) # Write response to file self.log.info('Write response to CSV') rendered_csv_output_filepath = self.csv_output_filepath.format( **context) keys = forecast_hourly_data_dict_list[0].keys() with open(rendered_csv_output_filepath, 'w') as outfile: dict_writer = csv.DictWriter(outfile, keys) dict_writer.writeheader() dict_writer.writerows(forecast_hourly_data_dict_list) self.log.info( 'Wrote response to {}'.format(rendered_csv_output_filepath))
def get_weather(latlong=latlong): from darksky.api import DarkSky, DarkSkyAsync from darksky.types import languages, units, weather API_KEY = get_API_from_file() # Synchronous way darksky = DarkSky(API_KEY) #print (latlong) latitude, longitude = latlong #[:] forecast = darksky.get_forecast( latitude, longitude, extend=False, # default `False` lang=languages.ENGLISH, # default `ENGLISH` #values_units= units.AUTO, # default auto exclude=[weather.MINUTELY], # weather.ALERTS] - default [] ) return forecast
def WeatherObserver(apikey, loc): darksky = DarkSky(apikey) def _forecast_fetch(units=units.AUTO, lang=languages.ENGLISH): return darksky.get_forecast(loc['lat'], loc['long'], units=units, lang=lang) return _forecast_fetch
def get_forecast(self, coordinate): API_KEY = self.config.get_config('darksky', 'api', '9bd0b8315895a1c550505b281fc082ff') # Synchronous way darksky = DarkSky(API_KEY) #latitude = 42.3601 #longitude = -71.0589 latitude, longitude = coordinate forecast = darksky.get_forecast( latitude, longitude, extend=False, # default `False` lang=languages.ENGLISH, # default `ENGLISH` values_units=units.AUTO, # default `auto` exclude=[weather.MINUTELY, weather.ALERTS], # default `[]`, timezone='Asia/Jakarta' # default None - will be set by DarkSky API automatically ) print(forecast) return forecast
def update_weather(self): # Get weather print("Updating weather:") darksky = DarkSky(self.darksky_secret) try: self.forecast = darksky.get_forecast(43.312691, -1.993332, lang='es') print(" >> Summary: ", self.forecast.currently.summary) print(" >> Icon: ", self.forecast.currently.icon) print(" >> Temperature: ", self.forecast.currently.temperature) print(" >> Humidity: ", self.forecast.currently.humidity) print(" >> Wind Speed: ", self.forecast.currently.wind_speed) print(" >> Pressure: ", self.forecast.currently.pressure) print(' >> Current summary: ' + self.forecast.currently.summary) #print(' >> Minutely summary: ' + self.forecast.minutely.summary) print(' >> Hourly summary: ' + self.forecast.hourly.summary) print("Get icon index:") weather_icons = { "clear-day": "01", "clear-night": "02", "partly-cloudy-day": "03", "partly-cloudy-night": "04", "cloudy": "05", "fog": "06", "wind": "07", "sleet": "08", "rain": "09", "snow": "10", } weather_icon_index = weather_icons.get( self.forecast.currently.icon) print(" >> Icon index: ", weather_icon_index) command = 'W' + weather_icon_index + '\r' print("Weather command: ", command) self.comport.write(bytes(command, 'UTF-8')) except: print("Exception occured during weather update")
def get_forecast_sync(self, coordinate): # Synchronous way Time Machine from datetime import datetime as dt API_KEY = self.config.get_config('darksky', 'api', '9bd0b8315895a1c550505b281fc082ff') darksky = DarkSky(API_KEY) t = dt(2018, 5, 6, 12) #latitude = 42.3601 #longitude = -71.0589 latitude, longitude = coordinate forecast = darksky.get_time_machine_forecast( latitude, longitude, extend=False, # default `False` lang=languages.ENGLISH, # default `ENGLISH` values_units=units.AUTO, # default `auto` exclude=[weather.MINUTELY, weather.ALERTS], # default `[]`, timezone='UTC', # default None - will be set by DarkSky API automatically time=t ) print(forecast) return forecast
def get_old_weather(latlong, time): #latlong = (float,float) #time = a datetime object from darksky.api import DarkSky, DarkSkyAsync from darksky.types import languages, units, weather API_KEY = get_API_from_file() # Synchronous way darksky = DarkSky(API_KEY) #print (latlong) latitude, longitude = latlong #[:] forecast = darksky.get_time_machine_forecast( latitude, longitude, time, extend=False, # default `False` lang=languages.ENGLISH, # default `ENGLISH` #values_units= units.AUTO, # default `auto` exclude=[weather.MINUTELY] #, weather.ALERTS] # default `[]` ) return forecast
def getweather(self): api_key = os.environ['DARKSKY_API_KEY'] darksky = DarkSky(api_key) coordinates = self.getcoords() geodata = dict() geodata['lat'] = coordinates['geometry']['location']['lat'] geodata['lng'] = coordinates['geometry']['location']['lng'] latitude = geodata['lat'] longitude = geodata['lng'] forecast = darksky.get_forecast( latitude, longitude, extend=False, # default `False` lang=languages.ENGLISH, # default `ENGLISH` values_units=units.AUTO, # default `auto` exclude=[], # default `[]`, timezone= None # default None - will be set by DarkSky API automatically ) return forecast
def result(): if request.method == 'POST': result = request.form print(result['mlocation']) geolocator = Nominatim(user_agent="MJGEo") location = geolocator.geocode(result['mlocation']) mloc = location API_KEY = 'e2fea81b36c2588f1315c4ad2b721989' darksky = DarkSky(API_KEY) latitude = location.latitude longitude = location.longitude forecast = darksky.get_forecast( latitude, longitude, extend=False, # default `False` lang=languages.ENGLISH, # default `ENGLISH` units=units.AUTO, # default `auto` exclude=[weather.MINUTELY, weather.ALERTS] # default `[]` ) summary = forecast.hourly.summary temperature = forecast.hourly.data[0].temperature icon = forecast.daily.data[0].icon visibility = forecast.daily.data[0].visibility print(temperature) print(forecast.timezone) forecast.latitude # 42.3601 forecast.longitude # -71.0589 forecast.timezone # timezone for coordinates. For exmaple: `America/New_York` forecast.currently # CurrentlyForecast. Can be finded at darksky/forecast.py forecast.minutely # MinutelyForecast. Can be finded at darksky/forecast.py forecast.hourly # HourlyForecast. Can be finded at darksky/forecast.py forecast.daily # DailyForecast. Can be finded at darksky/forecast.py forecast.alerts # [Alert]. Can be finded at darksky/forecast.py params = [mloc, summary, temperature, icon, visibility] return render_template("index.html", params=params)
def extract_data(self, message): try: responseDark = requests.get( "https://api.darksky.net/forecast/68a391b503f11aa6fa13d405bfefdaba/10,-10" ) darksky = DarkSky("68a391b503f11aa6fa13d405bfefdaba") latitude = message['latitude'] longitude = message['longitude'] forecast = darksky.get_forecast( latitude, longitude, extend=False, lang=languages.ENGLISH, values_units=units.AUTO, exclude=[weather.MINUTELY, weather.ALERTS], timezone='UTC') current = forecast.currently mssg = { 'summary': current.summary, 'windSpeed': current.wind_speed, 'humidity': current.humidity, 'temperature': current.temperature } return mssg except Exception as e: print(e) mssg = { 'summary': 'overcast', 'windSpeed': 12, 'humidity': 78, 'temperature': 42 } print(mssg) return mssg
def run_continuously(config, dry_run): #thestorm = dt.datetime(2020, 1, 12, 8) #thestorm.isoformat() darksky = DarkSky(config.darksky_key) already_snowing = False while True: now = dt.datetime.now(TIME_ZONE) print(now) forecast = get_forecast(darksky, config) snow_event = next_snowfall(forecast) if snow_event is None: # We don't have a clue when the next snowfall may be next_poll = LONG_POLL already_snowing = False else: if snow_event.time >= now: # The next snowfall is at some point in the future (or right this moment). duration_estimate = snow_event.time - now else: # This is a historical query - pretend now is the predicted time point. duration_estimate = EMPTY_DURATION if duration_estimate < SNOW_THRESHOLD: user_log.info("It's snowing in %s!" % config.location) send_message(snow_event.accumulation, already_snowing, config, dry_run) next_poll = SNOW_POLL already_snowing = True else: if already_snowing: user_log.info("Stopped") already_snowing = False estimate = dt.timedelta(seconds=int(duration_estimate.seconds * 0.2)) if estimate > LONG_POLL: # If the next predicted snowfall is too far in the future, cap it off at the long poll duration. next_poll = LONG_POLL else: next_poll = max(SNOW_THRESHOLD, estimate) logging.debug("Sleeping for %s seconds." % next_poll.seconds) time.sleep(next_poll.seconds)
class WeatherFetcher: def __init__(self): self.data: Forecast = None self._lock = threading.Lock() self.darksky = DarkSky(dark_sky_key) def do(self): forecast = self.darksky.get_forecast(dark_sky_lat, dark_sky_lon) self.update(forecast) print(forecast.currently.temperature) def update(self, data: Forecast): with self._lock: self.data = data def read(self): with self._lock: return self.data