Source

audrid / audrid / views / v2api / audits.py

# coding: utf-8

from audrid import (app, db)
from audrid import validators as V
from audrid.models import (User, Exam, Audit)
from audrid.utils import (random_id, authorization_required)
from flask import (jsonify, request, redirect, url_for)
from functools import wraps
import datetime
import json

#
# GET /audits
# GET /audits/<id>
#
@app.route('/api/v2/audits', methods=['GET'])
@authorization_required
def audits_get_all(user=None):
    """ Return all audits. """
    return jsonify(audits=[ a.as_dict() for a in Audit.query.all() ])

@app.route('/api/v2/audits/<id>', methods=['GET'])
@authorization_required
def audits_get(id, user=None):
    """ Return all audits. """
    audit = Audit.query.filter_by(id=id).first_or_404()
    return jsonify(audit.as_dict())

#
# POST /audits
#
@app.route('/api/v2/audits', methods=['POST'])
@authorization_required
def audits_post(user=None):
    """ Create an audit. This will create a trial document as well. """
    try:
        __audit = V.audit(json.loads(request.data))
    except Exception as exc:
        return jsonify(message='error during validation: %s' % exc), 400

    _ = User.query.filter_by(id=__audit['user_id']).first_or_404()
    _ = Exam.query.filter_by(id=__audit['exam_id']).first_or_404()

    try:
        audit = Audit(**__audit)
        db.session.add(audit)
        db.session.commit()        
    except Exception as exc:
        db.session.rollback()
        return jsonify(message='storage error: %s' % exc), 400
    return jsonify(audit.as_dict())

#
# PUT /audits/<id>
#
@app.route('/api/v2/audits/<id>', methods=['PUT'])
@authorization_required
def audits_put(id, user=None):
    """ Update audit. """
    audit = Audit.query.filter_by(id=id).first_or_404()
    current_status = audit.status
    
    try:
        __audit = V.audit(json.loads(request.data))
    except Exception as exc:
        return jsonify(message='error during validation: %s' % exc), 400

    STATUS_TRANSITIONS = {
        'registered' : ['started', 'registered'],
        'started' : ['finished', 'started'],
        'finished' : ['corrected', 'finished'],
        'corrected' : ['corrected', 'corrected'],
    }

    if ('status' in __audit) and (
        not __audit['status'] in STATUS_TRANSITIONS[current_status]):
        return jsonify(message='invalid status transistion: %s => %s' % (current_status, __audit['status'])), 400

    if not __audit['exam_id'] == audit.exam_id:
        return jsonify(message='exam_id is fixed'), 400        

    if not __audit['user_id'] == audit.user_id:
        return jsonify(message='user_id is fixed'), 400        

    try:
        audit.status = __audit.get('status', audit.status)
        db.session.add(audit)
        db.session.commit()        
    except Exception as exc:
        db.session.rollback()
        return jsonify(message='storage error: %s' % exc), 400
    return jsonify(audit.as_dict())


#
# DELETE /audits/<id>
#