Example #1
0
def for_location(request):
    geolocator = Nominatim(user_agent="location")

    geo_lookup = GeoLookup("582179b24ab7f5f07d71c6fb0be3fc7c")
    ulocation = geo_lookup.get_own_location()
    city = ulocation["city"]
    zip = ulocation["zip"]
    ip = ulocation["ip"]
    print(ulocation)
    #ip = '192.168.0.105'
    #ip = get('https://api.ipify.org').text
    #print('My public IP address is: {}'.format(ip))
    #ip = ("",publicip.get(),"")
    #ip = get('http://ip.42.pl/raw').text

    # country,city,lat,lon = get_geo(ip)

    # print('location country',country)
    # print('location city',city)

    # ulocation = geolocator.geocode(city)
    # print('###',ulocation)
    # alocation = request.remote_addr
    context = {
        'city': city,
        'zip': zip,
        'ip': ip,
        #'ulocation' : ulocation,
        #   'alocation' : alocation,
    }
    return render(request, 'location/main.html', context)
Example #2
0
def checkout(request):
    geo_lookup = GeoLookup("581858e87c3628991ff44ae8ff6ddd1e")
    location = geo_lookup.get_own_location()
    lat = location["latitude"]
    lng = location["longitude"]
    country = location["country_name"]
    region = location["region_name"]
    city = location["city"]
    print(location)
    return render(request, "checkout-page.html",{"country": country,"region": region, "city":city})
Example #3
0
def weather(request):

    geo_lookup = GeoLookup('c4b511b1f75d2bf3fa9b588ae6576d67')
    location = geo_lookup.get_own_location()

    lat = location["latitude"]
    lng = location["longitude"]
    region = location["region_name"]
    city = location["city"]
    country = location["country_name"]

    # Retrieve Weather Data
    weekday = date.today()
    loc = lat, lng
    # with forecast('ae32ed86484ab897ff2ee29d7c2ae1c7', *loc) as loc:
    #     for day in loc.daily:
    #         day = dict(day = date.strftime(weekday, '%a'), sum=day.summary, tempMin=day.temperatureMin, tempMax=day.temperatureMax)
    #         print('{day} ----- {tempMin} ----- {tempMax}'.format(**day))
    #         weekday += timedelta(days=1)

    hour = datetime.now().hour
    location = forecast('ae32ed86484ab897ff2ee29d7c2ae1c7', lat, lng)
    i = 0
    while hour < 24:
        temp = location.hourly[i].temperature
        if hour > 12:
            print('{}pm - {}'.format(hour - 12, temp))
        else:
            print('{}am - {}'.format(hour, temp))
        hour += 1
        i += 1

    context = {
        'latitude': lat,
        'longitude': lng,
        'region': region,
        'city': city,
        'country': country,
    }

    return render(request, 'weather.html', context)
def current_location_weather():
    geo_lookup = GeoLookup("9ff825aee8c78758e19180acda87060c")
    location = geo_lookup.get_own_location()
    coords = (location["latitude"], location["longitude"])
    return WeatherData(coords, "coords")
Example #5
0
def home(request):
    #-------------------------------------------------
    if request.user.is_authenticated:
        user_category = ''
        user = request.user
        user_category = user.profile.category
        form = TodoForm()
        todos = Todo.objects.filter(user=user).order_by('priority')
        city = ""
        if 'city' in request.GET:
            city = request.GET.get('city')
            if len(city) < 2:
                geo_lookup = GeoLookup("582179b24ab7f5f07d71c6fb0be3fc7c")
                ulocation = geo_lookup.get_own_location()
                city = ulocation["city"]
            api = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid=5bc57ba9bc106c9844915b5178ee10ad"
        else:
            geo_lookup = GeoLookup("582179b24ab7f5f07d71c6fb0be3fc7c")
            ulocation = geo_lookup.get_own_location()
            # print(ulocation)
            city = ulocation["city"]

            # zip = ulocation["zip"]
            # ip = ulocation["ip"]
            api = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid=5bc57ba9bc106c9844915b5178ee10ad"
        json_data = requests.get(api).json()
        condition = json_data['weather'][0]['main']
        temp = int(json_data['main']['temp'] - 273.15)
        min_temp = int(json_data['main']['temp_min'] - 273.15)
        max_temp = int(json_data['main']['temp_max'] - 273.15)
        feels_like = int(json_data['main']['feels_like'] - 273.15)
        pressure = json_data['main']['pressure']
        humidity = json_data['main']['humidity']
        #-------------------------------------------------------
        try:
            myapi = f"https://nominatim.openstreetmap.org/search?city=<{city}>&format=json"
            # From the api we get data.
            json_data = requests.get(myapi).json()
            part = json_data[0]
            display_name = part["display_name"]
            c_list = list(map(str, display_name.split(",")))
            co = c_list[-1].strip()
            country = translator.translate(co, lang_tgt='en').strip()
            print(country)
            if "Ireland" in country:
                country = "Ireland"
            if "Morocco" in country:
                country = "Morocco"
            if "Belgium" in country:
                country = "Belgium"
            if "Inebria" in country:
                country = "Bulgaria"
            if "Hellas" in country:
                country = "Greece"
            code = ""
            mylist = [["The United Arab Emirates", "ae"],
                      ["United States", "us"], ["Australia", "au"],
                      ["India", "in"], ["Argentina", "ar"], ["Austria", "at"],
                      ["Belgium", "be"], ["Bulgaria", "bg"], ["Brazil", "br"],
                      ["Canada", "ca"], ["China", "cn"], ["Colombia", "co"],
                      ["Cuba", "cu"], ["Czechia", "cz"], ["Egypt", "eg"],
                      ["France", "fr"], ["United Kingdom", "gb"],
                      ["Greece", "gr"], ["Hong Kong", "hk"], ["Hungary", "hu"],
                      ["Indonesia", "id"], ["Ireland", "ie"], ["Israel", "il"],
                      ["Italy", "it"], ["Japan", "jp"],
                      ["Republic of Korea", "kr"], ["Lithuania", "lt"],
                      ["Latvia", "lv"], ["Morocco", "ma"], ["Mexico", "mx"],
                      ["Malaysia", "my"], ["Nigeria", "ng"],
                      ["Netherlands", "nl"], ["Norway", "no"],
                      ["New Zealand", "nz"], ["Philippines", "ph"],
                      ["Poland", "pl"], ["Portugal", "pt"], ["Romania", "ro"],
                      ["rs"], ["Russia", "ru"], ["Saudi Arabia", "sa"],
                      ["Sweden", "se"], ["Singapore",
                                         "sg"], ["Slovenia", "si"],
                      ["Slovakia", "sk"], ["Thailand", "th"], ["Turkey", "tr"],
                      ["Taiwan", "tw"], ["Ukraine", "ua"], ["Venezuela", "ve"],
                      ["South Africa", "za"]]

            for i in range(len(mylist) + 1):
                # print(mylist[i][0])
                if country == mylist[i][0]:
                    code = mylist[i][1]
                    # print(code)
                    break
        except:
            country = "India"
            code = "in"


