Пример #1
0
def update_answer_result(request):
    """
    Receive call from poll entity for updating the syntax check result of an existing answer.
    
    Needs logged in user. User have to be the creater of the poll.
    
    Parameter:

    :request: Request HTTP-POST
    
    :cloze_text_id(string): 8 digits as string (existing poll id)

    :cloze_answer(string): HTTP-POST parameter: answer of the poll
    
    :syntaxresult(string): HTTP-POST parameter: result of the syntax check for given answer ('False', 'True', 'None', 'Forbidden')
    
    :answer_type(string, optional): HTTP-POST parameter: 'byEach'
    
    Returns one of the following:

    :HttpResponse: with status code on error

    :JsonResponse: if statuscode is 200 and next is not set
    """
    if not request.user.is_authenticated:
        return HttpResponse("Please login.",
                            status=401)  # HTTP_401_UNAUTHORIZED

    if request.method != 'POST':
        return HttpResponse("Invalid/Bad request",
                            status=400)  # HttpResponseBadRequest
    try:
        cloze_test_id = from_req(request, 'cloze_test_id')
    except KeyError:
        return HttpResponse("Bad request. KeyError cloze_test_id", status=400)
    try:
        update_answers(user=get_user(request),
                       ct_id=cloze_test_id,
                       ct_answer=from_req(request, 'cloze_answer'),
                       ca_num=from_req(request, 'answer_num'),
                       ca_type=from_req(request,
                                        'answer_type',
                                        default='byEach'),
                       ca_result=from_req(request, 'syntaxresult'))
        result = evaluate_cloze_test(cloze_test_id, user=get_user(request))
        result['poll'] = get_cloze_test("{}".format(cloze_test_id),
                                        user=get_user(request))

    except ForbiddenError as fe:
        return HttpResponseForbidden(str(fe))
    except KeyError as e:
        return HttpResponse("Bad request. KeyError. " + e, status=400)
    except Exception as e:
        return HttpResponse("Unknown error: {}".format(e), status=404)
    return JsonResponse(result)
Пример #2
0
def start_poll(request):
    """
    Receive call from poll entity for starting poll. Needs a logged in user and a post request with specific parameter.
    
    Needs logged in user. 
    
    Parameter:

    :request: Request HTTP-POST

    :cloze_name(string, optional): HTTP-POST parameter: title of the poll

    :cloze_text(string, optional): HTTP-POST parameter: source code for the poll

    :cloze_count(string, optional): HTTP-POST parameter: count of gaps in cloze_text

    :language(string, optional): HTTP-POST parameter: language of cloze_text (e.g. python, java, c, c++, R) (optional)

    :active(boolean, optional): HTTP-POST parameter: status of the poll (optional)
    
    Returns one of the following:

    :HttpResponse: with status code on error

    :JsonResponse: if statuscode is 200; returns object with cloze_test_id 
    """
    if not request.user.is_authenticated:
        return HttpResponse("Please login.",
                            status=401)  # HTTP_401_UNAUTHORIZED

    if request.method != 'POST':
        return HttpResponse("Invalid/Bad request",
                            status=400)  # HttpResponseBadRequest

    # Generate new id for cloze test
    cloze_test_id = unique_cloze_test_id_generator()
    try:
        # Create new cloze test table in database
        create_cloze_test(ct_id=cloze_test_id,
                          ct=from_req(request, 'cloze_test'),
                          cloze_count=from_req(request, 'cloze_count'),
                          ct_name=from_req(request, 'cloze_name'),
                          user=get_user(request),
                          language=from_req(request, 'language'))
    except KeyError as ke:
        print(ke)
        return HttpResponse("Bad request. KeyError.", status=400)
    except Exception as e:
        return HttpResponse("Unknown error: {}".format(e), status=404)
    return JsonResponse({'cloze_test_id': cloze_test_id})
