Beispiel #1
0
    def test_objectgetter(self):
        request = HttpRequest()
        book = Book.objects.get(pk=1)

        self.assertEqual(book, objectgetter(Book)(request, pk=1))
        self.assertEqual(book, objectgetter(Book, attr_name='id')(request, id=1))
        self.assertEqual(book, objectgetter(Book, field_name='id')(request, pk=1))

        with self.assertRaises(ImproperlyConfigured):
            # Raise if no `pk` argument is provided to the view
            self.assertEqual(book, objectgetter(Book)(request, foo=1))

        with self.assertRaises(ImproperlyConfigured):
            # Raise if given invalid model lookup field
            self.assertEqual(book, objectgetter(Book, field_name='foo')(request, pk=1))

        with self.assertRaises(Http404):
            # Raise 404 if no model instance found
            self.assertEqual(book, objectgetter(Book)(request, pk=100000))
Beispiel #2
0
    def test_objectgetter(self):
        request = HttpRequest()
        book = Book.objects.get(pk=1)

        self.assertEqual(book, objectgetter(Book)(request, pk=1))
        self.assertEqual(book, objectgetter(Book, attr_name='id')(request, id=1))
        self.assertEqual(book, objectgetter(Book, field_name='id')(request, pk=1))

        with self.assertRaises(ImproperlyConfigured):
            # Raise if no `pk` argument is provided to the view
            self.assertEqual(book, objectgetter(Book)(request, foo=1))

        with self.assertRaises(ImproperlyConfigured):
            # Raise if given invalid model lookup field
            self.assertEqual(book, objectgetter(Book, field_name='foo')(request, pk=1))

        with self.assertRaises(Http404):
            # Raise 404 if no model instance found
            self.assertEqual(book, objectgetter(Book)(request, pk=100000))
Beispiel #3
0
from crispy_forms.utils import render_crispy_form
from django.contrib.auth.decorators import login_required
from django.core.exceptions import PermissionDenied
from django.http import JsonResponse
from django.shortcuts import get_object_or_404
from django.template.context_processors import csrf
from django.template.loader import render_to_string
from rules.contrib.views import permission_required, objectgetter

from booking.forms import BookingForm
from booking.models import Booking


@permission_required("booking.change_booking",
                     fn=objectgetter(Booking, "booking_id"))
def delete_booking(request, booking_id):
    booking = get_object_or_404(Booking, pk=booking_id)
    booking.delete()
    return JsonResponse({
        "success": True,
    })