#----------------------------------------------------
        if user_category == '':
            category = 'general'
        else:
            category = user_category
        if 'category' in request.GET:
            category = request.GET.get('category')
            print(category)
        contents = []
        if len(code) == 2:
            myapi = f"https://newsapi.org/v2/top-headlines?country={code}&category={category}&apiKey=95336568b9a7490086201803ec8652e1"
            json_data = requests.get(myapi).json()
            articles = json_data["articles"]
            for article in articles:
                content = []
                title = "->" + article['title']
                description = article['description']
                url = article['url']
                content.append(title)
                content.append(description)
                content.append(url)
                contents.append(content)
        else:
            print("Country not found")

        if category == "":
            mycategory = "General"
        else:
            mycategory = category.capitalize()

        if country == "United Kingdom":
            country = "uk"
        if country == "United States":
            country = 'us'
        if country == "The United Arab Emirates":
            country = 'united-arab-emirates'
        if country == 'Czechia':
            country = "czech-republic"
        if country == 'Republic of Korea':
            country = "south-korea"
        if country == 'South Africa':
            country = 'south-africa'

        html_text = requests.get(
            f'https://www.worldometers.info/coronavirus/country/{country}'
        ).text
        soup = BeautifulSoup(html_text, 'lxml')
        main_counter = soup.find_all('div', id='maincounter-wrap')
        cases_counter = main_counter[
            0]  # to get first 'maincounter-wrap' out of 3
        cases_number = cases_counter.find('div', class_='maincounter-number')
        cases = cases_number.find('span').text
        deaths_counter = main_counter[
            1]  # to get second 'maincounter-wrap' out of 3
        deaths_number = deaths_counter.find('div', class_='maincounter-number')
        deaths = deaths_number.find('span').text
        recovered_counter = main_counter[
            2]  # to get third 'maincounter-wrap' out of 3
        recovered_number = recovered_counter.find('div',
                                                  class_='maincounter-number')
        recovered = recovered_number.find('span').text

        html_text = requests.get(
            'https://sports.ndtv.com/cricket/live-scores').text
        soup = BeautifulSoup(html_text, "html.parser")
        sect = soup.find_all('div', class_='sp-scr_wrp')
        section = sect[0]
        description = section.find('span', class_='description').text
        location = section.find('span', class_='location').text
        time = section.find('div', class_='scr_dt-red').text
        link = "https://sports.ndtv.com/" + section.find(
            'a', class_='scr_ful-sbr-txt').get('href')

        try:
            toss = section.find('div', class_="scr_dt-red @*scr-inf_tx*@").text
        except:
            toss = "Toss not Available Yet!"
        block = section.find_all('div', class_='scr_tm-wrp')
        team1_block = block[0]
        team1_name = team1_block.text
        try:
            team1_score = team1_block.find('span', class_='scr_tm-run').text
        except:
            team1_score = "Score not Available Yet!"
        team2_block = block[1]
        team2_name = team2_block.text
        try:
            team2_score = team2_block.find('span', class_='scr_tm-run').text
        except:
            team2_score = "Score not Available Yet!"

        url = "https://www.affirmations.dev/"
        myjson = requests.get(url).json()
        affirmation = myjson['affirmation']

        terna = requests.get('https://ternaengg.ac.in/notice-board/').text
        soup = BeautifulSoup(terna, 'lxml')
        mytable = soup.find('table', class_='tbl4')
        trs = mytable.find_all('tr')
        notices = []
        count_notice = 0
        for tr in trs:
            if count_notice == 5:
                break
            notice = []
            tds = tr.find_all('td')
            try:
                date_notice = tds[0].text
                notice.append(date_notice)
                desc = tds[2].text
                if "\n" in description:
                    description_notice = desc.replace('\n', '')
                else:
                    description_notice = "# " + desc
                notice.append(description_notice)
                link_notice = tds[2].a['href']
                notice.append(link_notice)
                notices.append(notice)
                count_notice = count_notice + 1
            except:
                pass

        context = {
            'form': form,
            'todos': todos,
            'city': city,
            'temp': temp,
            'min_temp': min_temp,
            'max_temp': max_temp,
            'feels_like': feels_like,
            'pressure': pressure,
            'humidity': humidity,
            'contents': contents,
            'category': mycategory,
            'cases': cases,
            'deaths': deaths,
            'recovered': recovered,
            'country': country.upper(),
            'description': description,
            'location': location,
            'time': time,
            'toss': toss,
            'team1_name': team1_name.strip(),
            'team1_score': team1_score.strip(),
            'team2_name': team2_name.strip(),
            'team2_score': team2_score.strip(),
            'link': link,
            'affirmation': affirmation,
            'notices': notices,
        }
        return render(request, 'todoapp/index.html', context)
Example #6
0
from ipstack import GeoLookup
import csv
from imutils.video import FPS
from threading import Thread
import xlwt
from .models import Video
from django.views.decorators.csrf import csrf_exempt
from base64 import b64encode, decodestring, decodebytes, b64decode


# The following piece of code fetches the user location by using the Geolookup library.
# We need the API key of the library and using that we can fetch the city, region and 
# country of the user. This data is stored in the previous results database table.
global location
geo_lookup = GeoLookup('776da34f4f37c2fb8f3ad306cc615bff')
location = geo_lookup.get_own_location()
location = location['city'] + ', ' + location['region_name'] + ', ' + location['country_name']



