from datetime import datetime import requests import json from django.utils import timezone from django.template.loader import render_to_string from .models import CheckIn, Daily, Weather def create_daily(): d, created = Daily.objects.get_or_create( date=timezone.now() ) def get_yesterday_weather(): current = CheckIn.objects.latest() PB_URL = "http://api.wunderground.com/api/39c3ce6a12b14e75/yesterday/q/%s,%s.json" % (current.lat, current.lon) r = requests.get(PB_URL) weather = json.loads(r.text) data = weather['history']['dailysummary'][0] date = "%s %s %s" % (data['date']['year'], data['date']['mon'], data['date']['mday']) dt = datetime.strptime(date, "%Y %m %d") w, created = Weather.objects.get_or_create( point=current.point, date=dt, temp_max=data['maxtempi'], temp_min=data['mintempi'], temp_mean=data['meantempi'], wind_mean=data['meanwindspdi'], wind_max=data['maxwspdi'], humidity=data['humidity'], snow_amount=data['snowfalli'], rain_amount=data['precipi'], fog=int(data['fog']), rain=int(data['rain']), snow=int(data['snow']), hail=int(data['hail']), thunder=int(data['thunder']), ) if created: d = Daily.objects.get(date=dt) d.weather = w d.weather_human = render_to_string('human_weather.txt', {'object': w}).strip() d.save()