@login_required
def edit_booking(request, booking_id=None):
    """
    View for adding a new booking to the database.

    :param booking_id:
    :param request:
    :return:
Beispiel #4
0
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, render
from rules.contrib.views import permission_required, objectgetter
from main.models import Competition, Entry


@login_required
@permission_required('main.manage_competition',
                     fn=objectgetter(Competition,
                                     attr_name='comp_id',
                                     field_name='pk'),
                     raise_exception=True)
def check_in(request, org_slug, comp_id):
    competition = get_object_or_404(Competition, pk=comp_id)
    entries = competition.entry_set.order_by('competitor__name').all()
    return render(request, 'ui/competition/check_in.html', {
        'competition': competition,
        'entries': entries
    })
Beispiel #5
0
            job = queue.fetch_job('tf_annotation.create/{}'.format(tid))
            if job is not None:
                result[tid] = {
                    "active": job.is_queued or job.is_started,
                    "success": not job.is_failed
                }

        return JsonResponse(result)
    except Exception as ex:
        slogger.glob.exception('exception was occured during tf meta request', exc_info=True)
        return HttpResponseBadRequest(str(ex))


@login_required
@permission_required(perm=['engine.task.change'],
    fn=objectgetter(TaskModel, 'tid'), raise_exception=True)
def create(request, tid):
    slogger.glob.info('tf annotation create request for task {}'.format(tid))
    try:
        db_task = TaskModel.objects.get(pk=tid)
        queue = django_rq.get_queue('low')
        job = queue.fetch_job('tf_annotation.create/{}'.format(tid))
        if job is not None and (job.is_started or job.is_queued):
            raise Exception("The process is already running")

        db_labels = db_task.label_set.prefetch_related('attributespec_set').all()
        db_labels = {db_label.id:db_label.name for db_label in db_labels}

        tf_annotation_labels = {
            "person": 1, "bicycle": 2, "car": 3, "motorcycle": 4, "airplane": 5,
            "bus": 6, "train": 7, "truck": 8, "boat": 9, "traffic_light": 10,
Beispiel #6
0
        )
        return render(
            request, "formation_detail.html",
            {
                'formation': formation,
                'can_edit_formation': can_edit_formation,
            }
        )
    else:
        raise Http404()


@login_required
@permission_required(
    'continuing_education.change_continuingeducationtraining',
    fn=objectgetter(ContinuingEducationTraining, 'formation_id'),
    raise_exception=True
)
def formation_edit(request, formation_id):
    formation = get_object_or_404(
        ContinuingEducationTraining.objects.select_related('postal_address', 'education_group'),
        pk=formation_id
    )
    form = ContinuingEducationTrainingForm(request.POST or None, user=request.user, instance=formation)
    address_form = AddressForm(request.POST or None, instance=formation.postal_address)
    if all([form.is_valid(), address_form.is_valid()]):
        address = address_form.save()
        formation = form.save(commit=False)
        formation.postal_address = address
        formation.save()
        return redirect(reverse('formation_detail', kwargs={'formation_id': formation.education_group.id}))
Beispiel #7
0
    for view in settings.VIEWS_DISABLED:
        if view in view_column_names.values():
            global_views_disabled.append((list(view_column_names.keys()))[list(
                view_column_names.values()).index(view)])
    admin_course_views = CourseViewOption.objects.get(course=course).json(
        include_id=False)
    course_view_options = {
        key: value
        for key, value in admin_course_views.items()
        if key not in global_views_disabled
    }
    return admin_course_views if is_admin else course_view_options


@permission_required('dashboard.get_course_info',
                     fn=objectgetter(Course, 'course_id', 'canvas_id'),
                     raise_exception=True)
def get_course_info(request, course_id=0):
    """Returns JSON data about a course

    :param request: HTTP Request
    :type request: Request
    :param course_id: Unizin Course ID, defaults to 0
    :param course_id: int, optional
    :return: JSON to be used
    :rtype: str
    """
    course_id = canvas_id_to_incremented_id(course_id)
    today = timezone.now()

    try:
Beispiel #8
0
                    "status": rq_job.get_status(),
                    "stderr": rq_job.exc_info
                })
        else:
            return JsonResponse({"status": "unknown"})
    except Exception as ex:
        slogger.glob.error(
            "error occured during checking repository request with rq id {}".
            format(rq_id),
            exc_info=True)
        return HttpResponseBadRequest(str(ex))


@login_required
@permission_required(perm=['engine.task.create'],
                     fn=objectgetter(models.Task, 'tid'),
                     raise_exception=True)
def create(request, tid):
    try:
        slogger.task[tid].info("create repository request")

        body = json.loads(request.body.decode('utf-8'))
        path = body["path"]
        lfs = body["lfs"]
        rq_id = "git.create.{}".format(tid)
        queue = django_rq.get_queue("default")

        queue.enqueue_call(func=CVATGit.initial_create,
                           args=(tid, path, lfs, request.user),
                           job_id=rq_id)
        return JsonResponse({"rq_id": rq_id})
Beispiel #9
0
from django.http import HttpResponse
from django.views.generic.edit import UpdateView, DeleteView

from rules.contrib.views import permission_required, objectgetter
from rules.contrib.views import LoginRequiredMixin, PermissionRequiredMixin

from .models import Book


class BookMixin(object):
    def get_object(self):
        return Book.objects.get(pk=self.kwargs['book_id'])


@permission_required('testapp.change_book', fn=objectgetter(Book, 'book_id'))
def change_book(request, book_id):
    return HttpResponse('OK')


class BookUpdateView(LoginRequiredMixin, PermissionRequiredMixin, BookMixin,
                     UpdateView):
    fields = ['title']
    template_name = 'empty.html'
    permission_required = 'testapp.change_book'


@permission_required('testapp.delete_book', fn=objectgetter(Book, 'book_id'))
def delete_book(request, book_id):
    return HttpResponse('OK')
Beispiel #10
0
def downloadThread(frames, tid, currentUser):
    for frame in frames:
        # Download the requested frame
        frame_path = task.get_frame_path(tid, frame)
        is_downloaded = downloadFile(settings.AWS_STORAGE_BUCKET_NAME, frame_path, frame_path)

        # Move the frame to a new folder under the current user name
        fileNameIndex = re.search(r'/\d+.jpg', frame_path)
        destination_path = frame_path[:fileNameIndex.start()] + '/' + currentUser + frame_path[fileNameIndex.start():]
        dir_path = frame_path[:fileNameIndex.start()] + '/' + currentUser
        if not os.path.isdir(dir_path):
            try:
                os.mkdir(dir_path)
            except FileExistsError as e:
                if not os.path.isdir(dir_path):
                    try:
                        os.remove(dir_path)
                        os.mkdir(dir_path)
                    except IsADirectoryError as e:
                        pass
            except OSError as e:
                if e.errno == errno.EEXIST:
                    if not os.path.isdir(dir_path):
                    try:
                        os.remove(dir_path)
                        os.mkdir(dir_path)
                    except IsADirectoryError as e:
                        pass
        
        if is_downloaded:
            os.rename(frame_path, destination_path)
        else:
            copyfile(frame_path, destination_path)

def shutdownThreads(tid, currentUser):
    if tid in runningThreads[currentUser]:
        end_frame = runningThreads[currentUser][tid]['endFrame']
        start_frame = runningThreads[currentUser][tid]['startFrame']
        runningThreads[currentUser].pop(tid, None)

        for frame in range(start_frame, end_frame):
            if str(frame) in downloadFrames[currentUser][tid]:
                downloadFrames[currentUser][tid][str(frame)].do_run = False
                del downloadFrames[currentUser][tid][str(frame)]

@login_required
@permission_required(perm=['engine.task.access'],
    fn=objectgetter(models.Task, 'tid'), raise_exception=True)
def exitProccess(request, tid):
    if request.user.username in watershedFrames:
        delete_frames_for_watershed(tid, request.user.username)

    # Stop all of the running threads and delete all leftover images on the server when the user exists the task.
    shutdownThreads(tid, request.user.username)
    exit_tracking_process(request.user.username, tid)
    for root, dirs, _ in os.walk('/home/django/data/' + str(tid)):
        for d in dirs:
            if os.path.join(root, d).endswith(request.user.username):
                shutil.rmtree(os.path.join(root, d))

    return HttpResponse()

@login_required
@permission_required(perm=['engine.task.access'],
    fn=objectgetter(models.Task, 'tid'), raise_exception=True)
def exitFromSegmentationMode(request, tid):

    delete_frames_for_watershed(tid, request.user.username)

    return HttpResponse()

def delete_frames_for_watershed(tid, username):
    watershedFrames.pop(username, None)
    for root, dirs, _ in os.walk('/home/django/data/watershed/' + str(tid)):
        for d in dirs:
            if os.path.join(root, d).endswith(username):
                shutil.rmtree(os.path.join(root, d))

@login_required
@permission_required(perm=['engine.task.access'],
    fn=objectgetter(models.Task, 'tid'), raise_exception=True)
def frames_for_watershed(request, tid, frame):
    try:
        stop_frame = list(models.Segment.objects.filter(task_id=tid).values_list("stop_frame", flat=True))[0] + 1
        q = django_rq.get_queue('mid')
        wanted_frames = []
        unwanted_frames = []

        # Set the range of frames to download
        if frame + 5 < stop_frame:
            stop_frame = frame + 5
        start_frame = frame - 2
        if start_frame < 0:
            start_frame = 0

        # If the user is not in the watershed frames create a dictionary for him.
        if request.user.username not in watershedFrames:
            watershedFrames[request.user.username] = {}
        if str(tid) in watershedFrames[request.user.username]:
            for i in range(start_frame, stop_frame):
                if i not in watershedFrames[request.user.username][str(tid)]:
                    wanted_frames.append(i)
            for j in watershedFrames[request.user.username][str(tid)]:
                if j < start_frame or j > stop_frame:
                    unwanted_frames.append(j)
            watershedFrames[request.user.username][str(tid)] = [i for i in range(start_frame, stop_frame)]
        else:
            watershedFrames[request.user.username][str(tid)] = [i for i in range(start_frame, stop_frame)]
            wanted_frames += watershedFrames[request.user.username][str(tid)]

        for wanted_frame in wanted_frames:
            q.enqueue_call(func=download_frame, args=(tid, wanted_frame, request.user.username),
                job_id="task/{}.frame/{}.download_frame".format(tid, wanted_frame))
        for unwanted_frame in unwanted_frames:
            q.enqueue_call(func=delete_frame, args=(tid, unwanted_frame, request.user.username),
                job_id="task/{}.frame/{}.delete_frame".format(tid, unwanted_frame))
        
        return HttpResponse()
    except Exception as e:
        slogger.task[tid].error("cannot get frame #{} for watershed".format(frame), exc_info=True)
        return HttpResponseBadRequest(str(e))

def download_frame(tid, frame, username):
    frame_path = task.get_frame_path(tid, frame)
    is_downloaded = downloadFile(settings.AWS_STORAGE_BUCKET_NAME, frame_path, frame_path)

    # Move the frame to a new folder under the current user name
    fileNameIndex = re.search(r'/\d+.jpg', frame_path)
    destination_path = '/home/django/data/watershed/' + str(tid) + "/" + username + frame_path[fileNameIndex.start():]
    dir_path = '/home/django/data/watershed/' + str(tid) + "/" + username
    if not os.path.isdir(dir_path):
        os.makedirs(dir_path)
    
    if is_downloaded:
        os.rename(frame_path, destination_path)
    else:
        copyfile(frame_path, destination_path)

def delete_frame(tid, frame, username):
    frame_path = task.get_frame_path(tid, frame)
    fileNameIndex = re.search(r'/\d+.jpg', frame_path)
    destination_path = '/home/django/data/watershed/' + str(tid) + "/" + username + frame_path[fileNameIndex.start():]
    os.remove(destination_path)

@login_required
@permission_required(perm=['engine.task.access'],
    fn=objectgetter(models.Task, 'tid'), raise_exception=True)
@never_cache
def get_frame_watershed(request, tid, frame):
    try:
        frame_watershed_path = task.get_frame_watershed_path(tid, frame)
    
        if os.environ.get('WITH_OS') == 'True':
            if os.path.exists(frame_watershed_path):
                q = django_rq.get_queue('default')
                q.enqueue_call(func=save_watershed_mask, args=(tid, frame),
                    job_id="task/{}.frame/{}.save_watershed_mask".format(tid, frame))
            else:
                try:
                    downloadFile(settings.AWS_STORAGE_BUCKET_NAME, frame_watershed_path, frame_watershed_path)
                except Exception as e:
                    pass
        
        if os.path.exists(frame_watershed_path):
            response = FileResponse(open(frame_watershed_path, 'rb'))
        else:
            response = FileResponse()

        return response
    except Exception as e:
        slogger.task[tid].error("cannot get frame #{} watershed".format(frame), exc_info=True)
        return HttpResponseBadRequest(str(e))

def save_watershed_mask(tid, frame):
    frame_watershed_path = task.get_frame_watershed_path(tid, frame)
    copyFileToOS(frame_watershed_path, frame_watershed_path)

@login_required
@permission_required(perm=['engine.task.delete'],
    fn=objectgetter(models.Task, 'tid'), raise_exception=True)
def delete_task(request, tid):
    """Delete the task"""
    try:
        slogger.glob.info("delete task #{}".format(tid))
        task.delete(tid)
    except Exception as e:
        slogger.glob.error("cannot delete task #{}".format(tid), exc_info=True)
        return HttpResponseBadRequest(str(e))

    return HttpResponse()

@login_required
@permission_required(perm=['engine.task.change'],
    fn=objectgetter(models.Task, 'tid'), raise_exception=True)
def update_task(request, tid):
    """Update labels & score for the task"""
    try:
        slogger.task[tid].info("update task request")
        labels = request.POST['labels']
        score = request.POST['score']
        assignee = request.POST['assignee']
        task.update(tid, labels, score, assignee)
    except Exception as e:
        slogger.task[tid].error("cannot update task", exc_info=True)
        return HttpResponseBadRequest(str(e))

    return HttpResponse()
    
@login_required
@permission_required(perm=['engine.task.change'],
    fn=objectgetter(models.Task, 'tid'), raise_exception=True)
def update_task_properties(request, tid):
    """Update labels for the task"""
    try:
        properties = json.loads(request.body.decode('utf-8'))
        task.updateProperties(tid, properties)
    except Exception as e:
        return HttpResponseBadRequest(str(e))

    return HttpResponse()

@login_required
@permission_required(perm=['engine.task.access'],
    fn=objectgetter(models.Task, 'tid'), raise_exception=True)
def get_task(request, tid):
    try:
        slogger.task[tid].info("get task request")
        response = task.get(tid)
    except Exception as e:
        slogger.task[tid].error("cannot get task", exc_info=True)
        return HttpResponseBadRequest(str(e))

    return JsonResponse(response, safe=False)

@login_required
@permission_required(perm=['engine.job.access'],
    fn=objectgetter(models.Job, 'jid'), raise_exception=True)
def get_job(request, jid):
    try:
        slogger.job[jid].info("get job #{} request".format(jid))
        response = task.get_job(jid)
    except Exception as e:
        slogger.job[jid].error("cannot get job #{}".format(jid), exc_info=True)
        return HttpResponseBadRequest(str(e))

    return JsonResponse(response, safe=False)

@login_required
@permission_required(perm=['engine.job.access'],
    fn=objectgetter(models.Job, 'jid'), raise_exception=True)
def get_task_byjob(request, jid):
    try:
        slogger.job[jid].info("get task by job #{} request".format(jid))
        response = task.get_task_byjob(jid)

        if response == {}:
            return HttpResponseBadRequest(str("Can not get task by jid #{}".format(jid)))

    except Exception as e:
        slogger.job[jid].error("cannot get job #{}".format(jid), exc_info=True)
        return HttpResponseBadRequest(str(e))

    return JsonResponse(response, safe=False)

@login_required
@permission_required(perm=['engine.task.access'],
    fn=objectgetter(models.Task, 'tid'), raise_exception=True)
def dump_annotation(request, tid):
    try:
        slogger.task[tid].info("dump annotation request")
        annotation.dump(tid, annotation.FORMAT_XML, request.scheme, request.get_host())
    except Exception as e:
        slogger.task[tid].error("cannot dump annotation", exc_info=True)
        return HttpResponseBadRequest(str(e))

    return HttpResponse()

@login_required
@gzip_page
@permission_required(perm=['engine.task.access'],
    fn=objectgetter(models.Task, 'tid'), raise_exception=True)
def check_annotation(request, tid):
    try:
        slogger.task[tid].info("check annotation")
        response = annotation.check(tid)
    except Exception as e:
        slogger.task[tid].error("cannot check annotation", exc_info=True)
        return HttpResponseBadRequest(str(e))

    return JsonResponse(response)


@login_required
@gzip_page
@permission_required(perm=['engine.task.access'],
    fn=objectgetter(models.Task, 'tid'), raise_exception=True)
def download_annotation(request, tid):
    try:
        slogger.task[tid].info("get dumped annotation")
        db_task = models.Task.objects.get(pk=tid)
        response = sendfile(request, db_task.get_dump_path(), attachment=True,
            attachment_filename='{}_{}.xml'.format(db_task.id, db_task.name))
    except Exception as e:
        slogger.task[tid].error("cannot get dumped annotation", exc_info=True)
        return HttpResponseBadRequest(str(e))

    return response

@login_required
@gzip_page
@permission_required(perm=['engine.task.access'],
    fn=objectgetter(models.Task, 'tid'), raise_exception=True)
def download_segmentation(request, tid):
    try:
        slogger.task[tid].info("get dumped segmentation")
        db_task = models.Task.objects.get(pk=tid)

        if os.environ.get('WITH_OS') == 'True':
            api_host = os.environ.get('API_HOST')
            api_secret = os.environ.get('API_SECRET')
            payload = { 'secret' : api_secret }
            payload = json.dumps(payload)
            headers = {
                "content-type": "application/json"
            }
            zip_url = "{}://{}/watershed/images?project.name={}&task.name={}".format('https' if os.environ.get('API_SECURE_SITE') == 'True' else 'http', 
                                                                                            api_host, 
                                                                                            db_task.project.name, 
                                                                                            db_task.name)
            response = requests.post(zip_url, data=payload, headers=headers, verify=False).content
            response = HttpResponse(response,  content_type='application/force-download')
        else:
            
            b = BytesIO()
            imagesZipFile = zipfile.ZipFile(b, mode='w')
            for frame in range(db_task.size):
                frame_watershed_path = task.get_frame_watershed_path(tid, frame)

                if os.path.exists(frame_watershed_path):
                    if db_task.mode == 'annotation':
                        db_task_source = models.TaskSource.objects.filter(task=db_task).filter(frame=frame)[0]
                        fname = db_task_source.source_name
                    else:
                        fdir, fname = os.path.split(frame_watershed_path)

                    zip_path = os.path.join(db_task.name, fname)
                    imagesZipFile.write(frame_watershed_path, zip_path)
            
            imagesZipFile.close()
            response = HttpResponse(b.getvalue(),  content_type="application/x-zip-compressed")

        response['Content-Disposition'] = 'attachment; filename="{}.zip"'.format(db_task.name)

    except Exception as e:
        slogger.task[tid].error("cannot get dumped segmentation", exc_info=True)
        return HttpResponseBadRequest(str(e))

    return response

@login_required
@gzip_page
@permission_required(perm=['engine.job.access'],
    fn=objectgetter(models.Job, 'jid'), raise_exception=True)
def get_annotation(request, jid):
    try:
        slogger.job[jid].info("get annotation for {} job".format(jid))
        response = annotation.get(jid)
    except Exception as e:
        slogger.job[jid].error("cannot get annotation for job {}".format(jid), exc_info=True)
        return HttpResponseBadRequest(str(e))

    return JsonResponse(response, safe=False)

@login_required
@permission_required(perm=['engine.job.change'],
    fn=objectgetter(models.Job, 'jid'), raise_exception=True)
def save_annotation_for_job(request, jid):
    try:
        slogger.job[jid].info("save annotation for {} job".format(jid))
        data = json.loads(request.body.decode('utf-8'))
        if 'annotation' in data:
            annotation.save_job(jid, json.loads(data['annotation']), data["taskid"], json.loads(data['frameProperties']))
        if 'logs' in data:
            for event in json.loads(data['logs']):
                clogger.job[jid].info(json.dumps(event))
        slogger.job[jid].info("annotation have been saved for the {} job".format(jid))
    except RequestException as e:
        slogger.job[jid].error("cannot send annotation logs for job {}".format(jid), exc_info=True)
        return HttpResponseBadRequest(str(e))
    except Exception as e:
        slogger.job[jid].error("cannot save annotation for job {}".format(jid), exc_info=True)
        return HttpResponseBadRequest(str(e))

    return HttpResponse()

@login_required
def parse_annotation_for_task(request, tid):
    return HttpResponse(task.parseTxtToXml(request.FILES.getlist('data')[0],tid))

@login_required
@permission_required(perm=['engine.task.change'],
    fn=objectgetter(models.Task, 'tid'), raise_exception=True)
def save_annotation_for_task(request, tid):
    try:
        slogger.task[tid].info("save annotation request")
        data = json.loads(request.body.decode('utf-8'))
        annotation.save_task(tid, data)
    except Exception as e:
        slogger.task[tid].error("cannot save annotation", exc_info=True)
        return HttpResponseBadRequest(str(e))

    return HttpResponse()

@login_required
@permission_required(perm=['engine.task.change'],
    fn=objectgetter(models.Task, 'tid'), raise_exception=True)
def delete_annotation_for_task(request, tid):
    try:
        slogger.task[tid].info("delete annotation request")
        annotation.clear_task(tid)
    except Exception as e:
        slogger.task[tid].error("cannot delete annotation", exc_info=True)
        return HttpResponseBadRequest(str(e))

    return HttpResponse()


@login_required
@permission_required(perm=['engine.job.change'],
    fn=objectgetter(models.Job, 'jid'), raise_exception=True)
def save_job_status(request, jid):
    try:
        data = json.loads(request.body.decode('utf-8'))
        status = data['status']
        slogger.job[jid].info("changing job status request")
        task.save_job_status(jid, status, request.user.username)
    except Exception as e:
        if jid:
            slogger.job[jid].error("cannot change status", exc_info=True)
        else:
            slogger.glob.error("cannot change status", exc_info=True)
        return HttpResponseBadRequest(str(e))
    return HttpResponse()

@login_required
@permission_required(perm=['engine.task.access'],
    fn=objectgetter(models.Task, 'tid'), raise_exception=True)
def track_task(request, tid):
    try:
        shapes = json.loads(request.body.decode('utf-8'))
        response = task.track_shapes(shapes, tid)
    except Exception as e:
        slogger.glob.error("cannot access/track", exc_info=True)
        return HttpResponseBadRequest(str(e))

    return JsonResponse(response, safe=False)

@login_required
@permission_required(perm=['engine.task.access'],
    fn=objectgetter(models.Task, 'tid'), raise_exception=True)
def track_all(request, tid):
    global entireVideoTracking

    if request.user.username not in entireVideoTracking:
        entireVideoTracking[request.user.username] = {}

    if tid not in entireVideoTracking[request.user.username]:
        entireVideoTracking[request.user.username] = {tid : {"downloaded": False, "startedDownloading": False, "video path" : "", "shapes" : {}}}

    currentTask = entireVideoTracking[request.user.username][tid]

    if not currentTask["downloaded"] and not currentTask["startedDownloading"]:
        currentTask["startedDownloading"] = True
        Thread(target=download_vid, args=(tid, currentTask,)).start()

    shape = json.loads(request.body.decode('utf-8'))

    if shape["id"] not in currentTask["shapes"]:
        currentTask["shapes"][shape["id"]] = {"positions": {}, "stopped": False, "finished": False}
        
    if currentTask["startedDownloading"] and not currentTask["shapes"][shape["id"]]["positions"]:
        return HttpResponse("Downloading...")

    if not currentTask["shapes"][shape["id"]]["positions"] and not currentTask["shapes"][shape["id"]]["finished"]:
        currentTask["shapes"][shape["id"]]["Thread"] = Thread(target=track_all_video, args=(shape, currentTask,))
        currentTask["shapes"][shape["id"]]["Thread"].start()

    temp_dict = {"results": currentTask["shapes"][shape["id"]]["positions"], "finished": currentTask["shapes"][shape["id"]]["finished"]}
    response = JsonResponse(temp_dict, safe=False)

    if temp_dict["finished"]:
        currentTask["shapes"].pop(shape["id"])
    elif len(temp_dict["results"].keys()) > 0:
        for key in list(temp_dict["results"]):
            currentTask["shapes"][shape["id"]]["positions"].pop(key, None)

    return response

@login_required
@permission_required(perm=['engine.task.access'],
    fn=objectgetter(models.Task, 'tid'), raise_exception=True)
def pause_tracking_all(request, tid, shapeId):
    if (request.user.username not in entireVideoTracking) or (tid not in entireVideoTracking[request.user.username]):
        return HttpResponse("No tracker stopped")

    currentTask = entireVideoTracking[request.user.username][tid]

    if shapeId in currentTask["shapes"]:
        currentTask["shapes"][shapeId]["stopped"] = True
    else:
        return HttpResponse("No tracker stopped")

    currentTask["shapes"][shapeId]["Thread"].join()

    response = JsonResponse({"results": currentTask["shapes"][shapeId]["positions"], "finished": currentTask["shapes"][shapeId]["finished"]}, safe=False)

    currentTask["shapes"].pop(shapeId)

    return response
    
@login_required
@permission_required(perm=['engine.task.access'],
    fn=objectgetter(models.Task, 'tid'), raise_exception=True)
def exit_tracking_process(request, tid):
    if entireVideoTracking:
        tasks = [task for user in entireVideoTracking.values() 
                    for task in user.keys() 
                    if task == tid]

        if len(tasks) == 1:
            currentTask = entireVideoTracking[username][tid]

            if os.path.exists(currentTask["video path"]):
                os.remove(currentTask["video path"])

        entireVideoTracking[username].pop(tid)

@login_required
@permission_required(perm=['engine.task.access'],
    fn=objectgetter(models.Task, 'tid'), raise_exception=True)
def video_file_exists(request, tid):
    if check_video_path(tid):
        response = HttpResponse("Video file exists")
    else:
        response = HttpResponse("Video file does not exist")

    return response

@login_required
@permission_required(perm=['engine.task.access'],
    fn=objectgetter(models.Task, 'tid'), raise_exception=True)
def stop_track_task(request, tid):
    try:
        task.stop_tracking(tid)
    except Exception as e:
        return HttpResponseBadRequest(str(e))
        
    return HttpResponse()
    
@login_required
@permission_required(perm=['engine.task.access'],
    fn=objectgetter(models.Task, 'tid'), raise_exception=True)
def watershed(request, tid, frame):
    try:
        frame_path = "/home/django/data/watershed/" + str(tid) + "/" + request.user.username + "/" + str(frame) + ".jpg"
        if not os.path.exists(frame_path):
            print("download frame")
            download_frame(tid, frame, request.user.username)
        draws = json.loads(request.body.decode('utf-8'))
        print("task watershed")
        task.watershed(tid, frame, draws['status'], request.user.username)
    except Exception as e:
        slogger.glob.error("cannot access/watershed", exc_info=True)
        return HttpResponseBadRequest(str(e))

    return HttpResponse()
    #return JsonResponse(response, safe=False)

def save_paintings(request, tid, frame):
    try:
        paintings = json.loads(request.body.decode('utf-8'))
        task.save_paintings(tid, frame, paintings['status'])
    except Exception as e:
        slogger.glob.error("cannot access/save_paintings", exc_info=True)
        return HttpResponseBadRequest(str(e))

    return HttpResponse()

def get_paintings(request, tid, frame):
    try:
        response = task.get_paintings(tid, frame)
    except Exception as e:
        slogger.glob.error("cannot access/get_paintings", exc_info=True)
        return HttpResponseBadRequest(str(e))

    return JsonResponse(response, safe=False)

@login_required
def is_staff(request):
    response = {'is_staff': request.user.has_perm("engine.views.is_staff")}
    return JsonResponse(response, safe=False)

@login_required
def get_username(request):
    response = {'username': request.user.username}
    return JsonResponse(response, safe=False)

def get_next_task(request, status, tid):
    if ((request.user.has_perm('dashboard.views.isManager')) or (request.user.has_perm('dashboard.views.isAdmin'))):
        response = task.nextJobIdByPriority("staff_user", status, tid)
    else:
        response = task.nextJobIdByPriority(request.user.username, status, tid)

    return HttpResponse(response)

@login_required
def updateTaskStatus(request, newStatus, taskId):
    try:
        # If the new status is not validation the user must be a manager to update it
        if (newStatus != 'validation'):
            if (not request.user.has_perm('dashboard.views.isManager')):
                return HttpResponseForbidden()
                
        db_task = models.Task.objects.get(pk=taskId)
        db_task.status = newStatus
        db_task.last_viewed_frame = 0
        db_task.save()
        db_job = models.Job.objects.get(segment__task=db_task)
        db_job.status = newStatus
        db_job.save()
    except Exception as e:
        slogger.glob.error("cannot update the target frame for task #{}".format(tid), exc_info=True)
        return HttpResponseBadRequest(str(e))

    return HttpResponse()

@login_required
def isManager(request):
    if (request.user.has_perm('dashboard.views.isManager')):
        return HttpResponse()
    else:
        return HttpResponseForbidden()
        
def get_matomo(request):
    response = None

    if (os.environ.get('MATOMO')):
        response = {'url': os.environ.get('MATOMO'), 'siteId': os.environ.get('MATOMO_SITE_ID'), 'userId': request.user.username}
        
    return JsonResponse(response, safe=False)

def rq_handler(job, exc_type, exc_value, tb):
    job.exc_info = "".join(traceback.format_exception_only(exc_type, exc_value))
    job.save()
    module = job.id.split('.')[0]
    if module == 'task':
        return task.rq_handler(job, exc_type, exc_value, tb)
    elif module == 'annotation':
        return annotation.rq_handler(job, exc_type, exc_value, tb)

    return True
Beispiel #11
0
        # NOTE: Regardless, we're only really concerned with the User
        # owning the VolunteerProfile, (rather than the profile itself),
        # so we'll just retrieve that here -- at the same time as
        # we *enforce the consistency of the parameters in the URL*
        # (otherwise we're just testing that the user knows their ID,
        # not that they actually own this profile):
        return get_object_or_404(
            User,
            pk=self.kwargs['user_pk'],
            volunteerprofile=self.kwargs['volunteer_pk'],
        )


@permission_required('user.is_same_user',
                     raise_exception=True,
                     fn=objectgetter(User, 'user_pk'))
def user_preferences_edit_view(request, user_pk):
    userprofile = get_object_or_404(User, pk=user_pk)
    if request.method == 'POST':
        try:
            marketplace.user.set_task_preferences(
                userprofile, request.POST.getlist('preferences'))
            return redirect('marketplace:user_profile', user_pk=user_pk)
        except KeyError:
            raise Http404
        except ValueError:
            pass
    elif request.method == 'GET':
        pass
    context = {
        'breadcrumb':
Beispiel #12
0
from django.db.models import Q
from rules.contrib.views import permission_required, objectgetter

from cvat.apps.authentication.decorators import login_required
from cvat.apps.engine.models import Task as TaskModel
from cvat.apps.authentication.auth import has_admin_role
from cvat.apps.engine.log import slogger

from .model_loader import load_labelmap
from . import model_manager
from .models import AnnotationModel


@login_required
@permission_required(perm=["engine.task.change"],
                     fn=objectgetter(TaskModel, "tid"),
                     raise_exception=True)
def cancel(request, tid):
    try:
        queue = django_rq.get_queue("low")
        job = queue.fetch_job("auto_annotation.run.{}".format(tid))
        if job is None or job.is_finished or job.is_failed:
            raise Exception("Task is not being annotated currently")
        elif "cancel" not in job.meta:
            job.meta["cancel"] = True
            job.save()

    except Exception as ex:
        try:
            slogger.task[tid].exception(
                "cannot cancel auto annotation for task #{}".format(tid),
Beispiel #13
0
from cvat.apps.engine.models import StatusChoice
from .downloader import download_file, download_file_m4s
from .handle_file_s3 import getFileUrl, downloadFile, copyFileToOS
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.models import User
watershedFrames = {}
runningThreads = {}
downloadFrames = {}
entireVideoTracking = {}
MAX_WORKER_COUNT = 5
FRAMES_DOWNLOAD_BUFFER = 100

############################# High Level server API
@login_required
@permission_required(perm=['engine.job.access'],
    fn=objectgetter(models.Job, 'jid'), raise_exception=True)
def catch_client_exception(request, jid):
    data = json.loads(request.body.decode('utf-8'))
    for event in data['exceptions']:
        clogger.job[jid].error(json.dumps(event))

    return HttpResponse()

@login_required
def dispatch_request(request):
    """An entry point to dispatch legacy requests"""
    if request.method == 'GET' and 'id' in request.GET:
        return render(request, 'engine/annotation.html', {
            'js_3rdparty': JS_3RDPARTY.get('engine', []),
            'status_list': [str(i) for i in StatusChoice]
        })
Beispiel #14
0
from django.http import HttpResponse, JsonResponse, HttpResponseBadRequest
from django.db.models import Q
from rules.contrib.views import permission_required, objectgetter

from cvat.apps.authentication.decorators import login_required
from cvat.apps.engine.models import Task as TaskModel
from cvat.apps.authentication.auth import has_admin_role
from cvat.apps.engine.log import slogger

from .model_loader import load_labelmap
from . import model_manager
from .models import AnnotationModel

@login_required
@permission_required(perm=["engine.task.change"],
    fn=objectgetter(TaskModel, "tid"), raise_exception=True)
def cancel(request, tid):
    try:
        queue = django_rq.get_queue("low")
        job = queue.fetch_job("auto_annotation.run.{}".format(tid))
        if job is None or job.is_finished or job.is_failed:
            raise Exception("Task is not being annotated currently")
        elif "cancel" not in job.meta:
            job.meta["cancel"] = True
            job.save()

    except Exception as ex:
        try:
            slogger.task[tid].exception("cannot cancel auto annotation for task #{}".format(tid), exc_info=True)
        except Exception as logger_ex:
            slogger.glob.exception("exception was occured during cancel auto annotation request for task {}: {}".format(tid, str(logger_ex)), exc_info=True)
Beispiel #15
0
        try:
            controle = Controle.objects.get(pk=pk)
        except Controle.DoesNotExist:
            logger.exception('Control not found')
            data['error_message'] = _('Contrôle inexistant')
            data['result'] = 'failure'
        else:
            data['result'] = 'success'
            data['status_display'] = controle.get_status_display()
            data['control_status'] = controle.status

        return JsonResponse(data)


@permission_required('risk_register.change_controle',
                     fn=objectgetter(Controle, 'pk'))
def change_control_status(request, pk):
    if request.method == 'POST' and request.is_ajax():
        data = {}

        try:
            controle = Controle.objects.get(pk=pk)
        except Controle.DoesNotExist:
            logger.exception('Controle not found')
            data['error_message'] = _('Contrôle inexistant')
            data['result'] = 'failure'
        else:
            if controle.status != request.POST.get('status'):
                data['result'] = 'failure'
                data['error_message'] = _('statut du contrôle désynchronisé.')
            elif controle.status == 'in_progress':
Beispiel #16
0
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from django.views import generic
from django.contrib.auth.decorators import login_required
from rules.contrib.views import permission_required, objectgetter
from django.views.decorators.http import require_http_methods
from django.shortcuts import get_object_or_404, redirect
from django.db import IntegrityError
from .models import HelpRequest, Class

def recent_requests(user):
    return HelpRequest.objects.filter(creator=user).order_by('-pub_datetime')

@permission_required('class.can_view', fn=objectgetter(Class, 'class_pk'))
def get_class(request, class_pk):
    klass = get_object_or_404(Class, pk=class_pk)
    requests = HelpRequest.objects.filter(klass=Class.objects.get(pk=class_pk))
    if klass.can_view_private(request.user):
        request_list = requests.order_by('-pub_datetime')[:]
    else:
        request_list = requests.filter(
            public=True).order_by('-pub_datetime')[:]
    if request.user.is_authenticated:
        request_list = request_list | requests.filter(creator=request.user.pk)
    context = {
        'requests_list': request_list,
        'klass': klass,
    }
    if request.user.has_perm('class.add_help_request'):
        context['urgency_choices'] = map(lambda x: x[0].title(),
Beispiel #17
0
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, render
from django.utils.translation import gettext as _
from rules.contrib.views import permission_required, objectgetter
from main.models import Stage
from .stages import manage_pool_stage, manage_cull_stage, manage_de_stage, manage_add_stage


@login_required
@permission_required('main.manage_competition',
                     fn=objectgetter(Stage,
                                     attr_name='stage_id',
                                     field_name='pk'),
                     raise_exception=True)
def manage_stage_router(request, org_slug, comp_id, stage_id):
    stage = get_object_or_404(Stage, pk=stage_id)
    if stage.type == Stage.POOL:
        pool_id = stage.poolstage_set.first().id
        return manage_pool_stage(request, pool_id)
    elif stage.type == Stage.CULL:
        cull_id = stage.cullstage_set.first().id
        return manage_cull_stage(request, cull_id)
    elif stage.type == Stage.DE:
        de_id = stage.destage_set.first().id
        return manage_de_stage(request, de_id)
    elif stage.type == Stage.ADD:
        add_id = stage.addstage_set.first().id
        return manage_add_stage(request, add_id)
    else:
        return HttpResponse("Not Implemented yet")
Beispiel #18
0
            tweet.save()
            return redirect('tweet:home')
    else:
        form = TweetForm()
    return render(request, 'tweet/tweet.html', {'form': form})

@login_required
def tdetail(request, pk):
    tweet = get_object_or_404(Tweet, pk=pk)
    favorite = Favorite.objects.filter(user=request.user, tweet=tweet)
    return render(request, 'tweet/tdetail.html', {
        'tweet': tweet,
        'favorite':favorite
        })

@permission_required('tweet.can_tedit',fn=objectgetter(Tweet, 'pk'))
def tedit(request, pk):
    tweet = get_object_or_404(Tweet, pk=pk)
    if request.method == 'POST':
        form = TweetForm(request.POST, instance=tweet)
        if form.is_valid():
            tweet.save()
            return redirect('tweet:home')
    else:
        form = TweetForm(instance=tweet)
    return render(request, 'tweet/tweet.html', {'form': form})

@require_POST
@permission_required('tweet.can_tedit',fn=objectgetter(Tweet, 'pk'))
def tdelete(request, pk):
    tweet = get_object_or_404(Tweet, pk=pk)
Beispiel #19
0
    Only allows superusers to view the history of a Course model object in the
    admin.
    """
    if request.user.is_superuser:
        # Hacky way to access the history_view of CourseAdmin, as I have not
        # found any other way to retrieve it. This is partly caused by this
        # view being the resolver of 'admin:semesterpage_course_history'.
        return admin.site._registry[Course].history_view(request, course_pk)
    else:
        # Don't need to do anything overly clever here, as this is not a normal
        # use case at all.
        return redirect('/')