class MultithreadedVideoStream:
    def __init__(self, path, queuesize=1024):
        self.stream = cv2.VideoCapture(path)
        self.stopped = False
        self.Q = Queue(maxsize=queuesize)

    def start(self):
        t = Thread(target=self.update, args=())
        t.daemon = True
        t.start()
        return self
Example #7
0
def home(request):
	

	geo_lookup= GeoLookup("ba3495a30c658700b23916512f93eef0")
	location = geo_lookup.get_own_location()


	lat = location['latitude']
	lng = location['longitude']
	region = location['city']

	boston = lat,lng

	weekday = date.today()

	weekly_weather = {}

	hourly_weather = {}

	with forecast('af01e6071f266c8191d8446298b7f097',*boston) as boston:
		for day in boston.daily:
			day = dict(day = date.strftime(weekday,'%A'), sum=day.summary,tempMin=round(((day.temperatureMin)-32)*5/9), tempMax=round(((day.temperatureMax)-32)*5/9))
			
			weekday += timedelta(days=1)

			pic = ''
			summary =('{sum}'.format(**day).lower())

			if 'drizzle' in summary:
				pic = 'rain.png'
			elif 'rain' in summary:
				pic = 'rain.png'
			elif 'clear' in summary:
				pic = 'sun.png'
			elif 'partly cloudy' in summary:
				pic = 'partly-cloudy-day.png'
			else:
				pic= 'clouds.png'

			weekly_weather.update({'{day}'.format(**day):{'tempMin':'{tempMin}'.format(**day),'tempMax':'{tempMax}'.format(**day),'pic':pic}})


	today = weekly_weather[(date.today().strftime("%A"))]
	del weekly_weather[(date.today().strftime("%A"))]

	hour = datetime.now().hour

	location = forecast('af01e6071f266c8191d8446298b7f097', lat,lng) 
	i = 0

	hour_ = ''

	while hour<24:
		temp = round(((location.hourly[i].temperature)-32)*5/9)

		pic = ''
		summary =location.hourly[i].summary.lower()

		if 'drizzle' in summary:
			pic = 'rain.png'
		elif 'clear' in summary and hour>19:
			pic = 'crescent-moon.png'
		elif 'rain' in summary:
			pic = 'rain.png'
		elif 'clear' in summary:
			pic = 'sun.png'
		elif 'partly cloudy' in summary:
			pic = 'partly-cloudy-day.png'
		else:
			pic= 'clouds.png'

		if hour<12:
			hour_ = '{}am'.format(hour)
			hourly_weather.update({hour_:{'pic':pic,'temp':temp}})
			
		else:
			hour_ = '{}pm'.format(hour-12)
			hourly_weather.update({hour_:{'pic':pic,'temp':temp}})
			
		hour += 1
		i += 1


	return render(request,'home.html',{'weekly_weather':weekly_weather,'hourly_weather':hourly_weather,'today':today,'region':region})
	

	
