Skip to content

Commit

Permalink
Merge pull request #18 from neutrons/update_tests
Browse files Browse the repository at this point in the history
Update tests and remove unused code
  • Loading branch information
rosswhitfield authored Jun 25, 2024
2 parents b329f66 + 590c5a3 commit c35a9ca
Show file tree
Hide file tree
Showing 6 changed files with 248 additions and 234 deletions.
32 changes: 5 additions & 27 deletions src/live_data_server/plots/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ class Instrument(models.Model):
name = models.CharField(max_length=128, unique=True)
run_id_type = models.IntegerField(default=0)

def __unicode__(self):
def __str__(self):
return self.name


Expand All @@ -35,8 +35,8 @@ class DataRun(models.Model):
instrument = models.ForeignKey(Instrument, on_delete=models.deletion.CASCADE)
created_on = models.DateTimeField("Timestamp", auto_now_add=True)

def __unicode__(self):
return "%s_%d_%s" % (self.instrument, self.run_number, self.run_id)
def __str__(self):
return f"{self.instrument}_{self.run_number}_{self.run_id}"


class PlotData(models.Model):
Expand All @@ -56,14 +56,8 @@ class PlotData(models.Model):

timestamp = models.DateTimeField("Timestamp")

def __unicode__(self):
return "%s" % self.data_run

def is_div(self):
"""
Return whether the data is a <div>
"""
return self.data_type % 100 == 1
def __str__(self):
return str(self.data_run)

def is_data_type_valid(self, data_type):
"""
Expand Down Expand Up @@ -93,19 +87,3 @@ def get_data_type_from_string(cls, type_string):
Returns the correct data type ID for a given string representation
"""
return DATA_TYPES.get(type_string, DATA_TYPES["json"])

@classmethod
def data_type_as_string(cls, data_type):
"""
Return an internal name to use for a given data_type.
This name is generally used in function names and relates
to the data format (json or html). In principle, different
data types can return the same string.
@param data_type: data type ID [integer]
"""
data_type = int(data_type)
data_type_info = DATA_TYPE_INFO.get(data_type)
if data_type_info is not None:
return data_type_info["name"]
return None
1 change: 0 additions & 1 deletion src/live_data_server/plots/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
app_name = "plots"

