2017-08-31 16:37:58 +00:00
|
|
|
from flask import Flask, Blueprint, request
|
|
|
|
|
from flask_security import (SQLAlchemyUserDatastore, login_required,
|
|
|
|
|
current_user, Security)
|
2017-09-01 04:23:40 +00:00
|
|
|
from flask_security.utils import (verify_and_update_password, login_user,
|
|
|
|
|
logout_user)
|
2017-08-31 14:14:54 +00:00
|
|
|
from flask_restless import APIManager, ProcessingException
|
2017-08-31 16:37:58 +00:00
|
|
|
from models import (db, User, Role, Gradeclass, Student, AttendanceUpdate,
|
2017-09-01 04:23:40 +00:00
|
|
|
Presence, presense_map)
|
2017-08-31 14:14:54 +00:00
|
|
|
from sqlalchemy import func
|
2017-08-31 08:44:47 +00:00
|
|
|
import json
|
2017-08-31 14:14:54 +00:00
|
|
|
from datetime import datetime, date
|
|
|
|
|
from dateutil import parser
|
2017-08-31 08:44:47 +00:00
|
|
|
|
|
|
|
|
app = Flask(__name__)
|
|
|
|
|
app.config['DEBUG'] = True
|
2017-08-31 14:14:54 +00:00
|
|
|
app.config['PORT'] = 5001
|
2017-09-01 04:23:40 +00:00
|
|
|
app.config['SECRET_KEY'] = '3kljk1232kl1j32kmk13nbciw'
|
2017-08-31 08:44:47 +00:00
|
|
|
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/db.sqlite'
|
|
|
|
|
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
|
|
|
|
|
app.config['SECURITY_PASSWORD_SALT'] = 'uaisfyasiduyaisiuf'
|
2017-09-01 04:23:40 +00:00
|
|
|
app.config['SECURITY_UNAUTHORIZED_VIEW'] = None
|
2017-08-31 08:44:47 +00:00
|
|
|
|
2017-08-31 14:14:54 +00:00
|
|
|
db.init_app(app)
|
2017-08-31 08:44:47 +00:00
|
|
|
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
|
|
|
|
|
security = Security(app, user_datastore)
|
|
|
|
|
|
2017-08-31 14:14:54 +00:00
|
|
|
|
2017-08-31 08:44:47 +00:00
|
|
|
def auth_func(*args, **kwargs):
|
2017-09-01 04:58:56 +00:00
|
|
|
if not current_user.is_authenticated:
|
|
|
|
|
raise ProcessingException(description='Not authenticated', code=401)
|
2017-08-31 08:44:47 +00:00
|
|
|
return True
|
|
|
|
|
|
2017-08-31 14:14:54 +00:00
|
|
|
|
|
|
|
|
verify_logged_id = dict(GET_SINGLE=[auth_func], GET_MANY=[auth_func])
|
2017-08-31 08:44:47 +00:00
|
|
|
|
|
|
|
|
manager = APIManager(app, flask_sqlalchemy_db=db)
|
2017-08-31 16:37:58 +00:00
|
|
|
manager.create_api(
|
|
|
|
|
Student,
|
|
|
|
|
methods=['GET', 'PUT'],
|
|
|
|
|
results_per_page=5,
|
|
|
|
|
preprocessors=verify_logged_id)
|
|
|
|
|
manager.create_api(
|
|
|
|
|
Gradeclass,
|
|
|
|
|
methods=['GET', 'PUT'],
|
|
|
|
|
results_per_page=5,
|
|
|
|
|
preprocessors=verify_logged_id)
|
2017-08-31 14:14:54 +00:00
|
|
|
|
2017-08-31 19:07:03 +00:00
|
|
|
json_cont = {'Content-Type': 'application/json'}
|
2017-09-01 04:23:40 +00:00
|
|
|
resp = lambda val, code: (json.dumps({'status': val}), code, json_cont)
|
|
|
|
|
resp_res = lambda val, code: (json.dumps({'results': val}), code, json_cont)
|
|
|
|
|
|
2017-08-31 19:07:03 +00:00
|
|
|
|
2017-08-31 08:44:47 +00:00
|
|
|
@app.before_first_request
|
2017-08-31 14:14:54 +00:00
|
|
|
def create_test_data():
|
2017-08-31 08:44:47 +00:00
|
|
|
try:
|
|
|
|
|
db.drop_all()
|
|
|
|
|
db.create_all()
|
2017-08-31 16:37:58 +00:00
|
|
|
for i in range(3):
|
2017-08-31 14:14:54 +00:00
|
|
|
g_cls = Gradeclass("Class {}".format(i))
|
|
|
|
|
db.session.add(g_cls)
|
2017-08-31 19:07:03 +00:00
|
|
|
db.session.commit()
|
2017-08-31 16:37:58 +00:00
|
|
|
for s in range(5):
|
2017-09-01 04:23:40 +00:00
|
|
|
stu = Student("TestStudent#{}-Class{}".format(s + 1, g_cls.id),
|
|
|
|
|
g_cls.id)
|
2017-08-31 14:14:54 +00:00
|
|
|
db.session.add(stu)
|
|
|
|
|
user_datastore.create_user(
|
|
|
|
|
email='user@example.com', password='password')
|
2017-08-31 08:44:47 +00:00
|
|
|
db.session.commit()
|
|
|
|
|
except:
|
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
2017-08-31 14:14:54 +00:00
|
|
|
def parse_time(time_str):
|
|
|
|
|
utc_now = (time_str and time_str == 'now') or not time_str
|
|
|
|
|
time = datetime.utcnow() if utc_now else None
|
|
|
|
|
try:
|
2017-09-01 04:45:22 +00:00
|
|
|
time = parser.parse(time_str)
|
2017-08-31 14:14:54 +00:00
|
|
|
except:
|
|
|
|
|
pass
|
|
|
|
|
return time
|
|
|
|
|
|
2017-08-31 16:37:58 +00:00
|
|
|
|
2017-09-01 04:23:40 +00:00
|
|
|
def compute_attendance(request_type, object_id, start_time, end_time):
|
|
|
|
|
def get_records(req_type, obj_id):
|
|
|
|
|
return AttendanceUpdate.query.filter(
|
|
|
|
|
AttendanceUpdate.update_type == req_type).filter(
|
|
|
|
|
AttendanceUpdate.value_identifier == obj_id).filter(
|
|
|
|
|
func.date(AttendanceUpdate.time) >=
|
|
|
|
|
start_time.date()).filter(
|
2017-09-01 04:45:22 +00:00
|
|
|
func.date(AttendanceUpdate.time) <=
|
2017-09-01 04:23:40 +00:00
|
|
|
end_time.date()).all()
|
|
|
|
|
|
|
|
|
|
def student_records(stud_id):
|
|
|
|
|
stud_recs = get_records('student', stud_id)
|
|
|
|
|
stud = Student.query.get(stud_id)
|
|
|
|
|
gcls_recs = get_records('class', stud.gradeclass_id)
|
|
|
|
|
pres_rec = stud_recs
|
|
|
|
|
for gr in gcls_recs:
|
|
|
|
|
# if any grade record overlaps with student record -> ignore
|
2017-09-01 04:45:22 +00:00
|
|
|
if not any(
|
|
|
|
|
map(lambda x: gr.time.date() == x.time.date(), stud_recs)):
|
2017-09-01 04:23:40 +00:00
|
|
|
pres_rec.append(gr)
|
|
|
|
|
recs = []
|
2017-09-01 04:45:22 +00:00
|
|
|
# sort student records by time
|
|
|
|
|
for r in sorted(pres_rec, key=lambda x: x.time):
|
2017-09-01 04:23:40 +00:00
|
|
|
recs.append({
|
|
|
|
|
"presence": presense_map[r.presence].lower(),
|
|
|
|
|
"student": stud.student_name,
|
|
|
|
|
"time": r.time.isoformat()
|
|
|
|
|
})
|
|
|
|
|
return recs
|
|
|
|
|
|
|
|
|
|
result = []
|
2017-08-31 19:07:03 +00:00
|
|
|
if request_type == 'student':
|
2017-09-01 04:23:40 +00:00
|
|
|
result.extend(student_records(object_id))
|
2017-08-31 19:07:03 +00:00
|
|
|
if request_type == 'class':
|
2017-09-01 04:23:40 +00:00
|
|
|
gcls = Gradeclass.query.get(object_id)
|
2017-09-01 04:45:22 +00:00
|
|
|
# get result for each student
|
2017-09-01 04:23:40 +00:00
|
|
|
for stud in gcls.students:
|
|
|
|
|
result.extend(student_records(stud.id))
|
|
|
|
|
return result
|
|
|
|
|
|
2017-08-31 19:07:03 +00:00
|
|
|
|
2017-08-31 14:14:54 +00:00
|
|
|
def upsert_attendance(update_type, object_id, attend_time, pres_enum):
|
|
|
|
|
existing = AttendanceUpdate.query.filter(
|
2017-08-31 16:37:58 +00:00
|
|
|
AttendanceUpdate.update_type == update_type).filter(
|
|
|
|
|
AttendanceUpdate.value_identifier == object_id).filter(
|
|
|
|
|
func.date(
|
|
|
|
|
AttendanceUpdate.time) == attend_time.date()).first()
|
2017-08-31 14:14:54 +00:00
|
|
|
if existing:
|
|
|
|
|
existing.presence = pres_enum
|
|
|
|
|
else:
|
2017-08-31 16:37:58 +00:00
|
|
|
new_entry = AttendanceUpdate(update_type, object_id, attend_time,
|
|
|
|
|
pres_enum)
|
2017-08-31 14:14:54 +00:00
|
|
|
db.session.add(new_entry)
|
|
|
|
|
db.session.commit()
|
|
|
|
|
|
2017-08-31 16:37:58 +00:00
|
|
|
|
2017-08-31 14:14:54 +00:00
|
|
|
def validate_attend(update_type, object_id):
|
|
|
|
|
if update_type in ['class', 'student'] and object_id:
|
2017-08-31 16:37:58 +00:00
|
|
|
g_cls_found = update_type == 'class' and Gradeclass.query.get(
|
|
|
|
|
object_id)
|
|
|
|
|
stud_found = update_type == 'student' and Student.query.get(object_id)
|
2017-08-31 14:14:54 +00:00
|
|
|
return g_cls_found or stud_found
|
|
|
|
|
else:
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
|
2017-08-31 16:37:58 +00:00
|
|
|
def get_attendance(update_type, request):
|
|
|
|
|
object_id = request.args.get('identifier', None)
|
|
|
|
|
start_timestr = request.args.get('start_time', None)
|
|
|
|
|
end_timestr = request.args.get('end_time', None)
|
|
|
|
|
start_time, end_time = parse_time(start_timestr), parse_time(end_timestr)
|
2017-09-01 04:23:40 +00:00
|
|
|
ret_data = resp('invalid', 400)
|
2017-08-31 16:37:58 +00:00
|
|
|
if validate_attend(update_type, object_id) and start_time and end_time:
|
2017-09-01 04:23:40 +00:00
|
|
|
pres = compute_attendance(update_type, object_id, start_time, end_time)
|
|
|
|
|
ret_data = resp_res(pres, 200)
|
2017-08-31 16:37:58 +00:00
|
|
|
return ret_data
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def update_attendance(update_type, request):
|
2017-08-31 14:14:54 +00:00
|
|
|
object_id = request.form.get('identifier', None)
|
|
|
|
|
presence = request.form.get('presence', None)
|
|
|
|
|
attend_str = request.form.get('time', None)
|
|
|
|
|
attend_time = parse_time(attend_str)
|
2017-09-01 04:23:40 +00:00
|
|
|
ret_data = resp('invalid', 400)
|
2017-08-31 16:37:58 +00:00
|
|
|
if validate_attend(
|
2017-09-01 04:23:40 +00:00
|
|
|
update_type,
|
|
|
|
|
object_id) and presence and attend_time and presence.upper(
|
|
|
|
|
) in presense_map.values():
|
2017-08-31 14:14:54 +00:00
|
|
|
pres_enum = Presence[presence.upper()]
|
|
|
|
|
upsert_attendance(update_type, object_id, attend_time, pres_enum)
|
2017-09-01 04:23:40 +00:00
|
|
|
ret_data = resp('updated', 200)
|
2017-08-31 16:37:58 +00:00
|
|
|
return ret_data
|
|
|
|
|
|
2017-08-31 14:14:54 +00:00
|
|
|
|
2017-08-31 16:37:58 +00:00
|
|
|
@app.route('/api/attendance/<update_type>', methods=['GET', 'POST'])
|
|
|
|
|
@login_required
|
|
|
|
|
def attendance(update_type):
|
|
|
|
|
if request.method == 'GET':
|
|
|
|
|
return get_attendance(update_type, request)
|
|
|
|
|
elif request.method == 'POST':
|
|
|
|
|
return update_attendance(update_type, request)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@app.route('/api/login', methods=['POST'])
|
2017-08-31 14:14:54 +00:00
|
|
|
def login():
|
|
|
|
|
username = request.form.get('username', None)
|
|
|
|
|
password = request.form.get('password', None)
|
2017-08-31 16:37:58 +00:00
|
|
|
ret_data = (json.dumps({'status': 'failed'}), 401, json_cont)
|
2017-08-31 14:14:54 +00:00
|
|
|
if username and password:
|
|
|
|
|
user = User.query.filter(User.email == username).first()
|
|
|
|
|
if not user:
|
2017-09-01 04:23:40 +00:00
|
|
|
ret_data = resp('notfound', 401)
|
2017-08-31 16:37:58 +00:00
|
|
|
elif verify_and_update_password(password, user):
|
2017-08-31 14:14:54 +00:00
|
|
|
login_user(user)
|
2017-09-01 04:23:40 +00:00
|
|
|
ret_data = resp('success', 200)
|
2017-08-31 14:14:54 +00:00
|
|
|
return ret_data
|
2017-08-31 08:44:47 +00:00
|
|
|
|
2017-08-31 16:37:58 +00:00
|
|
|
|
2017-09-01 04:23:40 +00:00
|
|
|
@app.route('/api/logout', methods=['GET'])
|
|
|
|
|
def logout():
|
|
|
|
|
logout_user()
|
|
|
|
|
return resp('success', 200)
|
|
|
|
|
|
|
|
|
|
|
2017-08-31 08:44:47 +00:00
|
|
|
@app.route('/')
|
|
|
|
|
def home():
|
2017-09-01 04:58:56 +00:00
|
|
|
return 'welcome'
|
2017-08-31 08:44:47 +00:00
|
|
|
|
2017-08-31 14:14:54 +00:00
|
|
|
|
2017-08-31 08:44:47 +00:00
|
|
|
if __name__ == '__main__':
|
|
|
|
|
app.run()
|