def get_latest_data(): ''' 1. Take input as token and device id. 2. Query InfluxDB for latest entry. 3. return this data in json format. ''' data = request.json print(data) if (validate_token(data)): try: from server import SQLSession session = SQLSession() d = session.query(Device).filter_by(id=data['id']).first() session.close() if not d: return jsonify({"message": "No such device"}), 400 if d.monitoring == False: return jsonify({"message": "Monitoring not allowed"}), 404 from influxdb import InfluxDBClient dbname = "ihome" host = "influx" port = 8086 influx_client = InfluxDBClient(host=host, port=port) influx_client.switch_database(dbname) q = 'SELECT LAST(value) FROM {}'.format(d.measurement) a = influx_client.query(q) print(list(a.get_points(measurement=d.measurement))) return jsonify( {"data": list(a.get_points(measurement=d.measurement))}), 200 except Exception as e: return jsonify({"message": str(e)}), 500 else: return jsonify({"message": "Unauthorize"}), 300
def get_all_users(): if request.method == 'POST': data = request.json if validate_token(data): from server import SQLSession session = SQLSession() users_ = session.query(User).all() users_ = [{ "name": i.username, "email": i.email, } for i in users_] if len(users_) == 0: response_object = { 'status': 'success', 'message': 'No user yet' } else: response_object = { 'status': 'success', 'message': 'giving all users. use it wisely', 'payload': users_ } return jsonify(response_object), 200 else: response_object = {'status': 'fail', 'message': 'not a admin'} return jsonify(response_object), 300 else: response_object = {'status': 'fail', 'message': 'method not allowed'} return jsonify(response_object), 400
def addadmin(name, email, password): "Seed Admin data for testing" from server import SQLSession from senateBack.models.userModel import User import datetime import uuid session = SQLSession() admin = User( email=email, public_id=str(uuid.uuid4()), username=name, password=password, registered_on=datetime.datetime.utcnow(), last_updated_on=datetime.datetime.utcnow(), admin=True, varified=True, maintainer=True ) try: session.add(admin) session.commit() session.close() api_key = jwt.encode({'email': admin.email, 'exp':datetime.datetime.utcnow() + datetime.timedelta(days=400)}, os.environ.get('SECRET_KEY')).decode('UTF-8') print("API_KEY: ", api_key) except Exception as e: print("err in creating admin") print(str(e))
def getDocs(): from senateBack.models.documentModel import Document from server import SQLSession session = SQLSession() try: all_docs = session.query(Document).all() session.close() all_titles = [i.type_of_doc for i in all_docs] payload = [{"name": i, "data": []} for i in set(all_titles)] for obj in all_docs: for i in payload: if obj.type_of_doc == i["name"]: i["data"].append({ "title": obj.title, "link": "data:application/pdf;base64," + str(b64encode(i.doc))[2:-1], "date": obj.created_on.strftime("%d %m %Y") }) # print(payload) response = {"status": "success", "message": "docs", "payload": payload} return jsonify(response), 200 except Exception as e: session.close() response = { "status": "fail", "message": str(e), } return jsonify(response), 502
def get_all_news(): from server import SQLSession session = SQLSession() all_news = session.query(News).all() session.close() if (len(all_news) == 0): response = {"status": "fail", "message": "No news yet", "payload": []} return jsonify(response), 201 else: pay = [{ "title": i.title, "content": [j.rstrip() for j in i.content.split("\n")], "isFile": i.isFile, "file_link": "data:application/pdf;base64," + str(b64encode(i.supported_doc))[2:-1] if i.isFile else "", "date": i.created_on.strftime("%d %m %Y"), } for i in all_news] response = { "status": "success", "message": "All news", "payload": pay[::-1] } return jsonify(response), 200
def getBody(): body_type = request.args.get('type', None, type=str) from senateBack.models.bodyModel import Body from server import SQLSession session = SQLSession() try: all_body = session.query(Body).filter_by(type_of_body=body_type).all() session.close() response = { "status": "success", "message": "body", "payload": [{ "title": i.title, "image": "data:image/jpg;base64, " + str(b64encode(i.image))[2:-1], "name": i.name, "Email": i.email, "Contact": i.contact } for i in all_body] } return jsonify(response), 200 except: response = { "status": "fail", "message": "internal err", } return jsonify(response), 502
def getSlider(): from senateBack.models.sliderModel import Slider from server import SQLSession session = SQLSession() try: all_slides = session.query(Slider).all() session.close() response = { "status": "success", "message": "sliders", "payload": [{ "image": "data:image/jpg;base64, " + str(b64encode(i.image))[2:-1], "title": i.title, "subtitle": i.subtitle } for i in all_slides] } return jsonify(response), 200 except Exception as e: session.close() response = { "status": "fail", "message": str(e), } return jsonify(response), 502
def get_token(data): from server import SQLSession session = SQLSession() user = session.query(User).filter_by(email=data['email']).first() session.close() if not user: responce_object = { 'Status': 'fail', 'message': 'no such user exist', } return responce_object, 400 else: if user.check_password(data.get('password')): if user.varified: responce_object = { 'status': 'success', 'message': 'Given the token. Use it wisely', 'token': jwt.encode({'email': user.email, 'exp':datetime.datetime.utcnow() + datetime.timedelta(days=90)}, os.environ.get('SECRET_KEY')).decode('UTF-8'), 'email': data['email'] } return responce_object, 200 else: responce_object = { 'status': 'fail', 'message': 'Not varified yet', } return responce_object, 400 else: responce_object = { 'status': 'fail', 'message': 'enter valid password/email' } return responce_object, 400
def get_tomorrows_list(): ''' return the list of students, who are enrolled for tomorrows meal. ''' try: auth = request.args.get('auth', None, type=str) print("auth = ", auth) except: response={ "status":"fail", "message":"No argument" } return jsonify(response), 400 valid_token, usr_ = validate_token({'token':auth}) if not valid_token or not usr_.role == 'maintainer': response_object = { 'status': 'fail', 'message': "Invalid maintainer", } return jsonify(response_object), 300 tomorrows_date = datetime.datetime.today() + datetime.timedelta(days=1) tomorrows_date = tomorrows_date.astimezone(timezone('Asia/Kolkata')) # tomorrows_date = datetime.datetime.today() + datetime.timedelta(days=1) # tomorrows_date = tomorrows_date.strftime("%d %m %Y") # tomorrows_date = datetime.datetime.strptime(tomorrows_date, "%d %m %Y") from server import SQLSession session = SQLSession() meals_ = session.query(Meal).filter_by(date=tomorrows_date.date()).all() res = [{ 'meal_id':i.id, 'date':i.date, 'type':i.type_of_meal, 'items':i.items, 'isVeg':i.veg, "number_of_users":len([j.id for j in i.attendees])} for i in meals_] #print(meals_) # uc = [i.id for i in meals_.attendees] session.close() response_object = { 'status': 'success', 'message': 'veg and non veg list', 'payload': res, # 'non_veg':nvc } return jsonify(response_object), 200
def setfixedmenu(): data = request.json from server import SQLSession session = SQLSession() m_ = session.query(FixedMenu).filter_by(day=data['day']).all() l = [(i.id, i.veg) for i in m_] if len(l) == 2: session.close() response_object = { 'status': 'fail', 'message': '{} menu already exist, apply for change'.format(data['day']), } return jsonify(response_object), 400 if len(l) > 0: if l[0][1] == data['veg']: if (data['veg'] == True): veg_ = "veg" else: veg_ = "non-veg" response_object = { 'status': 'fail', 'message': '{} menu already exist for {}, apply for change'.format( veg_, data['day']), } return jsonify(response_object), 400 new_men = FixedMenu(day=data['day'], breakfast=data['breakfast'], lunch=data['lunch'], dinner=data['dinner'], veg=data['veg']) try: session.add(new_men) session.commit() session.close() response_object = { 'status': 'success', 'message': 'saved the menu', } return jsonify(response_object), 200 except Exception as e: session.close() response_object = { 'status': 'fail', 'message': str(e), } return jsonify(response_object), 500
def devices(): ''' 1. take input as the token in url 2. return all devices and there information. Query the status of the device too. ''' try: auth = request.args.get('auth', None, type=str) print("auth = ", auth) except: response = {"status": "fail", "messahe": "No argument"} return jsonify(response), 400 if (validate_token({"token": auth})): from server import SQLSession session = SQLSession() devices = session.query(Device).all() session.close() res = [ { "id": device.id, # id of device, for further query "name": device.name, # name of the device # port of the pi, from which device is connected "port": device.port, "location": device.location, # location of device e.g. kitchen "desc": device.desc, # description of the device # status of the device, wether it is on or off "status": device.status, "monitoring": device.monitoring, # wheather device allow monitoring or not # if monitoring is on then which measurement it uses if not then null "measurement": device.measurement, "min_intensity": device.min_intensity, # min intensity of the device "max_intensity": device.max_intensity, # max intensity of the device "cur_intensity": device.cur_intensity # current intensity of the device } for device in devices ] response = { "status": "success", "message": "device information", "payload": res } return jsonify(response), 200 else: response = {"status": "fail", "message": "authorization fail"} return jsonify(response), 300
def last_month_meals(): try: auth = request.args.get('auth', None, type=str) print("auth = ", auth) except: response={ "status":"fail", "message":"No argument" } return jsonify(response), 400 valid_token, urs_ = validate_token({'token':auth}) if not valid_token: response={ "status":"fail", "message":"Not a valid token/user. please login again." } return jsonify(response), 300 from server import SQLSession session = SQLSession() m_ = session.query(User).filter_by(id = urs_.id).first() session.close() total_meals_till_date = [] todays_date = datetime.datetime.today() this_month_meal = [] for i in m_.meals: total_meals_till_date.append({ "date": i.date, "type_of_meal": i.type_of_meal }) if i.date.month == todays_date.month: this_month_meal.append({ "date": i.date, "type_of_meal": i.type_of_meal }) response={ "status":"success", "message":"Bills", "total_meals":total_meals_till_date, "month_meals":this_month_meal } return jsonify(response), 200
def games_by_platform(data): from server import SQLSession session = SQLSession() game = session.query(Games).filter_by(plateform=data['platform']).all() l = [] if not game: return l else: l = [] for g in game: l.append({ 'title': g.title, 'plateform': g.plateform, 'score': g.score, 'genre': g.genre, 'editors_choice': g.editor_choice }) return l
def addadmin(): "Seed Admin data for testing" from server import SQLSession from temp.models.userModel import User import datetime import uuid session = SQLSession() admin = User(email="*****@*****.**", public_id=str(uuid.uuid4()), username="******", password="******", registered_on=datetime.datetime.utcnow(), last_updated_on=datetime.datetime.utcnow(), admin=True, varified=True) session.add(admin) session.commit() session.close()
def save_new_user(data): from server import SQLSession session = SQLSession() print(data) user = session.query(User).filter_by(email=data['email']).first() if not user: new_user = User( public_id=str(uuid.uuid4()), email=data['email'], username=data['name'], veg=data['isVeg'], reg_id=data['reg_id'], sic_id=data['sic_id'], role=data['role'], password=data['password'], registered_on=datetime.datetime.utcnow(), last_updated_on=datetime.datetime.utcnow() ) try: session.add(new_user) session.commit() session.close() response_object = { 'status': 'Ok', 'message': 'User Created Successful', } return jsonify(response_object), 200 except Exception as e: session.close() response_object = { 'status': 'fail', 'message': 'Problem saving in db', 'error': str(e) } return jsonify(response_object), 500 else: session.close() response_object = { 'status': 'fail', 'message': 'User already exists. Please Log in. or try another email', } return jsonify(response_object), 400
def add_game(data): from server import SQLSession session = SQLSession() game = session.query(Games).filter_by(title=data['title']).first() if not game: new_game = Games(data['title'], data['plateform'], data['score'], data['genre'], data['editors_choice']) try: session.add(new_game) session.commit() print("OK") except: res = {'status': 'Fail', 'message': 'error in db'} print("NOT db") #return jsonify(res) finally: res = {'status': 'OK', 'message': 'successfully added'} #return jsonify(res) else: res = {'status': 'Fail', 'message': 'already_exist'}
def validate_token(data): ''' Return bollean true -> valid token.... false -> Invalid token.... takes dict as input having field "token" ''' token = data['token'] try: from server import SQLSession session = SQLSession() d = jwt.decode(token, os.environ.get('SECRET_KEY')) usr = d['email'] user_ = session.query(User).filter_by(email=usr).first() session.close() if not user_: return False, None else: return True, user_ except: return False, None
def add_daily_menu_from_fixed_menu(date): from server import SQLSession session = SQLSession() str_date = date date = datetime.datetime.strptime(date, "%d %m %Y") date = date.astimezone(timezone('Asia/Kolkata')) print(date) day = date.strftime("%A") print(day) todays_menu = session.query(FixedMenu).filter_by(day=day).all() try: for i in todays_menu: d = { 'breakfast': i.breakfast, 'lunch': i.lunch, 'dinner': i.dinner } for j in d: if d[j] == 'breakfast': t = '7:30 AM - 9:30 AM' elif d[j] == 'lunch': t = '11:45 AM -2:00 PM' else: t = '8:30 PM - 9:30 PM' meal_ = Meal(date=date, type_of_meal=j, items=d[j], veg=i.veg, time_limit=t) session.add(meal_) session.commit() session.close() return True except Exception as e: session.close() print(str(e)) return False
def add_device(): from server import SQLSession session = SQLSession() data = request.json new_device = Device(name=data["name"], port=data["port"], alias=data["alias"], monitoring=data["monitoring"], measurement=data["measurement"], min_intensity=data["min_intensity"], max_intensity=data["max_intensity"], cur_intensity=data["cur_intensity"], location=data["location"], desc=data["desc"], created_on=datetime.datetime.utcnow(), updated_on=datetime.datetime.utcnow()) try: session.add(new_device) session.commit() session.close() return jsonify({"message": "success"}), 200 except Exception as e: return jsonify({"message": str(e)}), 500
def getFest(): fest = request.args.get('name', None, type=str) from senateBack.models.societiesModel import Societies from server import SQLSession session = SQLSession() try: all_slides = session.query(Societies).filter_by( society_name=fest).all() session.close() response = { "status": "success", "message": "fests", "payload": [{ "name": i.society_name, "contactname": i.contact_person_name, "phone": i.phone, "email": i.email, "image": "data:image/jpg;base64, " + str(b64encode(i.image))[2:-1], "content": [j.rstrip() for j in i.content.split("\n")] } for i in all_slides] } return jsonify(response), 200 except Exception as e: session.close() response = { "status": "fail", "message": str(e), } return jsonify(response), 502
def update(): data = request.json valid_token, usr_ = validate_token(data) from server import SQLSession session = SQLSession() if(valid_token): usr = session.query(User).filter_by(email=usr_.email).first() if data['isVeg'] is not None: usr.veg = data['isVeg'] if data['phone'] is not None: usr.phone = data['phone'] if data['name'] is not None: usr.username = data['name'] if data['password'] is not None: usr.password = data['password'] usr.last_updated_on = datetime.datetime.utcnow() try: session.commit() session.close() return jsonify({ "status": "success", "message": "updated detail", }), 200 except: session.close() return jsonify({ "status": "fail", "message": "cannot save changes" }), 400 else: session.close() response_object = { 'status': 'fail', 'message': 'Invalid token', } return jsonify(response_object), 400
def get_daily_fixed_menu(): from server import SQLSession session = SQLSession() try: menu_ = session.query(FixedMenu).all() session.close() res = [{ "day": i.day, "id": i.id, "breakfast": i.breakfast, "lunch": i.lunch, "dinner": i.dinner, "veg": i.veg } for i in menu_] veg_foods = [] non_veg_foods = [] for i in res: if i['veg']: veg_foods.append(i) else: non_veg_foods.append(i) response_object = { 'status': 'success', 'message': 'all meals data', 'veg_food': sorted(veg_foods, key=lambda i: i['id']), 'non_veg_food': sorted(non_veg_foods, key=lambda i: i['id']) } return jsonify(response_object), 200 except Exception as e: session.close() response_object = { 'status': 'fail', 'message': str(e), } return jsonify(response_object), 500
def avail_meal(): data = request.json valid_token, usr_ = validate_token(data) from server import SQLSession session = SQLSession() if(not valid_token): session.close() response_object = { 'status': 'fail', 'message': 'Invalid token', } return jsonify(response_object), 300 try: user_ = session.query(User).filter_by(id=usr_.id).first() list_of_meals_already_avail = [i.id for i in user_.meals] lits_of_types_of_meal = [i.type_of_meal for i in user_.meals] for m_id in data['meal_id']: if m_id in list_of_meals_already_avail: session.close() response_object = { 'status': 'fail', 'message': 'already enrolled', 'meals': list_of_meals_already_avail } return jsonify(response_object), 400 meal_ = session.query(Meal).filter_by(id=m_id).first() print(m_id) print(meal_) if not meal_: session.close() response_object = { 'status': 'fail', 'message': 'No such meal', } return jsonify(response_object), 400 if meal_.type_of_meal in lits_of_types_of_meal: session.close() response_object = { 'status': 'fail', 'message': 'already enrolled in {}'.format(meal_.type_of_meal), 'meals': lits_of_types_of_meal } return jsonify(response_object), 400 user_.meals.append(meal_) session.commit() session.close() response_object = { 'status': 'success', 'message': 'meal added' } return jsonify(response_object), 200 except Exception as e: session.close() response_object = { 'status': 'fail', 'message': str(e), } return jsonify(response_object), 500
from game.Models.GamesAction import add_seed_data from game.Models.GamesModel import Games from server import SQLSession sess = SQLSession() game = sess.query(Games).filter_by(plateform='PlayStation Vita').all() res_l = [] for g in game: res_l.append({ 'title': g.title, 'plateform': g.plateform, 'score': g.score, 'genre': g.genre, 'editors_choice': g.editor_choice }) print(res_l) sess.close() #print(g) #add_seed_data()
def get_tomorrows_menu(): try: auth = request.args.get('auth', None, type=str) print("auth = ", auth) except: response = {"status": "fail", "message": "No argument"} return jsonify(response), 400 valid_token, urs_ = validate_token({'token': auth}) if not valid_token: response = { "status": "fail", "message": "Not a valid token/user. please login again." } return jsonify(response), 400 tomorrows_date = datetime.datetime.today() + datetime.timedelta(days=1) tomorrows_date = tomorrows_date.astimezone(timezone('Asia/Kolkata')) # tomorrows_date = timezone('Asia/Kolkata').localize(tomorrows_date) from server import SQLSession session = SQLSession() # query_date = tomorrows_date.strftime('%d %m %Y') m_ = session.query(Meal).filter_by(date=tomorrows_date.date()).all() print("QUERY FROM MEAL to see is present is complete") print(m_) if len(m_) == 0: # session.close() # print("does not exist. adding menu") tomorrows_date_str = tomorrows_date.strftime("%d %m %Y") status = add_daily_menu_from_fixed_menu(tomorrows_date_str) if not status: session.close() response_object = { 'status': 'fail', 'message': "error in saving the meal", } return jsonify(response_object), 400 else: print("Writing done") # query_date = datetime.datetime.strptime(tomorrows_date, "%d %m %Y") print(tomorrows_date) menu = session.query(Meal).filter_by(date=tomorrows_date.date()).all() day = tomorrows_date.strftime("%A") print(type(tomorrows_date)) print(day) general_meal = session.query(FixedMenu).filter_by(day=day).all() session.close() res = [{ 'meal_id': i.id, 'date': i.date, 'type': i.type_of_meal, 'items': i.items, 'isVeg': i.veg, 'time': i.time_limit, 'avail': urs_.id in [j.id for j in i.attendees] } for i in menu] veg_foods = [] non_veg_foods = [] for i in res: if i['isVeg']: veg_foods.append(i) else: non_veg_foods.append(i) general_meal_res = [[{ 'meal_id': i.id, 'day': i.day, 'veg': i.veg, 'time': 'breakfast', 'items': i.breakfast, }, { 'meal_id': i.id, 'day': i.day, 'veg': i.veg, 'time': 'lunch', 'items': i.lunch, }, { 'meal_id': i.id, 'day': i.day, 'veg': i.veg, 'time': 'dinner', 'items': i.dinner, }] for i in general_meal] general_veg_foods = [] general_non_veg_foods = [] for i in general_meal_res: for j in i: if j['veg']: general_veg_foods.append(j) else: general_non_veg_foods.append(j) response_object = { 'status': 'success', 'message': 'all meals data', 'veg_food': veg_foods, 'non_veg_food': non_veg_foods, 'general_non_veg_foods': general_non_veg_foods, 'general_veg_foods': general_veg_foods } return jsonify(response_object), 200