@permission_required(
    'semesterpage.change_course',
    fn=objectgetter(Course, 'course_pk'),
)
def new_course_url(request, course_pk: str) -> HttpResponse:
    """
    A user has specified a URL for a course which previously had none.
    This should be saved to the Course model object before redirecting
    to the course homepage.
    """
    homepage_url = request.GET.get('homepage_url', '')

    # Need to prevent relative links
    if not homepage_url[:4].lower() == 'http':
        homepage_url = 'http://' + homepage_url

    course = Course.objects.get(pk=int(course_pk))
    course.homepage = homepage_url.strip()
Beispiel #20
0
def project_list(request):
    return render(request, 'projects/list.html', {})


@view_with_auth(['GET', 'POST'], (IsBusiness,))
@permission_required('projects.add_project', fn=Organization.from_request, raise_exception=True)
def project_create(request):
    """ Create new project

    Create a new project linked to the business account
    """
    return render(request, 'projects/create.html', {})


@view_with_auth(['GET'], (IsBusiness,))
@permission_required('projects.change_project', fn=objectgetter(Project, 'pk'), raise_exception=True)
def project_settings(request, pk):
    project = get_object_with_check_and_log(request, Project, pk=pk)
    return render(request, 'projects/settings.html', {
        'project': project,
    })


