Beispiel #1
0
def astronauts_on_board_iss():
    """
    Returns a list of astronauts currently onboard the ISS 
    in a *.txt file (iss.txt)
    """
    # URL for the API to show astronauts onboard the ISS
    response_1 = urllib.request.urlopen(url_astro)
    result_1 = json.loads(response_1.read())

    file = open("iss.txt", "w")
    file.write("Currently, there are " + str(result_1["number"]) +
               " Astronauts aboard the ISS.\n" + "\nThey are: " + "\n")

    people = result_1['people']

    # loop over list of astros and write to file
    for person in people:
        file.write("\n - " + person['name'] + "\n")

    # get my longitude and latitude
    g = geocoder.ipinfo("me")
    file.write("\nYour current latitude / longitude is: " + str(g.latlng))
    file.write("\nYour current location is: " + g.city + ", " + g.state +
               ", " + g.country)

    # close file
    file.close()

    # open file
    return webbrowser.open("iss.txt")
Beispiel #2
0
def index():
    try:
        client_ip = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)
        client_geo = geocoder.ipinfo(client_ip)
        lat, lon = client_geo.latlng
        timezone = client_geo.json['raw']['timezone']
        client_tz = pytz.timezone(timezone)
    except:
        return 'Sorry, we were unable to locate you.'

    try:
        api_url = f"{WEATHER_API_URL}?lat={lat}&lon={lon}&APPID={WEATHER_API_KEY}&units=metric"
        resp = requests.get(api_url)
        if resp.status_code == 200:
            weather_dict = json.loads(resp.text)
            weather_attrib = [
                'lat', 'lon', 'name', 'temp', 'humidity', 'pressure'
            ]
            weather_values = find_weather_values(weather_dict, weather_attrib)
            weather_values['timestamp'] = datetime.now(client_tz)
            return render_template('weather.json', items=weather_values)
        return 'Something went wrong with WeatherAPI or...\nTry again, please!'
    except:
        pass

    return 'Something went wrong.'
    def __init__(self):
        g = geocoder.ipinfo('me')

        # this variable contains user's location information.
        self.location = g.state

        area = Label(screen1.main_frame, text=self.location)
        area.config(font=("Courier", 12), bg='#FF847C')
        area.grid(row=2, column=0, pady=20)
Beispiel #4
0
def display_yelp_api(user_id):
    curr_loc = geocoder.ipinfo('me')
    input_lat = str(curr_loc.latlng[0])
    input_long = str(curr_loc.latlng[1])
    input_rad_in_mi = 1
    # !Yelps input radius is in meters and must be an int. Convert miles to meters
    input_rad_in_mtr = math.floor(input_rad_in_mi * 1609.34)

    #convert floats to strings for request payload
    payload_rad = str(input_rad_in_mtr)

    # GET request params
    payload = {'latitude': input_lat, 'longitude': input_long, 'radius': input_rad_in_mtr, 'open_now': 'true'}

    # Adding API Key to request header
    headers = {'Authorization': 'Bearer 5tH0TUqZtFrYsX0Jp31k7McHUVxdnV4KEojl4uPzJZPVfMzubVRLCSmAeIMRg51AnzBxQMltAU33ATktN7i3KMV1MqeQRsHL0kfOZhsHcR1zjASbQ5CXofzAHQSPYHYx'}

    # GET request
    yelp_response = requests.get(yelp_base_url, params=payload, headers=headers)
    yelp_output = yelp_response.json()
    businesses = yelp_output["businesses"]

# parse JSON result
    businesses_list = []
    coords_list = []

    for x in range(len(businesses)):
        yelp_id = businesses[x]["id"]
        business_name = businesses[x]["name"]
        business_addr = businesses[x]["location"]["display_address"]
        
        business_coord = (businesses[x]["coordinates"]["latitude"], businesses[x]["coordinates"]["longitude"])
        coords_list.append(business_coord)
        
        business_dist = math.ceil(businesses[x]["distance"])
        
        # store as tuple, append to list
        businesses_list.append((yelp_id, business_name, business_addr, business_coord, business_dist))
        
    businesses_list.sort(key=itemgetter(4))

    api_key = "AIzaSyApeNoZj_DRHq9mCZ8aEnkZx1IHqpPUt_Q"    
    gmap = gmplot.GoogleMapPlotter(input_lat, input_long, 14, apikey=api_key)
    attractions_lats, attractions_lngs = zip(*coords_list)
    gmap.scatter(attractions_lats, attractions_lngs, color='#0B6EEF', size=15, marker=True)
    path = os.path.abspath(os.getcwd())
    path += "/templates/"
    gmap.draw(path+'businesses_map.html')

    if request.method == "POST":
        if request.form.get('visualize') == 'Map':
            return render_template('businesses_map.html')
        else:
            return render_template('businesses.html', input_lat=input_lat, input_long=input_long, input_rad_in_mi=input_rad_in_mi, businesses_list = businesses_list)
    else:
        return render_template('businesses.html', input_lat=input_lat, input_long=input_long, input_rad_in_mi=input_rad_in_mi, businesses_list = businesses_list)