Пример #3
0
def stop_poll(request):
    """
    Receive call from poll entity for stoping poll. Calcating percentage for answers in two formats:
    byBundle and byEach. 
    ByBundle calculates percentage for whole unique answers. byEach calculates percentage per gap in cloze.
    
    Needs logged in user. User have to be the creater of the poll.
    
    Parameter:

    :request: Request HTTP-POST
    
    :cloze_text_id(string): 8 digits as string (existing poll id)
        
    Returns one of the following:

    :HttpResponse: with status code on error

    :JsonResponse: if statuscode is 200; return the poll result object

    Returned Format additional to poll information:

    'results':{
        'byBundle':[{"clozes":[{"nr":"#1","code":"answer1.1"},{"nr":"#2","code":"answer1.2"}],"name":"Answer","percentage":100, 'syntaxcheck':'False'}],
        'byEach':[
            {"nr":"#1","clozes":[{"code":"answer1.1","percentage":100, 'syntaxcheck':'True'}]},
            {"nr":"#2","clozes":[{"code":"answer1.2","percentage":100, 'syntaxcheck':'False'}]}
        ]
    },


    """
    if not request.user.is_authenticated:
        return HttpResponse("Please login.", status=401)

    if request.method != 'POST':
        return HttpResponse("Invalid/Bad request", status=400)
    try:
        ct_id = from_req(request, 'cloze_test_id')
    except KeyError:
        return HttpResponse("Bad request. KeyError cloze_test_id", status=400)

    try:
        result = evaluate_cloze_test(ct_id, user=get_user(request))
        result['poll'] = get_cloze_test("{}".format(ct_id),
                                        user=get_user(request))
    except ForbiddenError as fe:
        return HttpResponseForbidden(str(fe))
    except KeyError:
        # return HttpResponse("Poll does not exist", status=404)
        return JsonResponse({'Error': 'Invalid Id'})
    except Exception as e:
        return HttpResponse("Unknown error: {}".format(e), status=404)
    # Evaluate cloze test and return results
    return JsonResponse(result)
Пример #4
0
def test_code(request):
    """
    Receive call from poll entity for test poll code. Depend on the language of 
    the source code it will be executed (Python, R) or compiled (Java, C, C++, JavaScript).
    Before excuting it will be checked for 'forbidden content'. 
    If code match any of regular expressions contains in :model: ForbiddenExecTexts,
    the result of the test, will be: Forbidden
    Otherwise: 'True' for successfully compiled/executed, 'False' for failed, 
    and 'None' if the execution took to long time (e.g. infinity loop)
    
    Needs logged in user. User have to be the creater of the poll.
    
    Parameter:

    :request: Request HTTP-POST
    
    :cloze_text(string, optional): HTTP-POST parameter: source code for the poll
    
    :language(string, optional): HTTP-POST parameter: language of cloze_text (e.g. python, java, c, c++, R) (optional)
        
    Returns one of the following:

    :HttpResponse: with status code on error

    :JsonResponse: if statuscode is 200; object with result contains one of the following 'True', 'False', 'None', 'Forbidden'
    """
    if not request.user.is_authenticated:
        return HttpResponse("Please login.",
                            status=401)  # HTTP_401_UNAUTHORIZED
    try:
        lang = from_req(request, 'language')
        cloze_test = build_codeanswer(from_req(request, 'cloze_test'), lang)
        is_correct = str(do_syntax_check(lang, cloze_test))
    except KeyError:
        return HttpResponse("Bad request. KeyError cloze_test_id", status=400)
    except ForbiddenExecution as fe:
        is_correct = "Forbidden"
    return JsonResponse({'result': is_correct})
Пример #5
0
def activate_poll(request):
    """
    Receive call from poll entity for activate poll (again)
    
    Needs logged in user. User have to be the creater of the poll.
    
    Parameter:

    :request: Request HTTP-POST
    
    :next(string, optional): HTTP-GET parameter: define the redirect url 

    :cloze_text_id(string): 8 digits as string (existing poll id)
        
    Returns one of the following:

    :HttpResponse: with status code on error

    :JsonResponse: if statuscode is 200 and next is not set; contains poll object

    :HttpsResponseRedirect: if HTTP-GET Param 'next' is set
    
    """
    if not request.user.is_authenticated:
        return HttpResponse("Please login.",
                            status=401)  # HTTP_401_UNAUTHORIZED

    if request.method != 'POST':
        return HttpResponse("Invalid/Bad request",
                            status=400)  # HttpResponseBadRequest
    try:
        ct_id = from_req(request, 'cloze_test_id')
    except KeyError:
        return HttpResponse("Bad request. KeyError cloze_test_id", status=400)
    try:
        set_poll_status(ct_id, True, user=get_user(request))
        poll = get_cloze_test("{}".format(ct_id), user=get_user(request))
    except ForbiddenError as fe:
        return HttpResponseForbidden(str(fe))
    except KeyError:
        return HttpResponse("Poll does not exist", status=404)
    except Exception as e:
        return HttpResponse("Unknown error: {}".format(e), status=404)

    next = request.GET.get('next', None)
    if next:
        return HttpResponseRedirect(next)
    return JsonResponse(poll)