def playground_replacements(request, task_data):
    if request.GET.get('playground', '0') == '1':
        for key in task_data:
            if "/samples/time-series.csv" in task_data[key]:
                task_data[key] = "https://app.heartex.ai" + task_data[key]
    return task_data

Beispiel #21
0
import json
import rq

__RQ_QUEUE_NAME = "default"
__DEXTR_HANDLER = DEXTR_HANDLER()


def _dextr_thread(db_data, frame, points):
    job = rq.get_current_job()
    job.meta["result"] = __DEXTR_HANDLER.handle(db_data, frame, points)
    job.save_meta()


@login_required
@permission_required(perm=["engine.job.change"],
                     fn=objectgetter(Job, "jid"),
                     raise_exception=True)
def create(request, jid):
    try:
        data = json.loads(request.body.decode("utf-8"))

        points = data["points"]
        frame = int(data["frame"])
        username = request.user.username

        slogger.job[jid].info(
            "create dextr request for the JOB: {} ".format(jid) +
            "by the USER: {} on the FRAME: {}".format(username, frame))

        db_data = Job.objects.select_related("segment__task__data").get(
            id=jid).segment.task.data
Beispiel #22
0
                self.request.POST)
            return HttpResponseRedirect(self.get_success_url())
        except KeyError as k:
            form.add_error(None, str(k))
            return super().form_invalid(form)