urlpatterns = [
re_path(r"^(?P<instrument>[\w]+)/(?P<run_id>\d+)/$", views.live_plot, name="live_plot"),
re_path(r"^(?P<instrument>[\w]+)/(?P<run_id>\d+)/update/json/$", views.update_as_json, name="update_as_json"),
re_path(r"^(?P<instrument>[\w]+)/(?P<run_id>\d+)/update/html/$", views.update_as_html, name="update_as_html"),
re_path(
Expand Down
80 changes: 23 additions & 57 deletions src/live_data_server/plots/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,8 @@

from django.conf import settings
from django.contrib.auth import authenticate, login
from django.core.exceptions import PermissionDenied
from django.http import HttpResponse, HttpResponseNotFound, JsonResponse
from django.shortcuts import get_object_or_404, render_to_response
from django.urls import reverse
from django.shortcuts import get_object_or_404
from django.utils import dateformat, timezone
from django.views.decorators.cache import cache_page
from django.views.decorators.csrf import csrf_exempt
Expand All @@ -21,15 +19,6 @@
from . import view_util


def _check_credentials(request):
"""
Internal utility method to check whether a user has access to a view
"""
# If we don't allow guests but the user is authenticated, return the function
if request.user.is_authenticated:
return True


def check_credentials(fn):
"""
Function decorator to authenticate a request
Expand All @@ -48,33 +37,14 @@ def request_processor(request, *args, **kws):
if request_user is not None and not request_user.is_anonymous:
login(request, request_user)
return fn(request, *args, **kws)
else:
return HttpResponse(status=401)
else:
raise PermissionDenied
return HttpResponse(status=401)

return request_processor


def live_plot(request, instrument, run_id):
"""
Test view for live plotting.
@param instrument: instrument name
@param run_id: run number
"""
data_type_default = PlotData.get_data_type_from_string("html")
data_type = request.GET.get("data_type", default=data_type_default)
update_url = reverse(
"plots:update_as_%s" % PlotData.data_type_as_string(data_type),
kwargs={"instrument": instrument, "run_id": run_id},
)
client_key = view_util.generate_key(instrument, run_id)
if client_key is not None:
update_url += "?key=%s" % client_key
template_values = {}
template_values["data_type"] = data_type
template_values["update_url"] = update_url
return render_to_response("plots/live_plot.html", template_values)


@view_util.check_key
@cache_page(15)
def update_as_json(request, instrument, run_id): # noqa: ARG001
Expand All @@ -87,7 +57,7 @@ def update_as_json(request, instrument, run_id): # noqa: ARG001
plot_data = view_util.get_plot_data(instrument, run_id, data_type=data_type)

if plot_data is None:
error_msg = "No data available for %s %s" % (instrument, run_id)
error_msg = f"No data available for {instrument} {run_id}"
logging.error(error_msg)
return HttpResponseNotFound(error_msg)

Expand All @@ -107,7 +77,7 @@ def update_as_html(request, instrument, run_id): # noqa: ARG001
plot_data = view_util.get_plot_data(instrument, run_id, data_type=data_type)

if plot_data is None:
error_msg = "No data available for %s %s" % (instrument, run_id)
error_msg = f"No data available for {instrument} {run_id}"
logging.error(error_msg)
return HttpResponseNotFound(error_msg)

Expand All @@ -124,7 +94,7 @@ def _store(request, instrument, run_id=None, as_user=False):
@param run_id: run number
@param as_user: if True, we will store as user data
"""
if request.user.is_authenticated and "file" in request.FILES:
if "file" in request.FILES:
raw_data = request.FILES["file"].read().decode("utf-8")
data_type_default = PlotData.get_data_type_from_data(raw_data)
data_type = request.POST.get("data_type", default=data_type_default)
Expand All @@ -134,7 +104,7 @@ def _store(request, instrument, run_id=None, as_user=False):
else:
view_util.store_plot_data(instrument, run_id, raw_data, data_type)
else:
raise PermissionDenied
return HttpResponse(status=400)

return HttpResponse()

Expand All @@ -160,26 +130,22 @@ def upload_user_data(request, user):

@csrf_exempt
@check_credentials
def get_data_list(request, instrument):
def get_data_list(_, instrument):
"""
Get a list of user data
"""
if request.user.is_authenticated:
instrument_object = get_object_or_404(Instrument, name=instrument.lower())
data_list = []
for item in DataRun.objects.filter(instrument=instrument_object):
localtime = timezone.localtime(item.created_on)
df = dateformat.DateFormat(localtime)
data_list.append(
dict(
id=item.id,
run_number=str(item.run_number),
run_id=item.run_id,
timestamp=item.created_on.isoformat(),
created_on=df.format(settings.DATETIME_FORMAT),
)
instrument_object = get_object_or_404(Instrument, name=instrument.lower())
data_list = []
for item in DataRun.objects.filter(instrument=instrument_object):
localtime = timezone.localtime(item.created_on)
df = dateformat.DateFormat(localtime)
data_list.append(
dict(
id=item.id,
run_number=str(item.run_number),
run_id=item.run_id,
timestamp=item.created_on.isoformat(),
created_on=df.format(settings.DATETIME_FORMAT),
)
response = HttpResponse(json.dumps(data_list), content_type="application/json")
return response
else:
raise PermissionDenied
)
return JsonResponse(data_list, safe=False)
26 changes: 0 additions & 26 deletions src/live_data_server/templates/base.html

This file was deleted.

43 changes: 0 additions & 43 deletions src/live_data_server/templates/plots/live_plot.html

This file was deleted.

Loading

0 comments on commit c35a9ca

Please sign in to comment.