Example #8
0
def home(request):

    geo_lookup = GeoLookup("458015c5b9b623034642993da2d3e712") #taking api from ipstack to detect location automatically
    location = geo_lookup.get_own_location()
    print(location) # we are not getting bangalore as location from this api, it is showing nelamangala, therefore we will be hardcoding the location

    lat = location['latitude']
    lng = location['longitude']
    region = location['region_name']

    city = 12.9716, 77.5937 #longitude and latitude of bengaluru according to google
    #city = lat,lng


    weekday = date.today()

    weekly_weather = {}
    hourly_weather = {}

    # 84ed95947b8889a445be094030dc2af3 - secret key from darksky to use their weather api

    with forecast('84ed95947b8889a445be094030dc2af3',*city) as city:
        for day in city.daily:
            tMin = (day.temperatureMin - 32) * 5/9 #this will convert fahrenheit to celsius, °C = (°F - 32) x 5/9
            tMax = (day.temperatureMax - 32) * 5/9 #this will convert fahrenheit to celsius, °C = (°F - 32) x 5/9
            day = dict(day = date.strftime(weekday,'%A'), sum = day.summary, tempMin = round(tMin), tempMax = round(tMax),)
            print('{day} --- {sum} -- {tempMin} - {tempMax}'.format(**day)) #this will get weather forecast on webserver, this is just to check
            weekday += timedelta(days=1)

            pic = ''
            summary = ('{sum}'.format(**day).lower())

            if 'drizzle' in summary:    #this will loop through and get the png's for the weather accordingly.
                pic = 'light-rain.png'  #the url is present on home.html, key and value will be taken from here.
            elif 'rain' in summary:
                pic = 'rain.png'
            elif 'clear' in summary:
                pic = 'sun.png'
            elif 'partly cloudy' in summary:
                pic = 'partly-cloudy-day.png'
            else:
                pic = 'clouds.png'

            weekly_weather.update({'{day}'.format(**day):{'tempMin':'{tempMin}'.format(**day),'tempMax':'{tempMax}'.format(**day),'pic':pic}})
            #weekly_weather as the name suggest will get the weekly weather update.

    today = weekly_weather[(date.today().strftime("%A"))]
    del weekly_weather[(date.today().strftime("%A"))]  #in the weekly weather we do not want to know todays weather, therefore deleting this.

    hour = datetime.now().hour
    location  = forecast('84ed95947b8889a445be094030dc2af3', 12.9716, 77.5937,)
    i = 0

    hour_ = ''

    while hour < 24: # this will get the hourly data

        temp1 = (location.hourly[i].temperature - 32) * 5/9

        temp = round(temp1)
        #print(temp)

        pic = ''
        summary = location.hourly[i].summary.lower()

        if 'drizzle' in summary:    #this will loop through and get the png's for the weather accordingly.
            pic = 'light-rain.png'  #the url is present on home.html, key and value will be taken from here.
        elif 'rain' in summary:
            pic = 'rain.png'
        elif 'clear' in summary:
            pic = 'sun.png'
        elif 'partly cloudy' in summary:
            pic = 'partly-cloudy-day.png'
        else:
            pic = 'clouds.png'

        if hour < 12:
            hour_ = '{}'.format(hour)
            hourly_weather.update({hour_:{'pic':pic,'temp':temp}})
            #print('{}am - {}'.format(hour,temp))
        else:
            hour_ = '{}'.format(hour)
            hourly_weather.update({hour_:{'pic':pic,'temp':temp}})
            #print('{}pm - {}'.format(hour,temp))

        hour+=1
        i+=1


    return render(request,'home.html',{'weekly_weather':weekly_weather,'hourly_weather':hourly_weather,'today':today,})