class CreateOrganizationRoleForm(ModelForm):
    class Meta:
        model = OrganizationRole
        fields = ['role', 'user']


@permission_required('organization.staff_view',
                     raise_exception=True,
                     fn=objectgetter(Organization, 'org_pk'))
def organization_staff_view(request, org_pk):
    if request.method == 'POST':
        form = CreateOrganizationRoleForm(request.POST)
        if form.is_valid():
            organization_role = form.save(commit=False)
            try:
                OrganizationService.add_staff_member(request.user, org_pk,
                                                     organization_role)
                messages.info(request, 'Staff member added successfully.')
                return redirect('marketplace:org_staff', org_pk=org_pk)
            except KeyError:
                raise Http404
            except ValueError:
                form.add_error(
                    None, "This user is already a member of the organization.")
Beispiel #23
0
            if job is not None:
                result[tid] = {
                    "active": job.is_queued or job.is_started,
                    "success": not job.is_failed
                }

        return JsonResponse(result)
    except Exception as ex:
        slogger.glob.exception('exception was occured during tf meta request',
                               exc_info=True)
        return HttpResponseBadRequest(str(ex))


@login_required
@permission_required(perm=['engine.task.change'],
                     fn=objectgetter(TaskModel, 'tid'),
                     raise_exception=True)
