Commit 95a2b05d authored by Samuel GAIST's avatar Samuel GAIST Committed by Flavio TARSETTI

[reports][all] Pre-commit cleanup

parent e893f0c4
Pipeline #42746 passed with stage
in 15 minutes and 33 seconds
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
#!/usr/bin/env python
# encoding: utf-8
###############################################################################
......@@ -30,86 +28,92 @@
# Flavio Tarsetti <flavio.tarsetti@idiap.ch>
# Wed May 20 15:46:11 CEST 2015
from django.contrib import admin
import simplejson as json
from django import forms
from django.contrib import admin
from ..common.texts import Messages
from ..ui.forms import CodeMirrorJSONCharField
from ..ui.forms import CodeMirrorRSTCharField
from .models import Report
from ..ui.forms import CodeMirrorRSTCharField, CodeMirrorJSONCharField
from ..ui.forms import NameField
import simplejson as json
class ReportModelForm(forms.ModelForm):
description = CodeMirrorRSTCharField(
label='Description',
required=False,
help_text=Messages['description'],
label="Description", required=False, help_text=Messages["description"],
)
content = CodeMirrorJSONCharField(
label='Content',
help_text=Messages['json'],
)
content = CodeMirrorJSONCharField(label="Content", help_text=Messages["json"],)
def clean_content(self):
"""Cleans-up the content data, make sure it is really new"""
try:
data = json.loads(self.cleaned_data['content'])
data = json.loads(self.cleaned_data["content"])
return json.dumps(data, indent=4)
except Exception as e:
raise forms.ValidationError(str(e))
class ReportAdmin(admin.ModelAdmin):
form = ReportModelForm
readonly_fields = ('referenced_plotters', 'referenced_plotterparameters')
readonly_fields = ("referenced_plotters", "referenced_plotterparameters")
filter_horizontal = [
'experiments',
'referenced_plotters',
'referenced_plotterparameters'
"experiments",
"referenced_plotters",
"referenced_plotterparameters",
]
fieldsets = (
(None,
dict(
fields=('status', 'name', 'number', 'author',),
),
),
('Dates',
dict(
classes=('collapse',),
fields=('creation_date', 'expiration_date', 'publication_date',),
),
),
('Documentation',
dict(
classes=('collapse',),
fields=('short_description', 'description',),
),
),
(None,
dict(
fields=('analyzer', 'experiments', 'referenced_plotters', 'referenced_plotterparameters', 'content',),
),
),
(None, dict(fields=("status", "name", "number", "author",),),),
(
"Dates",
dict(
classes=("collapse",),
fields=("creation_date", "expiration_date", "publication_date",),
),
),
(
"Documentation",
dict(classes=("collapse",), fields=("short_description", "description",),),
),
(
None,
dict(
fields=(
"analyzer",
"experiments",
"referenced_plotters",
"referenced_plotterparameters",
"content",
),
),
),
)
list_display = ('id', 'name', 'number', 'author', 'creation_date', 'expiration_date', 'publication_date')
search_fields = [
'author__username',
'name',
'short_description',
'description',
'number',
list_display = (
"id",
"name",
"number",
"author",
"creation_date",
"expiration_date",
"publication_date",
)
search_fields = [
"author__username",
"name",
"short_description",
"description",
"number",
]
list_display_links = ('id', 'name')
list_display_links = ("id", "name")
list_filter = ("author", "name")
list_filter = ('author', 'name')
admin.site.register(Report, ReportAdmin)
......@@ -26,44 +26,38 @@
###############################################################################
import json
from datetime import datetime, timedelta
from datetime import datetime
from datetime import timedelta
from django.conf import settings
from django.contrib.auth.models import User
from django.shortcuts import get_object_or_404
from django.db.models import Q
from django.shortcuts import get_object_or_404
from django.urls import reverse
from rest_framework import generics
from rest_framework import views
from rest_framework import permissions
from rest_framework.response import Response
from rest_framework import status
from rest_framework import views
from rest_framework.response import Response
from ..common.models import Shareable
from ..common.exceptions import ShareError
from ..common.mixins import CommonContextMixin
from ..common.responses import BadRequestResponse, ForbiddenResponse
from ..common.models import Shareable
from ..common.responses import BadRequestResponse
from ..common.responses import ForbiddenResponse
from ..common.utils import ensure_html
from ..experiments.serializers import ExperimentResultsSerializer
from .serializers import SimpleReportSerializer
from .models import Report
from .permissions import IsAccessibleOutside
from .permissions import IsAuthor
from .permissions import IsAuthorOrPublished
from .permissions import IsEditable
from .permissions import IsLocked
from .serializers import FullReportSerializer
from .serializers import ReportCreationFailedException
from .serializers import ReportCreationSerializer
from .serializers import ReportUpdateSerializer
from .serializers import ReportCreationFailedException
from .models import Report
from .permissions import (
IsAuthor,
IsAuthorOrPublished,
IsAccessibleOutside,
IsEditable,
IsLocked,
)
from .serializers import SimpleReportSerializer
# ----------------------------------------------------------
......
This diff is collapsed.
......@@ -29,8 +29,7 @@ from rest_framework import permissions
from .models import Report
#----------------------------------------------------------
# ----------------------------------------------------------
class IsAuthor(permissions.BasePermission):
......@@ -42,7 +41,7 @@ class IsAuthor(permissions.BasePermission):
return obj.author == request.user
#----------------------------------------------------------
# ----------------------------------------------------------
class IsEditable(permissions.BasePermission):
......@@ -50,13 +49,14 @@ class IsEditable(permissions.BasePermission):
Object level permission that returns true if the
given object has the Report.EDITABLE status
"""
message = 'This report is read-only'
message = "This report is read-only"
def has_object_permission(self, request, view, obj):
return obj.status == Report.EDITABLE
#----------------------------------------------------------
# ----------------------------------------------------------
class IsLocked(permissions.BasePermission):
......@@ -64,13 +64,14 @@ class IsLocked(permissions.BasePermission):
Object level permission that returns true if the
given object status is not Report.EDITABLE
"""
message = 'This report is not locked'
message = "This report is not locked"
def has_object_permission(self, request, view, obj):
return obj.status == Report.LOCKED
#----------------------------------------------------------
# ----------------------------------------------------------
class IsPublished(permissions.BasePermission):
......@@ -78,13 +79,14 @@ class IsPublished(permissions.BasePermission):
Object level permission that returns true if the
given object status is Report.PUBLISHED
"""
message = 'This report is not published'
message = "This report is not published"
def has_object_permission(self, request, view, obj):
return obj.status == Report.PUBLISHED
#----------------------------------------------------------
# ----------------------------------------------------------
class IsAuthorOrPublished(permissions.BasePermission):
......@@ -94,13 +96,13 @@ class IsAuthorOrPublished(permissions.BasePermission):
"""
def has_object_permission(self, request, view, obj):
if (obj.author== request.user) or (obj.status == Report.PUBLISHED):
if (obj.author == request.user) or (obj.status == Report.PUBLISHED):
return True
return False
#----------------------------------------------------------
# ----------------------------------------------------------
class IsAuthorOrAccessible(permissions.BasePermission):
......@@ -110,12 +112,13 @@ class IsAuthorOrAccessible(permissions.BasePermission):
"""
def has_object_permission(self, request, view, obj):
if (obj.author== request.user) or (obj.status != Report.EDITABLE):
if (obj.author == request.user) or (obj.status != Report.EDITABLE):
return True
return False
#----------------------------------------------------------
# ----------------------------------------------------------
class IsAccessibleOutside(permissions.BasePermission):
......
......@@ -27,6 +27,7 @@
from ..common.responses import ForbiddenResponse
class ReadOnlyResponse(ForbiddenResponse):
def __init__(self):
super(ReadOnlyResponse, self).__init__({'error': 'This report is read-only'})
super(ReadOnlyResponse, self).__init__({"error": "This report is read-only"})
......@@ -26,16 +26,14 @@
###############################################################################
import simplejson as json
from rest_framework import serializers
from .models import Report
from ..common import fields as beat_fields
from ..common.models import Contribution
from ..common.utils import validate_restructuredtext
from ..common import fields as beat_fields
from ..ui.templatetags.markup import restructuredtext
import simplejson as json
from .models import Report
# ----------------------------------------------------------
......
......@@ -25,36 +25,30 @@
# #
###############################################################################
import os
import shutil
from datetime import datetime
import simplejson as json
from django.conf import settings
from django.contrib.auth.models import User
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from django.contrib.auth.models import User
from django.conf import settings
import simplejson as json
from .models import Report
from ..algorithms.models import Algorithm
from ..attestations.models import Attestation
from ..backend.models import Environment
from ..backend.models import Queue
from ..common.testutils import tearDownModule # noqa test runner will call it
from ..dataformats.models import DataFormat
from ..databases.models import Database
from ..algorithms.models import Algorithm
from ..toolchains.models import Toolchain
from ..experiments.models import Experiment
from ..dataformats.models import DataFormat
from ..experiments.models import Block
from ..attestations.models import Attestation
from ..experiments.models import Experiment
from ..plotters.models import Plotter
from ..plotters.models import PlotterParameter
from ..backend.models import Environment
from ..backend.models import Queue
from datetime import datetime
import os
import shutil
from ..toolchains.models import Toolchain
from .models import Report
# ----------------------------------------------------------
......@@ -1449,7 +1443,7 @@ class EditableReportLockingTestCase(ReportTestCase):
)
def test_logged_in_user_non_empty_report_accessible_attestation_not_public_experiment(
self
self,
):
self.client.login(username=self.johndoe.username, password=self.password)
......@@ -1481,7 +1475,7 @@ class EditableReportLockingTestCase(ReportTestCase):
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
def test_logged_in_user_non_empty_report_accessible_attestation_public_experiment(
self
self,
):
self.client.login(username=self.johndoe.username, password=self.password)
......
......@@ -25,21 +25,18 @@
# #
###############################################################################
from django.shortcuts import render, redirect
from django.shortcuts import get_object_or_404
from django.conf import settings
from django.views.generic import TemplateView
from django.contrib.auth.models import User
from django.db.models import Q
from django.db.models.functions import Coalesce
from django.http import Http404
from ..ui.templatetags.markup import restructuredtext
from django.shortcuts import get_object_or_404
from django.shortcuts import redirect
from django.shortcuts import render
from django.views.generic import TemplateView
from .models import Report
import simplejson as json
# Permissions for viewing a report is complicated:
# - 'E' indicates permissions to view the editable version of the report (usually accessed by author and report name)
# - 'V' indicates permissions to view the view-only version of the report (usually accessed by report number)
......@@ -51,15 +48,16 @@ import simplejson as json
# | Anonymous | | V | V |
# | Public (Published) Reports List Reader | | | V |
def show_actionbar(request, report):
correct_status = report.status == 'E' or report.status == 'L'
correct_status = report.status == "E" or report.status == "L"
correct_user = request.user == report.author
is_admin = request.user.is_staff
return (correct_status and correct_user) or is_admin
#------------------------------------------------
# ------------------------------------------------
def by_number(request, number):
......@@ -68,114 +66,116 @@ def by_number(request, number):
isAnon = request.user.is_anonymous
if obj.status == 'E' and isAnon:
if obj.status == "E" and isAnon:
# return 404
raise Http404('No %s matches the given query.' % Report._meta.object_name)
raise Http404("No %s matches the given query." % Report._meta.object_name)
return render(request,
'reports/report.html',
{
'report_number' : number,
'owner': False,
'report': obj,
'USE_HTTPS_GRAVATAR': settings.USE_HTTPS_GRAVATAR,
'show_actionbar': show_actionbar(request, obj)
})
return render(
request,
"reports/report.html",
{
"report_number": number,
"owner": False,
"report": obj,
"USE_HTTPS_GRAVATAR": settings.USE_HTTPS_GRAVATAR,
"show_actionbar": show_actionbar(request, obj),
},
)
#------------------------------------------------
# ------------------------------------------------
def for_author(request, author_name, report_name):
# get the query from the DB
obj = get_object_or_404(Report,
author__username = author_name,
name = report_name)
obj = get_object_or_404(Report, author__username=author_name, name=report_name)
isAuthor = request.user.username == obj.author.username
isEditable = obj.status == 'E'
isPublished = obj.status == 'P'
isLocked = obj.status == 'L'
isEditable = obj.status == "E"
isPublished = obj.status == "P"
isLocked = obj.status == "L"
# if its the author and its locked, redirect to numbered url
# same if its published
if isPublished or (isAuthor and isLocked):
return redirect(obj)
# only valid when the author is accessing it and its editable
if isEditable and isAuthor:
return render(request,
'reports/report.html',
{
'author' : author_name,
'report_name' : report_name,
'owner' : (request.user == obj.author),
'report' : obj,
'USE_HTTPS_GRAVATAR': settings.USE_HTTPS_GRAVATAR,
'show_actionbar': show_actionbar(request, obj)
})
return render(
request,
"reports/report.html",
{
"author": author_name,
"report_name": report_name,
"owner": (request.user == obj.author),
"report": obj,
"USE_HTTPS_GRAVATAR": settings.USE_HTTPS_GRAVATAR,
"show_actionbar": show_actionbar(request, obj),
},
)
# return 404
raise Http404('No %s matches the given query.' % Report._meta.object_name)
raise Http404("No %s matches the given query." % Report._meta.object_name)
#------------------------------------------------
# ------------------------------------------------
def ls(request, author_name):
'''List all accessible reports to the request user'''
"""List all accessible reports to the request user"""
if not author_name: return public_ls(request)
if not author_name:
return public_ls(request)
# check that the user exists on the system
author = get_object_or_404(User, username=author_name)
owner = (request.user==author)
owner = request.user == author
if owner:
# user wants to retrieve all available objects, including his
objects = Report.objects.filter(Q(status=Report.PUBLISHED)|Q(author=author))
objects = Report.objects.filter(Q(status=Report.PUBLISHED) | Q(author=author))
else:
# user wants to retrieve objects belonging to another user
objects = Report.objects.filter(author=author, status=Report.PUBLISHED)
objects = objects.annotate(updated=Coalesce('publication_date', 'creation_date',)).order_by('-updated')
objects = objects.annotate(
updated=Coalesce("publication_date", "creation_date",)
).order_by("-updated")
return render(request,
'reports/list.html',
dict(
objects=objects,
author=author,
owner=owner,
))
return render(
request, "reports/list.html", dict(objects=objects, author=author, owner=owner,)
)
#------------------------------------------------
# ------------------------------------------------
def public_ls(request):
'''List all publicly accessible reports'''
"""List all publicly accessible reports"""
objects = Report.objects.filter(status=Report.PUBLISHED).order_by('publication_date')
objects = Report.objects.filter(status=Report.PUBLISHED).order_by(
"publication_date"
)
objects = objects.annotate(updated=Coalesce('publication_date', 'creation_date',)).order_by('-updated')
objects = objects.annotate(
updated=Coalesce("publication_date", "creation_date",)
).order_by("-updated")
return render(request,
'reports/list.html',
dict(
objects=objects,
author=request.user,
owner=False,
))
return render(
request,
"reports/list.html",
dict(objects=objects, author=request.user, owner=False,),
)
#------------------------------------------------
# ------------------------------------------------
class PartialGroupView(TemplateView):
def get_template_names(self):
if 'template_name' in self.kwargs:
self.template_name = 'reports/partials/' + self.kwargs.get('template_name')
if "template_name" in self.kwargs:
self.template_name = "reports/partials/" + self.kwargs.get("template_name")
return super(PartialGroupView, self).get_template_names()
def get_context_data(self, **kwargs):
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment