예제 #1
0
파일: location.py 프로젝트: caiges/populous
def get_current(location_list):
    """
    Gets your current conditions. It is a bit more flaky because
    it depends on the City and State being correct. However, it will get the
    exactly current up-to-date information.
    """
    import re
    import feedparser

    location, human_location = location_list
    city, state = human_location.split(",")
    url = "http://rss.wunderground.com/auto/rss_full/%s/%s.xml" % (state.strip(), city.strip())
    feed = feedparser.parse(url)
    s = feed.entries[0].summary
    current = {"location": location, "human_location": human_location}

    current["observation_time"] = parser.parse(feed.entries[0].updated)
    temperature = re.compile("Temperature: ([\d\.]+)")
    current["temperature"] = temperature.search(s).group(1)
    humidity = re.compile("Humidity: (\d+)")
    current["humidity"] = humidity.search(s).group(1)
    conditions = re.compile("Conditions: ([\w\s]+)")
    current["conditions"] = conditions.search(s).group(1)
    windspeed = re.compile("Wind Speed: ([\d\.]+)")
    current["wind_speed"] = windspeed.search(s).group(1)
    winddirection = re.compile("Wind Direction: (\w+)")
    current["wind_direction"] = winddirection.search(s).group(1)
    try:
        f = Forecast(**current)
        f.save()
    except:
        logging.info("Current Forecast Data missing or no new data available")
예제 #2
0
파일: location.py 프로젝트: caiges/populous
def get_hourly(location_list):
    """
    Gets a less frequently updated but more informative feed.
    Main difference is that this one grabs the icon for the current weather.
    This should be run once an hour
    """
    location, human_location = location_list
    query = location
    url = "http://api.wunderground.com/auto/wui/geo/WXCurrentObXML/index.xml?query=%s" % query
    f = urllib2.urlopen(url)
    xml = f.read()
    root = ET.XML(xml)

    current = {"location": location, "human_location": human_location}
    current["observation_time"] = parser.parse(root.find("observation_time").text.replace("Last Updated on", ""))
    current["temperature"] = root.find("temp_f").text
    current["humidity"] = root.find("relative_humidity").text.strip("%")  # Remove %
    current["wind_speed"] = root.find("wind_mph").text
    current["wind_direction"] = root.find("wind_dir").text
    current["icon"] = root.find("icon").text
    current["conditions"] = root.find("weather").text
    try:
        f = Forecast(**current)
        f.save()
    except:
        logging.info("Hourly Forecast Data missing or no new data available")
예제 #3
0
    def save_forecasts(self, forecasts):
        weather_forecasts = []
        for forecast in forecasts:
            date = datetime.now() + timedelta(
                days=int(forecast['DaySequence']))
            forecast_date = date.date()
            day_forecast = self.get_day_forecast(forecast_date)
            if not day_forecast:
                weather_forecasts.append(
                    Forecast(
                        **{
                            'date': forecast_date,
                            'wind': forecast['WindSpeed'],
                            'rain': forecast['Rainfall'],
                            'maximum_temperature': forecast['HighTemp'],
                            'minimum_temperature': forecast['LowTemp']
                        }))
            else:
                day_forecast.wind = forecast['WindSpeed']
                day_forecast.rain = forecast['Rainfall']
                day_forecast.maximum_temperature = forecast['HighTemp']
                day_forecast.minimum_temperature = forecast['LowTemp']
                day_forecast.save()

        Forecast.objects.bulk_create(weather_forecasts)
예제 #4
0
    def handle(self, *args, **options):
        for file_path in options['file_path']:
            with open(file_path, 'r') as weather_file:
                json_data = json.load(weather_file)
                try:
                    city_forecast = OpenWeatherMap.process_city_forecasts(
                        json_data)
                except OpenWeatherException as import_error:
                    raise CommandError(import_error.message)

                # Pops the forecasts to make is easier to create new city
                forecasts = city_forecast.pop('forecasts')

                # Get or create City
                try:
                    city_record, created = City.objects.get_or_create(
                        **city_forecast)
                except MultipleObjectsReturned:
                    # Gets only one city and warns the user
                    city_record = City.objects.filter(
                        name=city_forecast.get('name'),
                        country_code=city_forecast.get('country_code'))[0]
                    self.stderr.write(
                        self.style.WARNING('Multiple records '
                                           'returned for %s' %
                                           city_forecast.get('name')))

                # Update of create forecasts for the city
                for forecast in forecasts:
                    try:
                        obj = Forecast.objects.get(city=city_record,
                                                   date=forecast.get('date'),
                                                   time=forecast.get('time'))
                        for key, value in forecast.items():
                            setattr(obj, key, value)
                        obj.save()
                    except Forecast.DoesNotExist:
                        obj = Forecast(city=city_record, **forecast)
                        obj.save()

                self.stdout.write(
                    self.style.SUCCESS('Successfully imported '
                                       'data of "%s"' % file_path))
예제 #5
0
def update_forecast():
    json = _get_forecast_json()
    if json is not None:
        try:
            new_forecast = Forecast()
            temp_in_celsius = json['main']['temp'] - 273.15
            new_forecast.temperatue = temp_in_celsius
            new_forecast.description = json['weather'][0]['description']
            new_forecast.city = json['name']
            new_forecast.save()
        except:
            pass