def create(request, tid):
    slogger.glob.info('tf annotation create request for task {}'.format(tid))
    try:
        db_task = TaskModel.objects.get(pk=tid)
        queue = django_rq.get_queue('low')
        job = queue.fetch_job('tf_annotation.create/{}'.format(tid))
        if job is not None and (job.is_started or job.is_queued):
            raise Exception("The process is already running")

        db_labels = db_task.label_set.prefetch_related(
            'attributespec_set').all()
        db_labels = {db_label.id: db_label.name for db_label in db_labels}

        tf_annotation_labels = {
Beispiel #24
0
from rules.contrib.views import LoginRequiredMixin, PermissionRequiredMixin

from .models import Book


class BookMixin(object):
    def get_object(self):
        return Book.objects.get(pk=self.kwargs['book_id'])


class BookMixinWithError(object):
    def get_object(self):
        raise AttributeError('get_object')


@permission_required('testapp.change_book', fn=objectgetter(Book, 'book_id'))
def change_book(request, book_id):
    return HttpResponse('OK')



class BookCreateView(LoginRequiredMixin, PermissionRequiredMixin, BookMixin, CreateView):
    fields = ['title']
    template_name = 'empty.html'
    permission_required = 'testapp.create_book'


class BookUpdateView(LoginRequiredMixin, PermissionRequiredMixin, BookMixin, UpdateView):
    fields = ['title']
    template_name = 'empty.html'
    permission_required = 'testapp.change_book'
Beispiel #25
0
class MaquinaUpdateView(PermissionRequiredMixin, SuccessMessageMixin,
                        UpdateView):

    model = Maquina
    form_class = EditMaquinaForm
    template_name = 'maquinas/maquina_create_edit.html'
    permission_required = 'maquina.can_manage'

    success_message = 'Máquina atualizada com sucesso!'

    def get_success_url(self):
        return reverse('registro:maquinas')


@permission_required('maquina.can_manage', fn=objectgetter(Maquina, 'pk'))
def maquina_remove(request, pk):

    maquina = get_object_or_404(Maquina, pk=pk)

    try:
        maquina.delete()
        messages.info(request, 'Máquina excluída com sucesso!')
    except ProtectedError:
        messages.error(
            request,
            'Essa máquina não pode ser removida! Existem registros associados.'
        )
    return redirect('registro:maquinas')

Beispiel #26
0
import django_rq
import json
import rq


def _create_thread(jid, data):
    job = rq.get_current_job()
    reid_obj = ReID(jid, data)
    job.meta["result"] = json.dumps(reid_obj.run())
    job.save_meta()


@login_required
@permission_required(perm=["engine.job.change"],
                     fn=objectgetter(Job, 'jid'),
                     raise_exception=True)
def start(request, jid):
    try:
        data = json.loads(request.body.decode('utf-8'))
        queue = django_rq.get_queue("low")
        job_id = "reid.create.{}".format(jid)
        job = queue.fetch_job(job_id)
        if job is not None and (job.is_started or job.is_queued):
            raise Exception('ReID process has been already started')
        queue.enqueue_call(func=_create_thread,
                           args=(jid, data),
                           job_id=job_id,
                           timeout=7200)
        job = queue.fetch_job(job_id)
        job.meta = {}
Beispiel #27
0
            "gameform": GameForm(instance=game, auto_id="id_%s_" + uuid.uuid4().hex),
            "bookingform": BookingForm(
                initial={"game": game}, auto_id="id_%s_" + uuid.uuid4().hex
            ),
        },
        request=request,
    )
    return {
        "form_html": form_html,
        "game_html": game_html,
        "nav_html": _get_nav_html(game, request),
        "order": _get_game_order(game),
    }


