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)
def geolocation(target): try: geo_lookup = GeoLookup( "8b1261f4d109cc1673a33da38adf9d28") # Klucz do api location = geo_lookup.get_location( target) # zebranie informacji dla ip if location is None: return "Nie udało się znaleźć lokalizacji" # jesli nie uda się znaleźć lokalizacji else: geo_info = { "Kod kontynentu": "", "Nazwa kontynentu": "", "Kod kraju": "", "Nazwa kraju": "", "Kod regionu": "", "Nazwa regionu": "", "Miasto": "", "Kod pocztowy": "", "Szerokość geograficzna": "", "Długość geograficzna": "" } del location['location'], location['ip'], location['type'] for key, value in zip(geo_info.keys(), location.values()): geo_info[key] = value return (geo_info) except Exception as e: return e
def GeolocateIP(ip): # geo_data = GeoLookup("<IP Stack API Key Goes Here>") # geo_location = geo_data.get_location(ip) # location_string = "" # location_string += "IP: " location_string += geo_location['ip'] location_string += '\n' location_string += "City: " location_string += geo_location['city'] location_string += '\n' location_string += "State: " location_string += geo_location['region_name'] location_string += '\n' location_string += "Country: " location_string += geo_location['country_name'] location_string += '\n' location_string += "Zip: " location_string += geo_location['zip'] location_string += '\n' location_string += "Latitude: " location_string += str(geo_location['latitude']) location_string += '\n' location_string += "Longitude: " location_string += str(geo_location['longitude']) location_string += '\n' # return location_string
def login(): #User reached route via POST (as by submitting a form via POST) if request.method == "POST": # get client IP address ip = request.form.get('ip') # connect to the API geo_lookup = GeoLookup(os.getenv("API_KEY")) # get the location details location = geo_lookup.get_location(ip) # Get user city city = location['city'] # Get user country country = location['country_name'] # Ensure username was submitted if not request.form.get("username"): return sorry("Please enter your name") # Ensure password was submitted elif not request.form.get("password"): return sorry("Please enter password") # Query database for username rows = db.execute("SELECT * FROM users WHERE name = :username", { "username": request.form.get("username") }).fetchall() # Ensure username exists and password is correct if len(rows) != 1 or not check_password_hash( rows[0]["hash"], request.form.get("password")): return sorry("invalide username or/and password") # Remember which user has logged in session["user_id"] = rows[0]["id"] # Update user location with current data db.execute( "UPDATE users SET country = :country, city = :city WHERE id = :user", { "country": country, "city": city, "user": session["user_id"] }) db.commit() # Redirect user to search page return redirect("/search") # User reached route via GET (as by clicking a link or via redirect) else: return render_template("login.html")
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})
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 register(request): if request.method == "POST": hobbies = Hobbi.objects.all() username = request.POST["username"] password = request.POST["password"] email = "*****@*****.**" h = request.POST["hobby"] year = int(request.POST["age"]) ip = request.POST["ip"] geo_lookup = GeoLookup(os.getenv("API_KEY")) location = geo_lookup.get_location(ip) country = location["country_name"] city = location["city"] today = datetime.now() age = today.year - year confirm = request.POST["confirm"] if password != confirm: return render(request, "hobbibi/register.html", { "message": "Password does not match", "hobbies": hobbies }) try: user = User.objects.create_user(username, email, password) user.age = age user.city = city user.country = country user.save() ho = Hobbi.objects.get(id=h) hobbi = Hobbies.objects.create(user=user, hobbi=ho) hobbi.save() except IntegrityError: return render(request, "hobbibi/register.html", { "message": "Username already taken", "hobbies": hobbies }) login(request, user) return HttpResponseRedirect(reverse('search')) else: hobbies = Hobbi.objects.all() return render(request, "hobbibi/register.html", {"hobbies": hobbies})
def login_view(request): if request.method == "POST": username = request.POST["username"] password = request.POST["password"] ip = request.POST["ip"] geo_lookup = GeoLookup(os.getenv("API_KEY")) location = geo_lookup.get_location(ip) country = location["country_name"] city = location["city"] user = authenticate(request, username=username, password=password) if user is not None: user = User.objects.get(username=username) user.country = country user.city = city user.save() login(request, user) return HttpResponseRedirect(reverse("search")) else: return render(request, "hobbibi/login.html", {"message": "Invalid username and/or password."}) else: return render(request, "hobbibi/login.html")
def get_location_data(self, site): if not site: logger.error(f'{site} cannot be empty') raise ValueError site_type = self.payload_validation(site) try: geo_lookup = GeoLookup(settings.IPSTACK_KEY) logger.debug('GeoLookup connection established') except Exception: logger.error('IPStack does not response') raise IPStackError('IPStack does not response') data = geo_lookup.get_location(site_type) if not data['continent_name'] and not data['country_name'] and not data['region_name']: logger.error(f'Site {site_type} does not exist') raise ValueError else: logger.debug(f'Site {site_type} exists') return data
extract_queries(dic_imagesJSP) extract_queries(dic_textJSP) dic_all_queries = { k: v for k, v in sorted(dic_all_queries.items(), key=lambda item: item[1]) } with open('list_queries.txt', 'w') as f: print(dic_all_queries, file=f) ###Process the list of users to get the country and city of the IP address ##We used the ipstack. More info: https://ipstack.com/ ##10.000 requests/month key_geolookup = args['key'] geo_lookup = GeoLookup(key_geolookup) ##Process each user to get the country and city and save the result in a list for elem in list_users: IP = elem.split(' &&&& ')[0] if IP not in list_users_processed_country: try: information = geo_lookup.get_location(IP) country = information["country_name"] city = information["city"] list_users_processed_country[IP] = [country, city] except: print( "ERROR Limited Request per Month. Wait to save the IPs processed in a file" )
import pytz 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()
def __init__(self, cfg: SimpleNamespace, storage_dir: Path): self.logger = logging.getLogger(__name__) self.logger.setLevel(logging.getLogger("paperback").level) self.logger.info("initializing papertext_auth module") self.logger.debug("using storage dir %s", storage_dir) self.logger.debug("using config %s", cfg) self.storage_dir: Path = storage_dir self.cfg: SimpleNamespace = cfg self.logger.debug("updating crypto context") crypto_context.update(default=cfg.hash.algo) self.logger.info("updated crypto context") self.logger.debug("connecting to ipstack") self.ip2geo: GeoLookup = GeoLookup(cfg.IPstack_api_key) self.logger.info("connected to ipstack") self.logger.debug("getting JWT keys") self.private_key_file: Path = self.storage_dir / "private.pem" self.public_key_file: Path = self.storage_dir / "public.pem" self.private_key: bytes self.public_key: bytes if cfg.token.generate_keys: self.logger.debug("option for generation keys is enabled") if self.public_key_file.exists(): self.logger.warning("public key exist, saving it") bak_public_key_file = self.storage_dir / "public.pem.bak" self.public_key_file.rename(bak_public_key_file) self.public_key_file.touch(exist_ok=True) if self.private_key_file.exists(): self.logger.warning("private key exist, saving it") bak_private_key_file = self.storage_dir / "private.pem.bak" self.private_key_file.rename(bak_private_key_file) self.private_key_file.touch(exist_ok=True) if not (self.public_key_file.exists() and self.private_key_file.exists()): self.logger.debug("no keys found") self.public_key_file.touch(exist_ok=True) self.private_key_file.touch(exist_ok=True) self.logger.debug("generating new keys") self.private_key, self.public_key = self.generate_keys(cfg.token.curve) self.logger.debug("saving new keys") self.private_key_file.write_bytes(self.private_key) self.public_key_file.write_bytes(self.public_key) else: if self.public_key_file.exists() and self.private_key_file.exists(): self.logger.debug("both keys are present") else: self.logger.error("one of the keys if missing") raise FileExistsError("one of the keys if missing") self.private_key, self.public_key = self.read_keys(cfg.token.curve) self.logger.info("acquired JWT keys") self.logger.debug("setting up database") database_url: str = ( f"postgresql://{self.cfg.db.username}:{self.cfg.db.password}@" f"{self.cfg.db.host}:{self.cfg.db.port}/{self.cfg.db.db}" ) self.logger.debug("database url: %s", database_url) self.logger.debug("connecting to database") self.database: Database = Database(database_url) self.logger.debug("connected to database") self.engine: sa.engine.Engine = sa.create_engine(database_url) self.logger.debug("setting up tables") self.metadata: sa.MetaData = sa.MetaData(bind=self.engine) self.users: sa.Table = sa.Table( "users", self.metadata, sa.Column("user_id", sa.String(256), unique=True, primary_key=True), sa.Column("email", sa.String(256), unique=True, nullable=True), sa.Column("hashed_password", sa.Text()), sa.Column("user_name", sa.String(256)), sa.Column("level_of_access", sa.Integer()), sa.Column( "member_of", sa.String(256), sa.ForeignKey("organisations.organisation_id"), ), extend_existing=True, ) self.organisations: sa.Table = sa.Table( "organisations", self.metadata, sa.Column( "organisation_id", sa.String(256), unique=True, primary_key=True, ), sa.Column("organisation_name", sa.Text()), extend_existing=True, ) self.tokens = sa.Table( "tokens", self.metadata, sa.Column("token_uuid", sa.LargeBinary(16), primary_key=True, unique=True), sa.Column("location", sa.Text()), sa.Column("device", sa.Text()), sa.Column( "issued_by", sa.String(256), sa.ForeignKey("users.user_id"), ), sa.Column("issued_at", sa.Text()), extend_existing=True, ) self.invitation_codes = sa.Table( "invitation_codes", self.metadata, sa.Column( "invitation_code_uuid", sa.LargeBinary(16), primary_key=True, unique=True, ), sa.Column( "code", sa.Text(), unique=True, ), sa.Column( "issuer_id", sa.String(256), sa.ForeignKey("users.user_id"), ), sa.Column( "add_to", sa.String(256), sa.ForeignKey("organisations.organisation_id"), ), sa.Column( "used_times", sa.Integer, ), extend_existing=True, ) self.metadata.create_all(self.engine) self.logger.info("set up tables") self.logger.debug("creating publiv organisation") self.public_org: Dict[str, str] = self.create_public_org() self.logger.info("created publiv organisation")
#Determining Rasberry Pi's Location from ipstack import GeoLookup geo_lookup = GeoLookup("367b4e6fe41e712cfd85feb52af4cb11") location = geo_lookup.get_own_location() print(location.get('latitude')) print(location.get('longitude'))
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})
import json import webhook_listener from discord_webhook import DiscordWebhook, DiscordEmbed import pprint import requests import time import configparser from ipstack import GeoLookup # parse config file config = configparser.ConfigParser() config.read('config.ini') # globals discord_webhook_url = config['discord']['url'] geo_lookup = GeoLookup(config['geolookup']['api']) plex_authtoken = config['plex']['token'] plex_url_header = config['plex']['url'] def process_post_request(request, *args, **kwargs): # check user agent header - send to proper function handler agent = request.headers['User-Agent'] if agent.startswith("PlexMediaServer"): # plex print("This is a Plex webhook\n") handle_plex_wh(kwargs) return elif agent.startswith("Ombi"): # ombi print("This is an Ombi webhook\n")
from ipstack import GeoLookup geo_lookup = GeoLookup("acecac3893c90871c3") location = geo_lookup.get_location("github.com") print(location) # Lookup a location for an IP Address # and catch any exceptions that might # be thrown try: # Retrieve the location information for # github.com by using it's hostname. # # This function will work with hostnames # or IP addresses. location = geo_lookup.get_location("github.com") # If we are unable to retrieve the location information # for an IP address, null will be returned. if location is None: print("Failed to find location.") else: # Print the Location dictionary. print(location) except Exception as e: print(e)
from ipstack import GeoLookup # Create the GeoLookup object using your API key. geo_lookup = GeoLookup("Your acess key for the Api here") # Create and get the ip or website neede Ip_or_Website = input( 'please enter a website(ex google.com) or Ip address to get the location it came from: ' ) def get_lacation_of(Ip_or_Website): try: # Retrieve the location information for # any website by using it's hostname. # or by IP adrees # This function will work with hostnames # or IP addresses. location = geo_lookup.get_location(Ip_or_Website) # If we are unable to retrieve the location information # for an IP address, null will be returned. if location is None: print("Failed to find location.") else: # Print the Location dictionary. for keys, values in location.items(): print(keys + ':') print(values) except Exception as e:
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 })
def home(request): geo_lookup = GeoLookup("3a29cf8ecc0d557689bf7365aaf81d7d") location = geo_lookup.get_own_location() print(location) return render(request, 'index.html')
def orient(ip): #geo_lookup = GeoLookup("431c444c2d03ca049a4356d7d7c897b7") geo_lookup = GeoLookup("f02b34fc34b84c40be72c2299657cef0") location = geo_lookup.get_location(ip) return(location)
def register(): # Show the register page # Query database for list of all hobbies hobbies = db.execute("SELECT * FROM hobbies ORDER BY name ASC").fetchall() # user reached route via POST (as by submitting a form via POST) if request.method == "POST": # Ensure name was provided if not request.form.get("username"): return sorry("must provide a name") # Ensure password was provided elif not request.form.get("password"): return sorry("must provide a password") # Ensure password was confirmed elif request.form.get("password") != request.form.get("confirm"): return sorry("passwords do not match") # Ensure year of birth was provided elif not request.form.get("year"): return sorry("Please enter your birth year") # Ensure hobby was provided elif not request.form.get("hobby"): return sorry("Please select a hobby") # Ensure App was provided elif not request.form.get("app"): return sorry("Please provide an App") # Ensure link was provided elif not request.form.get("link"): return sorry("Please provide a link to your account in the app") # Query database for same username rows = db.execute("SELECT * FROM users WHERE name = :username", { "username": request.form.get("username") }).fetchall() # Ensure the user does not already exist if len(rows) != 0: return sorry("username already exists") # hash the password before saving it i the database hashed = generate_password_hash(request.form.get("password"), method='pbkdf2:sha256', salt_length=8) # checking the current year currentyear = datetime.utcnow().year # Calculating user age age = int(currentyear) - int(request.form.get("year")) # Getting name from the form name = request.form.get("username") # get client IP address ip = request.form.get('ip') # connect to the API geo_lookup = GeoLookup(os.getenv("API_KEY")) # get the location details location = geo_lookup.get_location(ip) # Get user city city = location['city'] # Get user country country = location['country_name'] # Getting app from the form app = request.form.get("app") # Getting hobby from the form h = request.form.get("hobby") # Getting link from the form link = request.form.get("link") # Adding user information useres table db.execute( "INSERT INTO users (name, hash, age, country, city, app, link) VALUES (:name, :hashed, :age, :country, :city, :app, :link)", { "name": name, "hashed": hashed, "age": age, "country": country, "city": city, "app": app, "link": link }) db.commit() # Query database for assigned user id row = db.execute("SELECT id FROM users WHERE name = :name", { "name": name }).fetchone() # Adding user hobby to hobby table db.execute("INSERT INTO hobby (hobby, user_id) VALUES (:hobby, :user)", { "hobby": h, "user": row[0] }) db.commit() # Remember which user has logged in session["user_id"] = row[0] # Riderict to search page return redirect("/search") # user reached route via GET else: # showing register page and providing lists of countries, cities and hobbies return render_template("register.html", hobbies=hobbies)
from app import settings from ipstack import GeoLookup from rest_framework import exceptions geolookup_client = GeoLookup(settings.IPSTACK_PRIVATE_KEY) class GeolocationClientError(exceptions.APIException): pass def remove_url_schema(field): """ Remove from URL address doesn't necessary by GeoLookups library, schema. """ if 'url' == field['type']: if "://" in field['value']: field['value'] = field['value'].split("://")[1] return field def get_geolookup_data(field): """ Make call to the external API service. """ geolookup_client.find_hostname() field = remove_url_schema(field) # import pdb; pdb.set_trace() try:
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']
from ipstack import GeoLookup geo_lookup = GeoLookup("8cf95a2a585a8f2bb223a3c2fe6a45c0")
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 })
from django.shortcuts import render from .models import Song import requests, json, csv from ipstack import GeoLookup import socket geo_lookup = GeoLookup("39f6234e3d9c6d69e5c561c790b129bc") def home(request): location = geo_lookup.get_own_location() country = location['country_name'] flag_link = location['location']['country_flag'] """ with open('musicplayer/Country_Flags.csv', 'r') as csv_file: csv_reader = csv.reader(csv_file) for line in csv_reader: if country == line[0]: flag_link = line[2] """ context = { 'flag_link': flag_link, 'country': country, } return render(request, 'musicplayer/home.html', context) def about(request): return render(request, 'musicplayer/about.html')
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)
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,})
def current_location_weather(): geo_lookup = GeoLookup("9ff825aee8c78758e19180acda87060c") location = geo_lookup.get_own_location() coords = (location["latitude"], location["longitude"]) return WeatherData(coords, "coords")
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