Beispiel #5
0
 def getlocation(self):
     global latlong
     g = geocoder.ipinfo('me')
     latlong=g.latlng
     data={}
     data["lat"]=latlong[0]
     data["long"]=latlong[1]
     data["city"]=g.current_result.city
     with open('web/location.json', 'w') as outfile:
         json.dump(data, outfile)
Beispiel #6
0
def findMyPlace():

    # keywords to filter results to gather from query search
    query = 'me'

    # get a query of google map search using a dictionary url and application secret key for authorization
    r = rq.get(url + 'query=' + query + '&key=' + api_key)

    # get information of data from a list of results as array of strings
    y = r.json()['results']

    # print("Format: ", y[0],"\n") -> The list of query columns: formatted_address, geometry(lat,lng),
    # viewport(northeast(lat,lng)), northwest(lat,lng), icon, id, name,
    # photos(height,html_attributions,photo_reference,width), place_id, reference, types, political

    # Fornat: "My Place: ",y[0]['formatted_address'], " Location:", y[0]['geometry']['location']['lat'], " ", y[0]['geometry']['location']['lng'])

    return geocoder.ipinfo('me').latlng
Beispiel #7
0
def redirect_link(shorturl):
    shortenedurl = ShortenedLinks.query.filter_by(
        shorten_url=shorturl).first_or_404()

    if shortenedurl:
        # do not add the crawler bots in the clicks (beta testing)
        if request.headers.get('Sec-Fetch-Site') and request.headers.get(
                'Sec-Fetch-Mode') and request.headers.get('Sec-Fetch-Dest'):
            click = Clicks(
                client_ip=request.environ['HTTP_X_FORWARDED_FOR'],
                location=geocoder.ipinfo(
                    request.environ['HTTP_X_FORWARDED_FOR']).country,
                referrer=parse_url(request.referrer),
                link=shortenedurl,
                shortlink_author=shortenedurl.author)
            db.session.add(click)
            db.session.commit()

    return redirect(shortenedurl.long_url)
def test_ipinfo():
    g = geocoder.ipinfo(location)
    assert g.ok
    osm_count, fields_count = g.debug()[0]
    assert osm_count >= 4
    assert fields_count >= 12
Beispiel #9
0
def test_ipinfo():
    g = geocoder.ipinfo(ip)
    assert g.ok
def test_ipinfo():
    g = geocoder.ipinfo(ip)
    assert g.ok
Beispiel #11
0
                    'ta': 'tamil',
                    'te': 'telugu',
                    'th': 'thai',
                    'tr': 'turkish',
                    'uk': 'ukrainian',
                    'ur': 'urdu',
                    'ug': 'uyghur',
                    'uz': 'uzbek',
                    'vi': 'vietnamese',
                    'cy': 'welsh',
                    'xh': 'xhosa',
                    'yi': 'yiddish',
                    'yo': 'yoruba',
                    'zu': 'zulu', }

coordinate_obj = geocoder.ipinfo('me')
my_coords = coordinate_obj.latlng	#current coord

print("my coords --> ",my_coords)


def to_radians(theta):
	return theta * (math.pi/180)

#returns (lat, lon) at a dist r, at angle theta
def displace(r, theta):		# args --> (in km, in degrees)
	R = 6378.1 #Radius of the Earth in km
	brng = to_radians(theta) #Bearing is 90 degrees converted to radians.
	d = r #Distance in km

	#lat2  52.20444 - the lat result I'm hoping for
Beispiel #12
0
def location():
    latitude, longitude = geocoder.ipinfo("me").latlng
    city = rg.search((latitude, longitude), verbose=False)
    return city[0]["name"]
Beispiel #13
0
import geocoder
print(geocoder.ipinfo('me'))
def simulatedGPS():
    return geocoder.ipinfo('me').latlng
Beispiel #15
0
def events_near_me():
    if not session.get('username'):
        return redirect(url_for("signin", next=request.url_rule))

    form = EventsNearMeForm(request.form)

    if request.args.get('radius'):
        form.radius.data = request.args.get('radius')
    if request.args.get('limit'):
        form.limit.data = request.args.get('limit')

    if request.method == 'post':
        return redirect(
            url_for('events_near_me',
                    radius=form.radius.data,
                    limit=form.limit.data))

    connection = mysql.get_db()
    cursor = connection.cursor()

    # get latitude and longitude of user's ip address
    user_loc_tup = None
    user_loc = None

    provided_ips = request.headers.getlist("X-Forwarded-For")
    ip = provided_ips[0] if len(provided_ips) > 0 else 'me'
    g = ipinfo(ip)
    if g and g.latlng and len(g.latlng) > 0:
        user_loc_tup = tuple(g.latlng)

    if user_loc_tup == None or len(user_loc_tup) == 0:
        user_loc_tup = (40.1164, -88.2434)  # lat/lng of Champaign
    user_loc = {"lat": user_loc_tup[0], "lng": user_loc_tup[1]}

    # calculate distances
    locs = []
    attrs = "eid, title, lat, lng"
    retlen = cursor.execute("SELECT {} FROM Event".format(attrs))
    if retlen > 0:
        for row in cursor.fetchall():
            eid = row[0]
            title = row[1]
            event_loc = (row[2], row[3])

            if event_loc and event_loc[0] and event_loc[1]:
                dist = haversine(user_loc_tup, event_loc, miles=True)
                if dist <= float(form.radius.data):
                    dict = {
                        "eid": eid,
                        "title": title,
                        "dist": dist,
                        "loc": {
                            "lat": event_loc[0],
                            "lng": event_loc[1]
                        }
                    }
                    locs.append(dict)
        locs.sort(key=lambda loc: loc["dist"])
        end_row = int(form.limit.data) if len(locs) >= int(
            form.limit.data) else len(locs)
        markers = locs[0:end_row]

    return render_template('events_near_me.html',
                           user_loc=user_loc,
                           markers=markers,
                           form=form,
                           key=GMAPS_KEY)