@permission_required("booking.change_game", fn=objectgetter(Game, "game_id"))
def move_game(request, game_id, direction):
    game = get_object_or_404(Game, pk=game_id)

    if direction not in ["up", "down", None]:
        return HttpResponseBadRequest("Unknown direction")

    if direction == "up":
        game.up()
    elif direction == "down":
        game.down()

    return JsonResponse({"success": True, **_get_game_response(game, request)})


@permission_required("booking.change_game", fn=objectgetter(Game, "game_id"))
Beispiel #28
0
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from rules.contrib.views import permission_required, objectgetter
from main.models import Competition, Organisation, Stage
from ..forms.competition import CreateCompetitionForm


@login_required
@permission_required('main.create_competition',
                     fn=objectgetter(Organisation,
                                     attr_name='org_slug',
                                     field_name='slug'))
def create_competition(request, org_slug):
    org = get_object_or_404(Organisation, slug=org_slug)
    if request.method == 'POST':
        form = CreateCompetitionForm(request.POST)
        if form.is_valid():
            comp = org.competition_set.create(name=form.cleaned_data['name'],
                                              date=form.cleaned_data['date'])

            return HttpResponseRedirect(
                reverse('ui/manage_competition', args=[org_slug, comp.id]))
    else:
        form = CreateCompetitionForm()

    return render(request, 'ui/competition/create.html', {'form': form})


