Bug fix in meb session
Added new reverse method to remove dependency from openstreet maps
This commit is contained in:
parent
5fc9678f14
commit
48a7f28404
@ -18,7 +18,7 @@ import hub_api.helpers.session_helper as sh
|
|||||||
from hub_api.control.session import SessionStart, SessionEnd, KeepSessionAlive
|
from hub_api.control.session import SessionStart, SessionEnd, KeepSessionAlive
|
||||||
from hub_api.control.uptime import Uptime
|
from hub_api.control.uptime import Uptime
|
||||||
from hub_api.buildings.meb import Meb
|
from hub_api.buildings.meb import Meb
|
||||||
|
from hub_api.geolocation.reverse import Reverse
|
||||||
|
|
||||||
sh.begin_time = datetime.datetime.now()
|
sh.begin_time = datetime.datetime.now()
|
||||||
app = flask.Flask('cerc_api')
|
app = flask.Flask('cerc_api')
|
||||||
@ -35,6 +35,9 @@ api.add_resource(KeepSessionAlive, '/v1.4/session/keep_alive')
|
|||||||
# Buildings
|
# Buildings
|
||||||
api.add_resource(Meb, '/v1.4/buildings/meb')
|
api.add_resource(Meb, '/v1.4/buildings/meb')
|
||||||
|
|
||||||
|
# GeoLocation
|
||||||
|
api.add_resource(Reverse, '/v1.4/geolocation/reverse/<latitude>/<longitude>', endpoint='reverse')
|
||||||
|
|
||||||
with open("hub_api/docs/openapi-specs.yml", "r") as stream:
|
with open("hub_api/docs/openapi-specs.yml", "r") as stream:
|
||||||
swagger_config = {
|
swagger_config = {
|
||||||
"headers": [],
|
"headers": [],
|
||||||
|
@ -1,9 +1,11 @@
|
|||||||
import json
|
import json
|
||||||
|
|
||||||
from flask import Response, request
|
from flask import Response, request
|
||||||
from flask_restful import Resource
|
from flask_restful import Resource
|
||||||
|
|
||||||
from hub_api.helpers.session_helper import active_session, session
|
|
||||||
from hub_api.config import Config
|
from hub_api.config import Config
|
||||||
|
from hub_api.helpers.session_helper import session, refresh_session
|
||||||
|
|
||||||
|
|
||||||
class Meb(Resource, Config):
|
class Meb(Resource, Config):
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
@ -16,21 +18,23 @@ class Meb(Resource, Config):
|
|||||||
session_id = request.headers.get('session_id', None)
|
session_id = request.headers.get('session_id', None)
|
||||||
token = request.headers.get('token', None)
|
token = request.headers.get('token', None)
|
||||||
application_uuid = request.headers.get('application_uuid', None)
|
application_uuid = request.headers.get('application_uuid', None)
|
||||||
if active_session(session_id, token, application_uuid):
|
_session = refresh_session(session_id, token, application_uuid)
|
||||||
application_id = session(session_id)['application_id']
|
if _session is None:
|
||||||
user_id = session(session_id)['user_id']
|
return Response(json.dumps({'error': 'unauthorized'}), status=403)
|
||||||
payload = request.get_json()
|
application_id = session(session_id)['application_id']
|
||||||
results = self.export_db_factory.results(user_id, application_id, payload)
|
user_id = session(session_id)['user_id']
|
||||||
if results == {}:
|
token = {'token': _session['token']}
|
||||||
# no data found for the given parameters
|
payload = request.get_json()
|
||||||
return Response(json.dumps({'result': 'succeed', 'results': results}), status=200)
|
results = self.export_db_factory.results(user_id, application_id, payload)
|
||||||
# deserialize the response to return pure json
|
if results == {}:
|
||||||
city_name = next(iter(results))
|
# no data found for the given parameters
|
||||||
for building_results in results[city_name]:
|
return Response(json.dumps({'result': 'succeed', 'results': results}), status=200, headers=token)
|
||||||
values = []
|
# deserialize the response to return pure json
|
||||||
for value in building_results['insel meb']:
|
city_name = next(iter(results))
|
||||||
key = next(iter(value))
|
for building_results in results[city_name]:
|
||||||
values.append({key: json.loads(value[key])})
|
values = []
|
||||||
building_results['insel meb'] = values
|
for value in building_results['insel meb']:
|
||||||
return Response(json.dumps({'result': 'succeed', 'results': results}), status=200)
|
key = next(iter(value))
|
||||||
return Response(json.dumps({'error': 'unauthorized'}), status=403)
|
values.append({key: json.loads(value[key])})
|
||||||
|
building_results['insel meb'] = values
|
||||||
|
return Response(json.dumps({'result': 'succeed', 'results': results}), status=200, headers=token)
|
||||||
|
@ -75,11 +75,11 @@ class KeepSessionAlive(Resource):
|
|||||||
session_id = request.headers.get('session_id', None)
|
session_id = request.headers.get('session_id', None)
|
||||||
token = request.headers.get('token', None)
|
token = request.headers.get('token', None)
|
||||||
application_uuid = request.headers.get('application_uuid', None)
|
application_uuid = request.headers.get('application_uuid', None)
|
||||||
session = refresh_session(session_id, token, application_uuid)
|
_session = refresh_session(session_id, token, application_uuid)
|
||||||
|
|
||||||
if session is None:
|
if _session is None:
|
||||||
return Response(json.dumps({'error': 'unauthorized'}), status=403)
|
return Response(json.dumps({'error': 'unauthorized'}), status=403)
|
||||||
|
|
||||||
response = Response(json.dumps({'result': 'succeed'}), status=200)
|
response = Response(json.dumps({'result': 'succeed'}), status=200)
|
||||||
response.headers['token'] = session['token']
|
response.headers['token'] = _session['token']
|
||||||
return response
|
return response
|
||||||
|
26456
hub_api/data/cities15000.txt
Normal file
26456
hub_api/data/cities15000.txt
Normal file
File diff suppressed because it is too large
Load Diff
@ -38,6 +38,7 @@ paths:
|
|||||||
name: password
|
name: password
|
||||||
schema:
|
schema:
|
||||||
type: string
|
type: string
|
||||||
|
format: password
|
||||||
required: true
|
required: true
|
||||||
description: the password for the user accessing this API
|
description: the password for the user accessing this API
|
||||||
- in: header
|
- in: header
|
||||||
@ -180,6 +181,43 @@ paths:
|
|||||||
application/json:
|
application/json:
|
||||||
schema:
|
schema:
|
||||||
$ref: '#/components/schemas/unauthorized'
|
$ref: '#/components/schemas/unauthorized'
|
||||||
|
/v1.4/geolocation/reverse/{latitude}/{longitude}:
|
||||||
|
get:
|
||||||
|
parameters:
|
||||||
|
- in: path
|
||||||
|
name: latitude
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
required: true
|
||||||
|
- in: path
|
||||||
|
name: longitude
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
required: true
|
||||||
|
tags:
|
||||||
|
- Reverse geolocation information
|
||||||
|
summary: Retrieve the geolocation information from the given latitude and longitude
|
||||||
|
operationId: reverse
|
||||||
|
description: Retrieve the geolocation information from the given latitude and longitude and renew the token
|
||||||
|
responses:
|
||||||
|
'200':
|
||||||
|
description: Succeed
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: '#/components/schemas/reverse'
|
||||||
|
headers:
|
||||||
|
token:
|
||||||
|
type: string
|
||||||
|
format: uuid
|
||||||
|
description: Token expected in next operation header
|
||||||
|
example: '77e1c83b-7bb0-437b-bc50-a7a58e5660ac'
|
||||||
|
'403':
|
||||||
|
description: Unauthorized
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: '#/components/schemas/unauthorized'
|
||||||
components:
|
components:
|
||||||
securitySchemes:
|
securitySchemes:
|
||||||
session_id:
|
session_id:
|
||||||
@ -202,6 +240,18 @@ components:
|
|||||||
type: string
|
type: string
|
||||||
format: hh:mm:ss.ms
|
format: hh:mm:ss.ms
|
||||||
example: '00:09:53.600281'
|
example: '00:09:53.600281'
|
||||||
|
reverse:
|
||||||
|
type: object
|
||||||
|
properties:
|
||||||
|
country:
|
||||||
|
type: string
|
||||||
|
example: 'CA'
|
||||||
|
city:
|
||||||
|
type: string
|
||||||
|
example: 'Montreal'
|
||||||
|
climate_zone:
|
||||||
|
type: string
|
||||||
|
example: '6'
|
||||||
unauthorized:
|
unauthorized:
|
||||||
type: object
|
type: object
|
||||||
properties:
|
properties:
|
||||||
|
35
hub_api/geolocation/reverse.py
Normal file
35
hub_api/geolocation/reverse.py
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
import json
|
||||||
|
import math
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from flask import Response
|
||||||
|
from flask.views import MethodView
|
||||||
|
|
||||||
|
from hub_api.config import Config
|
||||||
|
|
||||||
|
|
||||||
|
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):
|
||||||
|
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)
|
||||||
|
|
@ -22,7 +22,7 @@ def expired_sessions_collector(session_timeout_duration):
|
|||||||
"""
|
"""
|
||||||
while True:
|
while True:
|
||||||
if bool(sessions):
|
if bool(sessions):
|
||||||
for session in list(sessions):
|
for _session in list(sessions):
|
||||||
_expire = datetime.datetime.strptime(sessions[session]['expire'], '%Y-%m-%d %H:%M:%S.%f')
|
_expire = datetime.datetime.strptime(sessions[session]['expire'], '%Y-%m-%d %H:%M:%S.%f')
|
||||||
if _expire < datetime.datetime.now():
|
if _expire < datetime.datetime.now():
|
||||||
print("session with session_id: ", session, "expired.")
|
print("session with session_id: ", session, "expired.")
|
||||||
@ -35,10 +35,10 @@ def _validate_session(session_id, token, application_uuid):
|
|||||||
Checks if session is valid
|
Checks if session is valid
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
session = sessions[session_id]
|
_session = session(session_id)
|
||||||
if debug_mode:
|
if debug_mode:
|
||||||
token = session['token']
|
token = _session['token']
|
||||||
return bool(session) and (session['token'] == token) and session['application_uuid'] == application_uuid
|
return bool(_session) and (_session['token'] == token) and _session['application_uuid'] == application_uuid
|
||||||
except KeyError:
|
except KeyError:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
@ -61,8 +61,7 @@ def refresh_session(session_id, token, application_uuid):
|
|||||||
if _validate_session(session_id, token, application_uuid):
|
if _validate_session(session_id, token, application_uuid):
|
||||||
sessions[session_id]['expire'] = str(datetime.datetime.now() + datetime.timedelta(minutes=5))
|
sessions[session_id]['expire'] = str(datetime.datetime.now() + datetime.timedelta(minutes=5))
|
||||||
sessions[session_id]['token'] = str(uuid.uuid4())
|
sessions[session_id]['token'] = str(uuid.uuid4())
|
||||||
return sessions[session_id]
|
return session(session_id)
|
||||||
|
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user