def set_punch_in(attendance, date, inTime, studentid=None): msg = ("student successfuly puched in", ) if inTime == "" and attendance: attendance.punch_in = None db.session.delete(attendance) msg = "attendance delete" else: isValid, dateOrError = parseDate(inTime, "%H:%M:%S") if not isValid: return ( jsonify( dict(status="fail", message="time is not valid {}".format(inTime))), 200, ) if attendance: attendance.punch_in = inTime else: attendance = Attendance( date=date, student_id=studentid, punch_in=inTime, punch_in_by_id=request.user.id, ) db.session.add(attendance) db.session.commit() return ( jsonify( dict(status="success", message=msg, attendance=attendance.serialize())), 200, )
def add(): data = request.json or request.data or request.form res_code = 200 res = dict(status="fail") name = data.get("name") branch_id = data.get("branch_id") for key in ("name", "branch_id"): val = data.get(key) if not val: res["statusText"] = errors.BLANK_VALUES_FOR_REQUIRED_FIELDS.text res["statusData"] = errors.BLANK_VALUES_FOR_REQUIRED_FIELDS.type( [key]) return jsonify(res), res_code exam = Exam.query.filter_by(branch_id=branch_id, name=name).first() if exam: res["statusText"] = errors.CUSTOM_ERROR.text res["statusData"] = errors.CUSTOM_ERROR.type( 'Exam with name "%s" already exists' % exam.name) return jsonify(res), res_code exam = Exam(name=name, branch_id=branch_id) db.session.add(exam) db.session.commit() res["status"] = "success" res["exam"] = exam.serialize() return jsonify(res), res_code
def edit_contact(id): payload = request.json try: new_data = Contact.query.filter_by(id=int(id)).first() new_data.tag_contact = [] city = City.query.filter_by(id=int(payload['city'])).first() new_data.name = payload['name'] new_data.contact_one = payload['contact_one'] new_data.contact_two = payload['contact_two'] new_data.address = payload['address'] new_data.email = payload['email'] if (len(payload['tags']) is not 0): for item in payload['tags']: data = Tag.query.filter_by(id=item['id']).first() new_data.tag_contact.append(data) db.session.commit() return jsonify({'success': "Data added"}) except Exception as e: # return Exception for duplicate data print(str(e)) return jsonify({'message': "Something unexpected happened"})
def add_city(): if request.method == 'POST': payload = request.json print(payload) if len(payload['name']) != 0: check_data = City.query.filter_by(name=payload['name'].lower().strip()) if check_data.first(): return jsonify({'message': 'Data - '+check_data.first().name+' already exists.'}) else: try: if 'state' not in payload.keys(): payload['state'] = "" if 'country' not in payload.keys(): payload['country'] = "" new_data = City( payload['name'].lower().strip() , payload['state'].lower().strip() , payload['country'].lower().strip()) db.session.add(new_data) db.session.commit() json_data = { 'id' : new_data.id , 'name' : new_data.name} return jsonify({'success': 'Data Added', 'data' : json_data}) except Exception as e: print(str(e)) db.session.rollback() db.session.close() return jsonify({'message': 'Something unexpected happened. Check logs', 'log': str(e)}) else: return jsonify({'message': 'Empty Data.'}) else: return jsonify({'message': 'Invalid HTTP method . Use POST instead.'})
def edit_city(): if request.method == 'POST': payload = request.json if payload['name'] is not None: check_data = City.query.filter_by( name=payload['name'].lower().strip()).first() if check_data and check_data.name != payload['name'].lower().strip(): return jsonify({'message': 'Data - '+check_data.name+' already exists.'}) else: try: new_data = City.query.filter_by( id=payload['id']).first() new_data.name = payload['name'].lower().strip() new_data.state = payload['state'].lower().strip() new_data.country = payload['country'].lower().strip() db.session.commit() return jsonify({'success': 'Data Updated'}) except Exception as e: print(str(e)) db.session.rollback() db.session.close() return jsonify({'message': 'Something unexpected happened. Check logs', 'log': str(e)}) else: return jsonify({'message': 'Empty Data.'}) else: return jsonify({'message': 'Invalid HTTP method . Use POST instead.'})
def add(): data = request.json or request.data or request.form res_code = 200 res = dict(status="fail") catName = data.get("name") subjects = data.get("subjects") branch_id = data.get("branch_id") for key in ("name", "branch_id"): val = data.get(key) if not val: res["statusText"] = errors.BLANK_VALUES_FOR_REQUIRED_FIELDS.text res["statusData"] = errors.BLANK_VALUES_FOR_REQUIRED_FIELDS.type( [key]) return jsonify(res), res_code cat = Category.query.filter_by(name=catName).first() if cat: res["error"] = "Category with this name already present" return jsonify(res), res_code cat = Category(name=catName, branch_id=branch_id) print(subjects, data) for subid in subjects: a = Association() sub = Subject.query.filter_by(id=int(subid)).first() print(a, sub) if a and sub: a.subject = sub cat.subjects.append(a) print(cat, cat.serialize()) db.session.add(cat) db.session.commit() res["status"] = "success" res["category"] = cat.serialize() return jsonify(res), res_code
def delete_tag(): if request.method == 'POST': payload = request.json check_data = Tag.query.filter_by(id=payload['id']) if check_data.first(): if len(check_data.first().tag_contact) is int(0): try: check_data.delete() db.session.commit() return jsonify({'success': 'Data deleted'}) except Exception as e: db.session.rollback() db.session.close() return jsonify({ 'message': 'Something unexpected happened. Check logs', 'log': str(e) }) else: return jsonify({ 'message': 'Cannot delete data. Being used by other master.' }) else: return jsonify({'message': 'Data does not exist.'}) else: return jsonify({'message': 'Invalid HTTP method . Use POST instead.'})
def update_business(user_id, business_id, _business): """ updates a business """ business = Business.query.filter_by(id=business_id).first() if not business: return jsonify({ "success": False, "message": "Business with id " + business_id + " not found" }), 404 if business.user_id != user_id: return jsonify({ "success": False, "message": "You can not perform that action" }), 401 business.name = _business["name"] business.category = _business["category"] business.location = _business["location"] db.session.commit() business_object = { 'id': business.id, 'name': business.name, 'category': business.category, 'location': business.location } return jsonify({ "success": True, "message": "Business updated successfully", "business": business_object }), 200
def set_punch_in(attendance, inTime, studentid=None): if attendance and attendance.punch_in: return jsonify(dict(status="fail", message="student already punched in")), 200 isValid, dateOrError = parseDate(inTime, "%H:%M:%S") if not isValid: return ( jsonify(dict(status="fail", message="time is not valid {}".format(inTime))), 200, ) attendance = Attendance( date=datetime.today().date(), student_id=studentid, punch_in=inTime, punch_in_by_id=request.user.id, ) db.session.add(attendance) db.session.commit() return ( jsonify( dict( status="success", message="student successfuly puched in", attendance=attendance.serialize(), ) ), 200, )
def get_all_post(): post = db.session.query(Posts).all() print post if post == []: return jsonify({'post': None}) else: return jsonify({'post': post})
def delete_business(business_id, user_id): """ deletes a business """ # get business business = Business.query.filter_by(id=business_id).first() if not business: return jsonify({ "success": False, "message": "Business with id " + business_id + " not found" }), 404 # check owner if business.user_id != user_id: return jsonify({ "success": False, "message": "You can not perform that action" }), 401 db.session.delete(business) db.session.commit() return jsonify({ "success": True, "message": "Business successfully deleted" }), 200
def set_punch_out(attendance, outTime): if not attendance or not attendance.punch_in: return ( jsonify(dict(status="fail", message="Cannot puch out before puch in")), 200, ) if attendance.punch_out: return jsonify(dict(status="fail", message="student already punched out")), 200 isValid, dateOrError = parseDate(outTime, "%H:%M:%S") if not isValid: return ( jsonify( dict(status="fail", message="time is not valid {}".format(outTime)) ), 200, ) attendance.punch_out = outTime attendance.punch_out_by_id = request.user.id db.session.add(attendance) db.session.commit() return ( jsonify( dict( status="success", message="student successfuly puched out", attendance=attendance.serialize(), ) ), 200, )
def borrow_book(book_id, user_id): """ Use this route to execute a borrow_a_book transaction :param book_id: target book's id :param user_id: target user's id :param event_id: google calendar :return: a JSON containing transaction's information """ borrowed_book = book_routes.Book.query.get(book_id) borrow_history = BorrowedBooks.query.filter(BorrowedBooks.book_id == book_id, BorrowedBooks.user_id == user_id, BorrowedBooks.return_status == None).first() if borrowed_book.quantity <= 0: return jsonify({"message": "Out of stock"}), 400 elif borrow_history is not None: return jsonify({"message": "Current user has already borrowed this book and has not returned it!"}), 400 else: borrow_date = datetime.now() due_date = days_to_return_book(borrow_date) borrow_status = "borrowed" return_status = None return_date = None event_id = None borrowed_book.quantity -= 1 # Create a new row borrow = BorrowedBooks(book_id, user_id, borrow_date, due_date, return_date, borrow_status, return_status, event_id) db.session.add(borrow) db.session.commit() return borrowed_book_schema.jsonify(borrow)
def update(catid): # cannot update subjects because user might remove the subject from category, # in such cases an existing test for that cat-sub would become invalid data = request.json or request.data or request.form res_code = 200 res = dict(status="fail") cat_name = data.get("name") subjects = data.get("subjects") if not cat_name: res["statusText"] = errors.BLANK_VALUES_FOR_REQUIRED_FIELDS.text res["statusData"] = errors.BLANK_VALUES_FOR_REQUIRED_FIELDS.type( ["name"]) return jsonify(res), res_code cat = Category.query.filter_by(id=catid).first() if not cat: res["statusText"] = errors.CUSTOM_ERROR.text res["statusData"] = errors.CUSTOM_ERROR.type("No such Category") return jsonify(res), res_code cat.name = cat_name already_added_subs = [a.subject for a in cat.subjects] for subid in subjects: a = Association() sub = Subject.query.filter_by(id=int(subid)).first() print(a, sub) if a and sub and sub not in already_added_subs: a.subject = sub cat.subjects.append(a) db.session.add(cat) db.session.commit() res["status"] = "success" res["category"] = cat.serialize() return jsonify(res), res_code
def addMedicalHistory(current_user): if current_user.rol != 3: return make_response('Forbidden: Access is denied', 403) doctor = Doctor.query\ .filter_by(id_user = current_user.id)\ .first() if not doctor: return jsonify({"message" : "Forbidde: Access denid, sign up incomplete"}) if doctor.password_changed == 0: return make_response('Forbidden: Change your password for get access', 403) data = request.json id_patient = data['id_patient'] id_doctor = doctor.id id_patientstatus = data['id_patientstatus'] id_medicalspecialty = doctor.id_medicalspecialty observation = data['observation'] if not data or not id_patientstatus or not observation: return make_response('Medical History information incomplete', 422) new_medicalhistory = MedicalHistory(id_patient, id_doctor, id_patientstatus, id_medicalspecialty, observation) db.session.add(new_medicalhistory) db.session.commit() return jsonify({"message" : "Medical History registered succesfully"}), 201
def set_attendance(studentid, what): res = dict(status="fail") res_code = 200 if what not in ["in", "out", "comment"]: res["message"] = "Invalid url" return jsonify(res), res_code faculty = Faculty.query.get(request.user.id) data = request.json or request.data or request.form if what in ("in", "out"): isValid, timeOrError = parseDate(data.get(what), "%H:%M:%S") if not isValid: res["message"] = "Invalid time format " return jsonify(res), res_code student = Student.query.get(studentid) if not student: res["message"] = "Invalid student id" return jsonify(res), res_code attendance = Attendance.query.filter_by( date=datetime.today().date(), student_id=student.id ).first() if what == "in": return set_punch_in(attendance, data.get("in"), studentid=studentid) elif what == "out": return set_punch_out(attendance, data.get("out")) elif what == "comment": return set_comment(attendance, data.get("comment"))
def add_job(): if request.method == 'POST': payload = request.json print(payload) if payload: try: if (len(payload['club']) is not 0): template = Template.query.filter_by( id=int(payload['template'])).first() new_data = Job() new_data.template.append(template) meta = {'type': payload['type']} new_data.meta = json.dumps(meta) for item in payload['club']: print(item) data = Club.query.filter_by(id=item['id']).first() new_data.club.append(data) db.session.add(new_data) db.session.commit() return jsonify({'success': 'Data Added'}) except Exception as e: print(str(e)) db.session.rollback() db.session.close() return jsonify({ 'message': 'Something unexpected happened. Check logs', 'log': str(e) }) else: return jsonify({'message': 'Empty Data.'}) else: return jsonify({'message': 'Invalid HTTP method . Use POST instead.'})
def update(subjectid): data = request.json or request.data or request.form res_code = 200 res = dict(status="fail") subject_name = data.get("name") subject_short_name = data.get("shortName") if not subject_name and not subject_short_name: res["statusText"] = errs.BLANK_VALUES_FOR_REQUIRED_FIELDS.text what_is_empty = [ n for n, v in [("name", subject_name), ("short_name", subject_short_name)] if not v ] res["statusData"] = errs.BLANK_VALUES_FOR_REQUIRED_FIELDS.type( what_is_empty) return jsonify(res), res_code subject = Subject.query.filter_by(id=subjectid).first() if not subject: res["statusText"] = errs.CUSTOM_ERROR.text res["statusData"] = errs.CUSTOM_ERROR.type("No such Subject") return jsonify(res), res_code if subject_name: subject.name = subject_name if subject_short_name: subject.short_name = subject_short_name db.session.add(subject) db.session.commit() res["status"] = "success" res["subject"] = subject.serialize() return jsonify(res), res_code
def get_data(crypto): if crypto == 'etc': lst = conv_for_server( minute_price_historical('ETH', 'BTC', 10, 1, ['Coinbase'])) return jsonify({"data": lst}) lst = conv_for_server( minute_price_historical('BTC', 'USD', 30, 1, ['Coinbase'])) return jsonify({"data": lst})
def run_job_sms(): payload = request.json job = Job.query.filter_by(id=int(payload['curr_id'])).first() try: task = tasks.messages(job.id) return jsonify({'success': 'Job started'}) except Exception as e: return jsonify({'message': 'Unable to run job. Check logs'})
def deleteBell(id): if request.method != 'DELETE': abort(400) code = bellsContent.delete_with_id(id) if code == StatusCode.ok: return jsonify({}) return jsonify(ErrorHelper.make_response_for_code(code))
def confirmSignup(current_user): auth = request.json confirm_code = current_user.uuid if confirm_code == auth['uuid']: current_user.account_verified = 1 db.session.commit() return jsonify({"message" : "Your account was verified succesfully"}), 200 else: return jsonify({"message" : "Confirm code wrong!"}), 422
def createLector(): json = {} if request.headers['Content-Type'] == 'application/json': json = request.get_json().copy() else: abort(400) lector, code = lectorsContent.create_from_json(json) if lector is None: return jsonify(ErrorHelper.make_response_for_code(code)) else: return jsonify(lector.serialized())
def get_by_test(testid): res = dict(status="fail") test = Test.query.get(testid) if not test: res["statusText"] = errs.CUSTOM_ERROR.text res["statusData"] = errs.CUSTOM_ERROR.type("No such Test") return jsonify(res), 200 marks = Marks.query.filter_by(test_id=test.id).all() marks = [mark.serialize() for mark in marks] res["marks"] = marks res["status"] = "success" return jsonify(res), 200
def state_service(): try: country = request.args.get('countryname') countyname = country.split("_")[0] statelist = [] for statename in State.objects(countryname=countyname): statelist.append(statename.state) states = sorted(statelist) return jsonify(statelist) except Exception as e: return jsonify('{"mesg":' + str(e) + '}')
def createLesson(group_id): json = {} if request.headers['Content-Type'] == 'application/json': json = request.get_json().copy() else: abort(400) json[Key.group_id] = group_id lesson, code = lessonsContent.create_from_json(json) if lesson is None: return jsonify(ErrorHelper.make_response_for_code(code)) else: return jsonify(lesson.serialized)
def get_borrow_history_of_a_user(user_id): """ Get borrow_a_book & return history of a user :param user_id: target user's id :return: A JSON with the list of borrow_a_book & return of the target user """ borrow = BorrowedBooks.query.filter(BorrowedBooks.user_id == user_id).all() if len(borrow) == 0: return jsonify([{"message": "Borrow history is empty!"}]) else: result = borrowed_books_schema.dump(borrow) return jsonify(result)
def city_post(): try: country = request.args.get('country') countyname = country.split("_")[0] state = request.args.get('state') citylist = [] for cityname in City.objects(countryname=countyname, state=state): citylist.append(cityname.city) cities = sorted(citylist) return jsonify(cities) except Exception as e: return jsonify('{"mesg":' + str(e) + '}')
def completeSignUp(current_user): if current_user.account_verified == 0: return make_response('Forbidden: First confirm your account', 403) auth = request.json patient = Patient.query\ .filter_by(id_user = current_user.id)\ .first() hospital = Hospital.query\ .filter_by(id_user = current_user.id)\ .first() if patient or hospital or current_user.rol == 3: return jsonify({"message" : "Sign up have been completed yet"}), 409 #PATIENT if current_user.rol == 1: name = auth['name'] address = auth['address'] birthdate = datetime.strptime(auth['birthdate'], '%d/%m/%y') id_user = current_user.id complete_signup = Patient(name, address, birthdate, id_user) if not name or not address or not birthdate: return make_response('Patient information incomplete', 422) else: db.session.add(complete_signup) db.session.commit() return jsonify({'message' : 'Sign Up Completed Successfully'}), 200 #HOSPITAL if current_user.rol == 2: name = auth['name'] address = auth['address'] id_medicalservice = auth['id_medicalservice'] id_user = current_user.id complete_signup = Hospital(name, address, id_medicalservice, id_user) if not name or not address or not id_medicalservice: return make_response('Hospital information incomplete', 422) else: db.session.add(complete_signup) db.session.commit() return jsonify({'message' : 'Sign Up Completed Successfully'}), 200
def createGroup(): if request.method != 'POST': abort(400) if request.headers['Content-Type'] != 'application/json': abort(400) json = request.get_json().copy() group, code = groupsContent.add_from_json(json) if code == StatusCode.ok: return jsonify(group.serialized()) return jsonify(ErrorHelper.make_response_for_code(code))
def delete_contact(id): try: new_data = Contact.query.filter_by(id=int(id)) if new_data.first(): new_data.delete() db.session.commit() return jsonify({'success': "Data Deleted"}) else: return jsonify({'message': "Data doesn't exists"}) except Exception as e: # return Exception for duplicate data print(str(e))
def search_book_by_query(query): """ Search books based on a query :param query: user entered query :return: """ books = Book.query.filter( Book.author.like("%{}%".format(query)) | Book.ISBN.like("%{}%".format(query)) | Book.title.like( "%{}%".format(query))).all() if len(books) == 0: return jsonify([{"message": "No matches!"}]) else: result = books_Schema.dump(books) return jsonify(result)
def get_all_undue_borrow_of_a_user(user_id): """ use this route to get all undue book of a user :param user_id: target user's id :return: A JSON containing all undue books of a user """ borrow = BorrowedBooks.query.filter(BorrowedBooks.user_id == user_id, BorrowedBooks.return_status == None).all() print(borrow) if len(borrow) == 0: return jsonify([{"message": "No undue books!"}]) else: result = borrowed_books_schema.dump(borrow) return jsonify(result)
def getMedicalHistoriesByDoctorID(current_user, id_doctor): if current_user.account_verified == 0: return make_response('Forbidden: First confirm your account', 403) if current_user.rol != 2: return make_response('Forbidden: Access is denied', 403) result = medical_histories.dump(MedicalHistory.query\ .filter_by(id_doctor = id_doctor) .all()) if result: return jsonify({"All medical histories" : result }) else: return jsonify({"message" : "Not medical histories found"})
def getLector(lectorId): lector = Lector.query.filter(Lector.id == lectorId).first() if lector is not None: return jsonify(lector.serialized()) else: abort(404)
def get_epicoders(): epicoders = models.Epicoder.query.all() directory = {} for e in epicoders: directory[e.id] = [e.firstName, e.lastName, e.github] return jsonify({"epicoders": directory })
def get_epicoder(epicoder_id): result = models.Epicoder.query.get(epicoder_id) epicoder = {"firstName": result.firstName, "lastName": result.lastName, "github": result.github} return jsonify({'epicoder': epicoder})
def createBell(): if request.method != 'POST': abort(400) if request.headers['Content-Type'] != 'application/json': abort(400) json = request.get_json().copy() bell, code = bellsContent.add_from_json(json) if code is not None and code != StatusCode.ok: return jsonify(ErrorHelper.make_response_for_code(code)) if bell is None: abort(400) return jsonify(bell.serialized())
def groups(groupId): group = groupsContent.get(groupId) if type(group) is not Group: return jsonify(ErrorHelper.make_response_for_code(group)) lessons = group.lessons return render_template( 'group.html', title='Group ' + group.title, group=group, lessons=lessons, reverseDays=dict((v, k) for k, v in days.iteritems()))
def createLesson(groupId): if request.method == 'GET': return render_create_lesson(groupId) if request.method == 'POST': json = {} if request.headers['Content-Type'] == 'application/json': json = request.get_json().copy() elif 'multipart/form-data' in request.headers['Content-Type']: json = request.form.copy() else: abort(400) json['group_id'] = groupId code = lessonsContent.create_from_json(json) return jsonify(ErrorHelper.make_response_for_code(code))
def get_tasks(): tasks = [ { 'id': 1, 'title': u'Buy groceries', 'description': u'Milk, Cheese, Pizza, Fruit, Tylenol', 'done': False }, { 'id': 2, 'title': u'Learn Python', 'description': u'Need to find a good Python tutorial on the web', 'done': False } ] return jsonify({'tasks': tasks})
def virtualissue_results(): #find most recent highlight result vi_results = db.virtualissues.find().sort("datetime", -1).limit(1) data = vi_results[0]["data"] return jsonify({"virtualissue_results": data})
def highlights_results(): #find most recent highlight result highlights_results = db.highlights.find().sort("datetime", -1).limit(1) data = highlights_results[0]["data"] return jsonify({"highlights_results": data})
def getLessons(group_id): lessons = map(Lesson.serialized, groupsContent.get(group_id).lessons) json = {'lessons': lessons} return jsonify(json)
def not_found(error): return make_response(jsonify({'error': 'Not found'}), 404)
def getLectors(): lectors = map(Lector.serialized, Lector.query.all()) json = {'lectors': lectors} return jsonify(json)
def get_notifications(): currentDate = (time.strftime("%H:%M:%S")) return jsonify(mongo.db.notifications.find({'sent': False}))
def not_found(error): return make_response(jsonify({'error': 'Bad request'}), 400)
def add_numbers(): """Eine Besipielmethode, die über json mit jquery interagiert...""" a = request.args.get('a', 0, type=int) b = request.args.get('b', 0, type=int) res = a + b return jsonify(ergebnis=res)
def getBells(): bells = map(Bell.serialized, Bell.query.all()) json = {'bells': bells} return jsonify(json)
def getGroups(): groups = map(Group.serialized, groupsContent.all()) json = {'groups': groups} return jsonify(json)
def deleteLesson(lesson_id): code = lessonsContent.delete(lesson_id) return jsonify({})