Пример #6
0
def vote_view(request, *args, **kwargs):
    """
    Render the view, which is allows the participation for given poll id. Shows cloze_test.
    
    Parameter:

    :request: HTTP request
    
    :cloze_text_id(string): 8 digits as string (existing poll id)

    Returns one of the following:

    :HttpRedirect: redirects to :view:`pages.home`
    """
    try:
        cloze_test_id = from_req(request, 'cloze_test_id')
        cloze_test_id = clean_answer(cloze_test_id, " *", "")
    except KeyError:
        messages.error(request, 'Cloze ID not found.')
        return redirect('views:home')

    if exists(cloze_test_id):
        ct = get_cloze_test(cloze_test_id)
        if ct.active:
            print("Already votes?")
            if request.user.is_authenticated and is_poll_creator(
                    get_user(request), ct):
                pass
            elif already_voted(request.COOKIES.get('usid', None), ct):
                messages.error(request, 'You have already voted.')
                return redirect('views:home')
            content = {
                'cloze_test_id': ct.cloze_test_id,
                'code': ct.cloze_test,
                'cloze_count': [i + 1 for i in range(ct.cloze_count)],
                'language': ct.language,
                # 'user':get_user_details
            }
            return render(request, 'vote.html', content)
        else:
            messages.error(request, 'Voting for cloze not active')
            # print('Voting for this Session ID not acitve')
            return redirect('views:home')
    # messages.error(request, 'Session ID not correct.')
    messages.error(request, 'Cloze ID not exists.')
    # print('Session ID not correct')
    return redirect('views:home')
Пример #7
0
def status_poll(request):
    """
    Receive call from poll entity for getting the count of answers dor a specific poll id
    
    Needs logged in user. User have to be the creater of the poll.
    
    Parameter:

    :request: Request HTTP-POST
    
    :next(string, optional): HTTP-GET parameter: define the redirect url 

    :cloze_text_id(string): 8 digits as string (existing poll id)

    Returns one of the following:

    :HttpResponse: with status code on error

    :JsonResponse: if statuscode is 200; contains object with cloze_answer_count
    """
    if not request.user.is_authenticated:
        return HttpResponse("Please login.",
                            status=401)  # HTTP_401_UNAUTHORIZED

    if request.method != 'POST':
        return HttpResponse("Invalid/Bad request", status=400)
    try:
        ct_id = from_req(request, 'cloze_test_id')
    except KeyError:
        return HttpResponse("Bad request. KeyError cloze_test_id", status=400)

    try:
        answer_count = get_answer_count(ct_id, user=get_user(request))
    except ForbiddenError as fe:
        return HttpResponseForbidden(str(fe))
    except KeyError:
        return HttpResponse("Poll does not exist", status=404)
        # return KeyError({'Error': 'Invalid Id'})
        # return JsonResponse({'Error': 'Invalid Id'})
    except Exception as e:
        return HttpResponse("Unknown error: {}".format(e), status=404)
    # Evaluate cloze test and return results
    return JsonResponse({"cloze_answer_count": answer_count})