Beispiel #16
0
def visitor(sender, user, request, **kwargs):
    if hasattr(request, 'user') and user_is_authenticated(request.user):
        if request.user_agent.is_mobile:
            device_type = "Mobile"
        elif request.user_agent.is_tablet:
            device_type = "Tablet"
        elif request.user_agent.is_touch_capable:
            device_type = "Touch"
        elif request.user_agent.is_pc:
            device_type = "PC"
        elif request.user_agent.is_bot:
            device_type = "Bot"
        else:
            device_type = "Unknown"

        browser = request.user_agent.browser.family
        browser_version = request.user_agent.browser.version_string

        os_info = request.user_agent.os.family
        os_info_version = request.user_agent.os.version_string

        device_name = request.user_agent.device.family
        device_name_brand = request.user_agent.device.brand
        device_name_model = request.user_agent.device.model

        ipaddress = request.META.get("HTTP_X_FORWARDED_FOR", None)
        if ipaddress:
            ipaddress = ipaddress.split(", ")[0]
        else:
            ipaddress = request.META.get("REMOTE_ADDR", "")
        if not request.session.exists(request.session.session_key):
            request.session.create()
        session = Session.objects.get(session_key=request.session.session_key)
        city = None
        state = None
        country = None
        latitude = None
        longitude = None
        try:
            if not request.POST['latitude'] == '':
                latitude = request.POST['latitude']
                longitude = request.POST['longitude']
                g = geocoder.google([latitude, longitude], method='reverse')
                city = g.city
                state = g.state_long
                country = g.country_long
            else:
                location = geocoder.ipinfo(ipaddress)
                if location:
                    city = location.city
                    state = location.state
                    country = location.country
        except Exception as e:
            pass
        username = request.user
        unique_computer = request.META.get("PROCESSOR_IDENTIFIER", None)
        Visitor.objects.create(device_type=device_type, name=username, ipaddress=ipaddress, browser=browser,
                               browser_version=browser_version, os_info_version=os_info_version,
                               os_info=os_info,
                               device_name=device_name, city=city, state=state, country=country,
                               device_name_brand=device_name_brand, device_name_model=device_name_model,
                               unique_computer_processor=unique_computer, session=session, latitude=latitude,
                               longitude=longitude)
import socket
import requests
import geocoder

print("Örnek Website: https://google.com")
url = input("Website giriniz: ")
httporhttps = url[:7]
httporhttps2 = httporhttps.find("s")

if httporhttps2 == -1:
    ipadd = socket.gethostbyname(url[7:])
    g = geocoder.ipinfo(ipadd)
    print("Ülke: ", g.country)
    print("Şehir: ", g.city)
elif httporhttps2 != -1:
    ipadd = socket.gethostbyname(url[8:])
    g = geocoder.ipinfo(ipadd)
    print("Ülke: ", g.country)
    print("Şehir: ", g.city)

else:

    print("Hatalı giriş...")
counterclock = 0
if direction:
    counterclock = ledCount

hourMargin = hyperion.args.get('hour-margin', 2)
minuteMargin = hyperion.args.get('minute-margin', 1)
secondMargin = hyperion.args.get('second-margin', 0)

hourColor = hyperion.args.get('hour-color', (255, 0, 0))
minuteColor = hyperion.args.get('minute-color', (0, 255, 0))
secondColor = hyperion.args.get('second-color', (0, 0, 255))

latitude = hyperion.args.get('latitude', None)
longitude = hyperion.args.get('longitude', None)
if not (latitude or longitude):
    g = geocoder.ipinfo('me')
    if g.latlng:
        latitude = g.latlng[0]
        longitude = g.latlng[1]

owmWait = 0
owmAPIkey = hyperion.args.get('owmAPIkey', '')
if owmAPIkey and (latitude or longitude):
    owm = pyowm.OWM(owmAPIkey)  # You MUST provide a valid API key
    secondColor = myTemp(latitude, longitude)

marker = ledCount / 4
markers = [
    0 + offset,
    int(marker + offset) % ledCount,
    int(2 * marker + offset) % ledCount,
def iplocate():
    host = raw_input('Enter your ip address:')
    localisation = geocoder.ipinfo(host)
    i = localisation.json
    for key, value in i.items():
        print key, ":", value
def get_loc(ip):
    return geocoder.ipinfo(ip).latlng