def list_competitions(request, org_slug):
Beispiel #29
0
from rules.contrib.views import permission_required, objectgetter
from django.views.decorators.gzip import gzip_page
from sendfile import sendfile

from . import annotation, task, models
from cvat.settings.base import JS_3RDPARTY
from cvat.apps.authentication.decorators import login_required
from requests.exceptions import RequestException
import logging
from .log import slogger, clogger
from cvat.apps.engine.models import StatusChoice

############################# High Level server API
@login_required
@permission_required(perm=['engine.job.access'],
    fn=objectgetter(models.Job, 'jid'), raise_exception=True)
def catch_client_exception(request, jid):
    data = json.loads(request.body.decode('utf-8'))
    for event in data['exceptions']:
        clogger.job[jid].error(json.dumps(event))

    return HttpResponse()

@login_required
def dispatch_request(request):
    """An entry point to dispatch legacy requests"""
    if request.method == 'GET' and 'id' in request.GET:
        return render(request, 'engine/annotation.html', {
            'js_3rdparty': JS_3RDPARTY.get('engine', []),
            'status_list': [str(i) for i in StatusChoice]
        })
    if grade_float >= 90:
        return GRADE_A
    elif grade_float >=80:
        return GRADE_B
    elif grade_float >=70:
        return GRADE_C
    else:
        return GRADE_LOW


def get_home_template(request):
    return render(request, 'frontend/index.html')


@permission_required('dashboard.get_course_info',
    fn=objectgetter(Course, 'course_id', 'canvas_id'), raise_exception=True)
def get_course_info(request, course_id=0):
    """Returns JSON data about a course

    :param request: HTTP Request
    :type request: Request
    :param course_id: Unizin Course ID, defaults to 0
    :param course_id: int, optional
    :return: JSON to be used
    :rtype: str
    """
    course_id = canvas_id_to_incremented_id(course_id)
    today = timezone.now()

    try:
        course = Course.objects.get(id=course_id)
Beispiel #31
0
            return HttpResponse(
                "Pools must have an add fencers stage somewhere before them")
    elif state == Stage.READY:
        pools = pool.pool_set.all()
        return render(request, 'ui/stages/pool/READY.html', {
            'pools': pools,
            'stage_id': pool.stage.id
        })
    elif state == Stage.STARTED:
        pools = pool.pool_set.all()
        all_completed = all(map(lambda x: x.complete(), pools))
        return render(request, 'ui/stages/pool/STARTED.html', {
            'stage': pool.stage,
            'pools': pools,
            'all_completed': all_completed
        })
    else:
        pools = pool.pool_set.all().order_by('number')
        return render(request, 'ui/stages/pool/FINISHED.html', {
            'stage': pool.stage,
            'pools': pools
        })


@login_required
@permission_required('main.manage_competition',
                     fn=objectgetter(Pool, 'pool_id'))
def dt_manage_pool(request, pool_id):
    return render(request, 'ui/stages/pool/dt_pool_edit.html',
                  {'pool_id': pool_id})
from continuing_education.models.prospect import Prospect
from continuing_education.views.common import get_object_list


@login_required
@permission_required('continuing_education.view_prospect',
                     raise_exception=True)
def list_prospects(request):
    prospects_list = get_prospects_by_user(request.user)
    return render(
        request, "prospects.html", {
            'prospects': get_object_list(request, prospects_list),
            'prospects_count': len(prospects_list)
        })


@login_required
@permission_required('continuing_education.view_prospect',
                     fn=objectgetter(Prospect, 'prospect_id'),
                     raise_exception=True)
def prospect_details(request, prospect_id):
    prospect = get_object_or_404(Prospect, pk=prospect_id)
    return render(request, "prospect_details.html", {'prospect': prospect})


@login_required
@permission_required('continuing_education.export_prospect',
                     raise_exception=True)
def prospect_xls(request):
    return create_xls(request.user)