Пример #8
0
def delete_poll(request):
    """
    Receive call from poll entity for delete poll. This can not be undone.
    
    Needs logged in user. User have to be the creater of the poll.

    Parameter:

    :request: Request HTTP-POST
    
    :next(string, optional): HTTP-GET parameter: define the redirect url 

    :cloze_text_id(string): 8 digits as string (existing poll id)
    
    Returns one of the following:

    :HttpResponse: with status code on error

    :JsonResponse: if statuscode is 200 and next is not set
    
    :HttpsResponseRedirect: if HTTP-GET Param 'next' is set
    """
    if not request.user.is_authenticated:
        return HttpResponse("Please login.",
                            status=401)  # HTTP_401_UNAUTHORIZED
    if request.method != 'POST':
        return HttpResponse("Invalid/Bad request",
                            status=400)  # HttpResponseBadRequest
    try:
        ct_id = from_req(request, 'cloze_test_id')
    except KeyError:
        return HttpResponse("KeyError: cloze_test_id", status=404)
    user = get_user(request)
    try:
        delete_cloze_test(ct_id, user)
    except Exception:
        return HttpResponse("Could not delete poll", status=404)

    next = request.GET.get('next', None)
    if next:
        return HttpResponseRedirect(next)
    return HttpResponse("deleted poll", status=200)
Пример #9
0
def get_poll(request):
    """
    Receive call from poll entity for getting poll information including all attributes.
    
    Needs logged in user. User have to be the creater of the poll.
    
    Parameter:

    :request: Request HTTP-POST

    :cloze_text_id(string): 8 digits as string (existing poll id)
    
    Returns one of the following:

    :HttpResponse: with status code on error

    :JsonResponse: if statuscode is 200; including poll object
    
    """
    if not request.user.is_authenticated:
        return HttpResponse("Please login.",
                            status=401)  # HTTP_401_UNAUTHORIZED

    if request.method != 'POST':
        return HttpResponse("Invalid/Bad request",
                            status=400)  # HttpResponseBadRequest
    try:
        ct_id = from_req(request, 'cloze_test_id')
    except KeyError:
        return HttpResponse("Bad request. KeyError cloze_test_id", status=400)
    try:
        poll = get_cloze_test("{}".format(ct_id), user=get_user(request))
    except KeyError:
        return HttpResponse("Poll {} does not exist".format(ct_id), status=404)
    except ForbiddenError as fe:
        return HttpResponseForbidden(str(fe))
    except Exception as e:
        return HttpResponse("Unknown error: {}".format(e), status=404)
    return JsonResponse(poll)
Пример #10
0
def status_view(request, *args, **kwargs):
    """
    Render the view, which is visible after answering the poll
    
    Needs logged in user. 
    
    Parameter:

    :request: HTTP reequest

    :cloze_text_id(string): 8 digits as string (existing poll id)

    Returns one of the following:

    :HttpResponse: with rendered template :template:`status.html`
    """
    try:
        cloze_test_id = from_req(request, 'cloze_test_id')
        cloze_test_id = clean_answer(cloze_test_id, " *", "")
    except KeyError:
        return status(request, 'failure', 'Error', 'Cloze ID not found.')

    if not exists(cloze_test_id):
        return status(request, 'failure', 'Error', 'Cloze ID not exists.')

    ct = get_cloze_test(cloze_test_id)
    if not ct.active:
        return status(request, 'failure', 'Cloze test inactive',
                      'Voting no longer available')
    try:
        if request.user.is_authenticated:
            if is_poll_creator(get_user(request), ct):
                pass
            else:
                print("request ", request)
                print("SESSION", request.session)
                print("SESSION id ", request.session.get('usid', None))
                if already_voted(request.COOKIES.get('usid', None), ct):
                    messages.error(request, 'You have already voted.')
                    return redirect('views:home')
        else:
            if already_voted(request.COOKIES.get('usid', None), ct):
                messages.error(request, 'You have already voted.')
                return redirect('views:home')
    except Exception:
        pass
    answers = []
    for i in range(ct.cloze_count):
        try:
            cloze_i = from_req(request, 'cloze_' + str(i + 1))
        except KeyError:
            return status(request, 'neutral', 'Incomplete',
                          'Please fill in all the clozes')

        cloze_i = clean_answer(cloze_i)
        answers.append(cloze_i)
        if answers[-1] == '' or answers[-1].isspace():
            answers[-1] = ""
    sid = request.session._get_or_create_session_key()
    cas = save_answers(ct, answers, sid)
    try:
        cloze_test = build_code(ct.cloze_test, answers, ct.language)
        print("1TEST: ", cloze_test)
        is_correct_merged = str(do_syntax_check(ct.language, cloze_test))
    except ForbiddenExecution as fe:
        is_correct_merged = "Forbidden"
    print("1RESULT: ", is_correct_merged, type(is_correct_merged))
    if ct.cloze_count > 1 and is_correct_merged != "True":
        # print("First check is not successful")
        is_correct = [''] * ct.cloze_count
        for i in range(ct.cloze_count):
            print('\n' * 3)
            try:
                cloze_test = build_codeanswer(ct.cloze_test, ct.language, i,
                                              answers)
                is_correct[i] = str(do_syntax_check(ct.language, cloze_test))
            except ForbiddenExecution as fe:
                is_correct[i] = "Forbidden"
    else:
        is_correct = [is_correct_merged] * ct.cloze_count
    for i in range(ct.cloze_count):
        cas[i + 1].result = syntax_result[is_correct[i]]
        cas[i + 1].save()

    # Result of unit tests depends on message words: 'not compile', 'wrong', 'hack', 'successfully'
    response = status(request, 'success', 'Thanks for Voting!',
                      'Unknown Result of compiling: ' + is_correct_merged)
    if is_correct_merged == "None":
        response = status(request, 'success', 'Thanks for Voting!',
                          'Could not compile the code.')
    elif is_correct_merged == "False":
        response = status(request, 'success', 'Thanks for Voting!',
                          'Something in your syntax was wrong.')
    elif is_correct_merged == "Forbidden":
        response = status(request, 'success', 'Thanks for Voting!',
                          'Dont try to hack the system ;-).')
    elif is_correct_merged == "True":
        response = status(
            request, 'success', 'Thanks for Voting! :)',
            'Code compiled successfully. {}'.format(
                '' if ct.language != 'python' else ''))
    response.set_cookie('usid', sid)
    return response
