add logic to update the device last_contact_ts whenever it makes and API call.

pull/181/head
Chris Veilleux 2019-06-10 16:19:26 -05:00
parent 36a90171f0
commit e1ff87bf2b
3 changed files with 31 additions and 0 deletions

View File

@ -5,6 +5,7 @@ from http import HTTPStatus
from flask import current_app, Blueprint, g as global_context
from schematics.exceptions import DataError
from selene.data.device import DeviceRepository
from selene.data.metrics import ApiMetric, ApiMetricsRepository
from selene.util.auth import AuthenticationError
from selene.util.db import connect_to_db
@ -36,11 +37,13 @@ def setup_request():
@selene_api.after_app_request
def teardown_request(response):
add_api_metric(response.status_code)
update_device_last_contact()
return response
def add_api_metric(http_status):
"""Add a row to the table tracking metrics for API calls"""
api = None
# We are not logging metrics for the public API until after the socket
# implementation to avoid putting millions of rows a day on the table
@ -74,3 +77,18 @@ def add_api_metric(http_status):
)
metric_repository = ApiMetricsRepository(global_context.db)
metric_repository.add(api_metric)
def update_device_last_contact():
"""Update the timestamp on the device table indicating last contact.
This should only be done on public API calls because we are tracking
device activity only.
"""
if 'public' in current_app.name and 'device_id' in global_context:
if 'db' not in global_context:
global_context.db = connect_to_db(
current_app.config['DB_CONNECTION_CONFIG']
)
device_repository = DeviceRepository(global_context.db)
device_repository.update_last_contact_ts(global_context.device_id)

View File

@ -170,3 +170,10 @@ class DeviceRepository(RepositoryBase):
)
self.cursor.update(db_request)
def update_last_contact_ts(self, device_id):
db_request = self._build_db_request(
sql_file_name='update_last_contact_ts.sql',
args=dict(device_id=device_id)
)
self.cursor.update(db_request)

View File

@ -0,0 +1,6 @@
UPDATE
device.device
SET
last_contact_ts = now()
WHERE
id = %(device_id)s