Example #9
0
def home(request):

    # city = 42.3601, 71.0589
    geo_lookup = GeoLookup("40d5d9284ed678d9bba68017704770bc")
    location = geo_lookup.get_own_location()

    lat = location['latitude']
    lng = location['longitude']
    region = location['region_name']

    city = lat, lng

    print(location)

    weekday = date.today()

    weekly_weather = {}
    hourly_weather = {}

    with forecast('fcbb70ecadd8b48599aca7e92529bf30', *city,
                  units="si") as city:
        for day in city.daily:
            day = dict(day=date.strftime(weekday, '%A'),
                       sum=day.summary,
                       tempMin=round(day.temperatureMin),
                       tempMax=round(day.temperatureMax))
            print('{day} ---- {sum} -- {tempMin} - {tempMax}'.format(**day))
            weekday += timedelta(days=1)

            pic = ''
            summary = ('{sum}'.format(**day).lower())

            if 'drizzle' in summary:
                pic = 'rain.png'
            elif 'rain' in summary:
                pic = 'rain.png'
            elif 'cloudy' in summary:
                pic = 'clouds.png'
            elif 'clear' in summary:
                pic = 'sun.png'
            elif 'partly cloudy' in summary:
                pic = 'partly-cloudy-day.png'
            elif 'humid' in summary:
                pic = 'partly-cloudy-day.png'
            else:
                pic = 'clouds.png'

            weekly_weather.update({
                '{day}'.format(**day): {
                    'tempMin': '{tempMin}'.format(**day),
                    'tempMax': '{tempMax}'.format(**day),
                    'pic': pic
                }
            })

    today = weekly_weather[(date.today().strftime("%A"))]
    del weekly_weather[(date.today().strftime("%A"))]

    print(today.get("tempMax"))

    hour = datetime.now().hour
    location = forecast('fcbb70ecadd8b48599aca7e92529bf30',
                        lat,
                        lng,
                        units="si")
    i = 0

    hour_ = ''

    while hour < 24:
        temp = round(location.hourly[i].temperature)

        pic = ''
        summary = location.hourly[i].summary.lower()

        if 'drizzle' in summary:
            pic = 'rain.png'
        elif 'rain' in summary:
            pic = 'rain.png'
        elif 'cloudy' in summary:
            pic = 'clouds.png'
        elif 'clear' in summary:
            pic = 'sun.png'
        elif 'partly cloudy' in summary:
            pic = 'partly-cloudy-day.png'
        elif 'humid' in summary:
            pic = 'partly-cloudy-day.png'
        else:
            pic = 'clouds.png'

        if hour < 12:
            hour_ = '{}am'.format(hour)
            hourly_weather.update({hour_: {'pic': pic, 'temp': temp}})
        else:
            hour_ = '{}pm'.format(hour - 12)
            hourly_weather.update({hour_: {'pic': pic, 'temp': temp}})

        hour += 1
        i += 1

    return render(
        request, 'home.html', {
            'weekly_weather': weekly_weather,
            'hourly_weather': hourly_weather,
            'today': today,
            'region': region
        })
Example #10
0
from django.shortcuts import render
from pyowm.commons.exceptions import *
from ipstack import GeoLookup  # using ipstack to find the user's exact ip address
import ipinfo  # using ipinfo to retrieve information on the ip's owner
import pyowm  # importing pyowm to receive weather data

owm = pyowm.OWM('0d92fe6673852fd95c9d1ff3a259685a')  # defining pyowm API key

mgr = owm.weather_manager()  # calling PyOWM weather manager

geo_lookup = GeoLookup(
    "1379a525f4c6d711990c5bb322c9f4ea")  # defining our API key for ipstack

location = geo_lookup.get_own_location(
)  # using the "get_own_location()" method to get the user's location

ip_address = location[
    'ip']  # using the 'ip' key of the location dictionary to retrieve our own ip_address