Пример #11
0
def update_poll(request):
    """
    Receive call from poll entity for updating an existing poll. Only update the given parameter
    
    Needs logged in user. User have to be the creater of the poll.
    
    Parameter:

    :request: Request HTTP-POST
    
    :next(string, optional): HTTP-GET parameter: define the redirect url 

    :cloze_text_id(string): 8 digits as string (existing poll id)

    :cloze_name(string, optional): HTTP-POST parameter: title of the poll
    
    :cloze_text(string, optional): HTTP-POST parameter: source code for the poll
    
    :cloze_count(string, optional): HTTP-POST parameter: count of gaps in cloze_text
    
    :language(string, optional): HTTP-POST parameter: language of cloze_text (e.g. python, java, c, c++, R) (optional)
    
    :active(boolean, optional): HTTP-POST parameter: status of the poll (optional)
    
    Returns one of the following:

    :HttpResponse: with status code on error

    :JsonResponse: if statuscode is 200 and next is not set
    
    :HttpsResponseRedirect: if HTTP-GET Param 'next' is set
    """
    if not request.user.is_authenticated:
        return HttpResponse("Please login.",
                            status=401)  # HTTP_401_UNAUTHORIZED

    if request.method != 'POST':
        return HttpResponse("Invalid/Bad request",
                            status=400)  # HttpResponseBadRequest
    try:
        cloze_test_id = from_req(request, 'cloze_test_id')
    except KeyError:
        return HttpResponse("Bad request. KeyError cloze_test_id", status=400)
    try:
        update_cloze_test(user=get_user(request),
                          ct_id=cloze_test_id,
                          ct_name=from_req(request, 'cloze_name',
                                           default=None),
                          ct_test=from_req(request, 'cloze_test',
                                           default=None),
                          ct_count=from_req(request,
                                            'cloze_count',
                                            default=None),
                          active=from_req(request, 'active', default=None),
                          language=from_req(request, 'language', default=None))
    except ForbiddenError as fe:
        return HttpResponseForbidden(str(fe))
    except KeyError as e:
        return HttpResponse("Bad request. KeyError. e", status=400)
    except Exception as e:
        return HttpResponse("Unknown error: {}".format(e), status=404)

    next = request.GET.get('next', None)
    if next:
        return HttpResponseRedirect(next)
    return JsonResponse({'Error': ''})