44 lines
1.5 KiB
Python
44 lines
1.5 KiB
Python
import json
|
|
import math
|
|
from pathlib import Path
|
|
|
|
from flask import Response, request
|
|
from flask.views import MethodView
|
|
|
|
from hub_api.config import Config
|
|
from hub_api.helpers.session_helper import refresh_session
|
|
|
|
|
|
class Reverse(MethodView, Config):
|
|
def __init__(self):
|
|
super().__init__()
|
|
self._reverse_path = Path(Path(__file__).parent.parent / 'data/cities15000.txt').resolve()
|
|
|
|
def get(self, latitude: float, longitude: float):
|
|
session_id = request.headers.get('session_id', None)
|
|
token = request.headers.get('token', None)
|
|
application_uuid = request.headers.get('application_uuid', None)
|
|
_session = refresh_session(session_id, token, application_uuid)
|
|
if _session is None:
|
|
return Response(json.dumps({'error': 'unauthorized'}), status=403)
|
|
token = {'token': _session['token']}
|
|
latitude = float(latitude)
|
|
longitude = float(longitude)
|
|
distance = math.inf
|
|
country = 'unknown'
|
|
city = 'unknown'
|
|
with open(self._reverse_path, 'r') as f:
|
|
for line_number, line in enumerate(f):
|
|
fields = line.split('\t')
|
|
file_city_name = fields[1]
|
|
file_latitude = float(fields[4])
|
|
file_longitude = float(fields[5])
|
|
file_country_code = fields[8]
|
|
new_distance = math.sqrt(pow((latitude-file_latitude),2) + pow((longitude-file_longitude),2))
|
|
if distance > new_distance:
|
|
distance = new_distance
|
|
country = file_country_code
|
|
city = file_city_name
|
|
return Response(json.dumps({'country': country, 'city':city}), status=200, headers=token)
|
|
|