def index(request):
    if request.method == 'POST':
        city = str(request.POST["city"]
                   )  # if the POST method is used, do the following
        try:
            observation = mgr.weather_at_place(
                city)  # getting weather data from pyowm
            w = observation.weather  # defining the weather object
            temp_dict = w.temperature(
                'celsius')  # calling the temp dictionary from pyowm
            temp = int(temp_dict['temp']
Example #11
0
def home(request):

    geo_lookup = GeoLookup("41b1afd1f407de24e54e36d54ceca69c")
    location = geo_lookup.get_own_location()
    lat = location['latitude']
    lng = location['longitude']
    region = location['region_name']
    
    CITY = lat, lng
    
    api_key = '5cd0bb087cf49e0d8503c2dc342f7af1'
    weekday = date.today()

    weekly_weather = {}

    hourly_weather = {}

    with forecast(api_key, *CITY) as city:        
        for day in city.daily:
            day = dict(
            day = date.strftime(weekday, '%a'),
            sum = day.summary,
            tempMin = round((day.temperatureMin-32) * 5.0/9.0),
            tempMax = round((day.temperatureMax-32) * 5.0/9.0) 
            )
            # print('{day}: {sum} Temp range: {tempMin} - {tempMax} C'.format(**day))
            weekday += timedelta(days=1)

            pic = ''
            summary = ('{sum}'.format(**day).lower())

            if 'rain' in summary:
                pic = 'rain.png'
            elif 'cloudy' in summary:
                pic = 'cloudy.png'
            elif 'overcast' in summary:
                pic = 'partly-cloudy.png'
            elif 'clear' in summary:
                pic = 'sunny.png'
            else:
                pic = 'cloudy.png'
            
            weekly_weather.update({
            '{day}'.format(**day):{
                'sum':'{sum}'.format(**day),
                'tempMin':'{tempMin}'.format(**day), 
                'tempMax':'{tempMax}'.format(**day),
                'pic':pic  
            }})

    today = weekly_weather[(date.today().strftime('%a'))]
    del weekly_weather[(date.today().strftime("%a"))]

    
    hour = datetime.now().hour
    location = forecast(api_key, *CITY)
    i = 0

    hour_ = ''

    while hour < 24:

        temp = round((location.hourly[i].temperature-32)* 5.0/9.0)
        

        pic = ''
        summary = location.hourly[i].summary.lower()

        if 'rain' in summary:
            pic = 'rain.png'
        elif 'cloudy' in summary:
            pic = 'cloudy.png'
        elif 'overcast' in summary:
            pic = 'partly-cloudy.png'
        elif 'clear' in summary:
            pic = 'sunny.png'
        else:
            pic = 'cloudy.png'

        if hour < 12:
            hour_ = '{}am'.format(hour)
            hourly_weather.update({hour_:{'pic':pic,'temp':temp}})

        elif hour == 12:
            hour_ = '{}pm'.format(hour)
            hourly_weather.update({hour_:{'pic':pic,'temp':temp}})

        else:
            hour_ = '{}pm'.format(hour-12)
            hourly_weather.update({hour_:{'pic':pic,'temp':temp}})
            
        
        hour += 1
        i += 1


    return render(request, 'index.html', {'weekly_weather':weekly_weather, 'hourly_weather':hourly_weather, 'today':today, 'region':region })
Example #12
0
def home(request):
    geo_lookup = GeoLookup("3a29cf8ecc0d557689bf7365aaf81d7d")
    location = geo_lookup.get_own_location()
    print(location)
    return render(request, 'index.html')
Example #13
0
def main():

    #GET LOCATION
    geo_lookup = GeoLookup("3f6e3ea0f53c0a3eeb2ebd578f3d74f3")
    location = geo_lookup.get_own_location()
    lon = location['longitude']
    lat = location['latitude']
    city = location['city']

    print(city)

    #GET CURRENT WEATHER
    url = 'http://api.openweathermap.org/data/2.5/weather?lat={}&lon={}&units=imperial&appid=7acfccf49d5888267f2a1348496ac9a2'
    weather_response = requests.get(url.format(lat, lon)).json()

    #GET MARINE INFO
    marine_url = 'http://api.worldweatheronline.com/premium/v1/marine.ashx?key=7b48a0b9095643daa99232159211102&q={}, {}&format=json&tp=1'
    marine_response = requests.get(marine_url.format(lat, lon)).json()

    #GET CURRENT TIME
    now = datetime.now()
    current_time = int(now.strftime("%H"))
    current_minute = int(now.strftime("%M"))
    print("Current Time =", current_time, current_minute)

    if current_minute >= 45 and current_time != 23:
        current_time += 1

    print(current_time)

    #GET SUNRISE AND SUNSET INFO
    sunset_full_time = marine_response['data']['weather'][0]['astronomy'][0][
        'sunset']
    sunrise_full_time = marine_response['data']['weather'][0]['astronomy'][0][
        'sunrise']
    sunrise_code = int(sunrise_full_time[:2])
    sunset_code = int(sunset_full_time[:2])

    if sunset_full_time[-2:] == 'PM':
        sunset_code += 12

    if sunrise_full_time[-2:] == 'PM':
        sunrise_code += 12

    if current_time < sunset_code and current_time > sunrise_code:
        day = 'day'
    else:
        day = 'night'

    print(sunset_code, sunrise_code)

    #GET SPECIFIC DATA
    forecast = marine_response['data']['weather'][0]['hourly'][current_time]
    temp_f = str(round(weather_response['main']['temp']))
    water_temp_f = forecast['waterTemp_F']
    icon = 'images/world-weather-online-set/PNGs_128x128/' + day + '/' + forecast[
        'weatherCode']

    #CONTEXT
    marine_weather = {
        "temp": temp_f + '°F',
        "water": water_temp_f + '°F',
        "icon": icon,
    }

    context = ('marine_weather', marine_weather)

    return context