def serialize_machine(machine): machine_dict = to_dict(machine) machine_dict['problems'] = sorted( [to_dict(problem) for problem in machine.problems], key=lambda e: e['problem_id'], reverse=True) return machine_dict
def load(): for s in Fermenter.query.all(): app.cbp['FERMENTERS'][s.id] = to_dict(s) for s in FermenterStep.query.filter_by(state='A').all(): app.cbp['CURRENT_TASK'][s.fermenter_id] = to_dict(s) if s.state == 'A' and s.timer_start is not None: app.cbp['CURRENT_TASK'][s.fermenter_id]["endunix"] = int((s.timer_start - datetime.datetime(1970, 1, 1)).total_seconds()) app.logger.info("CURRENT_TASK") app.logger.info(app.cbp['CURRENT_TASK'])
def load(): for s in Fermenter.query.all(): app.cbp['FERMENTERS'][s.id] = to_dict(s) for s in FermenterStep.query.filter_by(state='A').all(): app.cbp['CURRENT_TASK'][s.fermenter_id] = to_dict(s) if s.state == 'A' and s.timer_start is not None: app.cbp['CURRENT_TASK'][s.fermenter_id]["endunix"] = int((s.timer_start - datetime.datetime(1970, 1, 1)).total_seconds()) app.logger.info("CURRENT_TASK") app.logger.info(app.cbp['CURRENT_TASK'])
def get_startup_info_route(): events = get_events() users = get_users() machines = get_machines(g.event_id) return jsonify({ 'data': { 'machines': [to_dict(machine) for machine in machines], 'events': [to_dict(event) for event in events], 'users': [to_dict(event) for user in users] }, 'status': 'success' })
def to_dict_simple(self): player_dict = to_dict(self) player_dict['pin'] = None player_dict['full_name'] = self.get_full_name() if self.roles: player_dict['roles'] = { role.role_id: role.to_dict_simple() for role in self.roles } if self.linked_division_id: #player_dict['linked_division']=self.linked_division.to_dict_simple() player_dict[ 'linked_division_name'] = self.linked_division.get_tournament_name( self.linked_division.tournament) if self.division_machine: player_dict['division_machine'] = { 'division_machine_id': self.division_machine.division_machine_id, 'division_machine_name': self.division_machine.machine.machine_name } if self.teams: player_dict['teams'] = [ team.to_dict_simple() for team in self.teams ] if len(self.teams) > 0 and self.teams[0].division_machine: player_dict['team_division_machine'] = { 'division_machine_id': self.teams[0].division_machine.division_machine_id, 'division_machine_name': self.teams[0].division_machine.machine.machine_name } if self.asshole_count: player_dict['jagoff_count'] = self.asshole_count return player_dict
def add_machine_route(): input_data = getRequestData(request) new_machine = add_machine(current_app, g.event_id, input_data) return jsonify({ 'data': to_dict(new_machine), 'status': 'fail' if new_machine is None else 'success' })
def initHardware(cleanup = True): app.brewapp_switch_state = {} app.brewapp_hardware_config = {} app.brewapp_thermometer_cfg = {} app.brewapp_hydrometer_cfg = {} hw = Hardware.query.all() for h in hw: h1 = to_dict(h) if(h1['config'] != None): h1['config'] = json.loads(h1['config']) if(h1["type"] == "T"): app.brewapp_thermometer_cfg[h1["id"]] = h1 elif (h1["type"] == "S"): pass else: app.brewapp_hardware_config[h1["id"]] = h1 app.brewapp_switch_state[h1["id"]] = False if(cleanup): app.brewapp_hardware.cleanup() app.brewapp_hardware.init() app.logger.info("## INIT HARDWARE") app.logger.info("Hardware: " + str(app.brewapp_hardware_config)) app.logger.info("Thermometer: " + str(app.brewapp_thermometer_cfg))
def to_dict_simple(self): queue = to_dict(self) queue['player'] = { 'player_id': self.player_id, 'player_name': "%s %s" % (self.player.first_name, self.player.last_name) } queue['division_machine'] = { 'division_machine_id': self.division_machine.division_machine_id, 'division_machine_name': self.division_machine.machine.machine_name } if len(self.division_machine.queue) > 0: for potential_queue_head in self.division_machine.queue: if potential_queue_head.parent_id is None: queue_node = potential_queue_head else: queue_node = None queue_position = 1 while queue_node and len( queue_node.queue_child) > 0 and queue_node != self: queue_position = queue_position + 1 queue_node = queue_node.queue_child[0] if queue_node is None: queue['queue_position'] = "This Should Not Happen" else: queue['queue_position'] = queue_position return queue
def save_record_state_to_history(result=None, **kwargs): """ Saves the current state of the record so that changes can be undone. :param result: :param kwargs: :return: """ # No need to store history array within the history table data data = copy.copy(result) if 'history' in data: del data['history'] if 'ratings' in data: del data['ratings'] history = RecordHistory(record_id=result['id'], user_id=result['user_id'], data=json.dumps(data)) db.session.add(history) db.session.commit() if 'history' not in result: result['history'] = [] result['history'].insert(0, to_dict(history))
def add_problem_route(): input_data = getRequestData(request) new_problem = add_problem(current_app, input_data) return jsonify({ 'data': to_dict(new_problem), 'status': 'fail' if new_problem is None else 'success' })
def nextStep(): active = Step.query.filter_by(state='A').first() inactive = Step.query.filter_by(state='I').order_by(Step.order).first() if(inactive == None): socketio.emit('message', {"headline": "BREWING_FINISHED", "message": "BREWING_FINISHED_MESSAGE"}, namespace ='/brew') if(active != None): active.state = 'D' active.end = datetime.utcnow() setTargetTemp(active.kettleid, 0) db.session.add(active) db.session.commit() app.brewapp_current_step = None if(inactive != None): inactive.state = 'A' inactive.start = datetime.utcnow() setTargetTemp(inactive.kettleid, inactive.temp) db.session.add(inactive) db.session.commit() app.brewapp_current_step = to_dict(inactive) if(inactive.timer_start != None): app.brewapp_current_step["endunix"] = int((inactive.timer_start - datetime(1970,1,1)).total_seconds())*1000 nextStepBeep() socketio.emit('step_update', getSteps(), namespace ='/brew')
def nextStep(): active = Step.query.filter_by(state='A').first() inactive = Step.query.filter_by(state='I').order_by(Step.order).first() if (inactive == None): socketio.emit('message', { "headline": "BREWING_FINISHED", "message": "BREWING_FINISHED_MESSAGE" }, namespace='/brew') if (active != None): active.state = 'D' active.end = datetime.utcnow() setTargetTemp(active.kettleid, 0) db.session.add(active) db.session.commit() app.brewapp_current_step = None if (inactive != None): inactive.state = 'A' inactive.start = datetime.utcnow() setTargetTemp(inactive.kettleid, inactive.temp) db.session.add(inactive) db.session.commit() app.brewapp_current_step = to_dict(inactive) if (inactive.timer_start != None): app.brewapp_current_step["endunix"] = int( (inactive.timer_start - datetime(1970, 1, 1)).total_seconds()) * 1000 nextStepBeep() socketio.emit('step_update', getSteps(), namespace='/brew')
def initHardware(cleanup=True): app.brewapp_switch_state = {} app.brewapp_hardware_config = {} app.brewapp_thermometer_cfg = {} app.brewapp_hydrometer_cfg = {} hw = Hardware.query.all() for h in hw: h1 = to_dict(h) if (h1['config'] != None): h1['config'] = json.loads(h1['config']) if (h1["type"] == "T"): app.brewapp_thermometer_cfg[h1["id"]] = h1 elif (h1["type"] == "S"): pass else: app.brewapp_hardware_config[h1["id"]] = h1 app.brewapp_switch_state[h1["id"]] = False if (cleanup): app.brewapp_hardware.cleanup() app.brewapp_hardware.init() app.logger.info("## INIT HARDWARE") app.logger.info("Hardware: " + str(app.brewapp_hardware_config)) app.logger.info("Thermometer: " + str(app.brewapp_thermometer_cfg))
def next(id): active = FermenterStep.query.filter_by(fermenter_id=int(id), state='A').first() inactive = FermenterStep.query.filter_by( fermenter_id=int(id), state='I').order_by(FermenterStep.order).first() if active is not None: active.state = "D" active.end = datetime.datetime.utcnow() if inactive is not None: setTargetTemp(int(id), inactive.temp) inactive.start = datetime.datetime.utcnow() inactive.state = "A" app.cbp['CURRENT_TASK'][int(id)] = to_dict(inactive) temp = app.brewapp_thermometer_last[app.cbp['FERMENTERS'][int(id)] ["sensorid"]] if temp >= inactive.temp: app.cbp['CURRENT_TASK'][int(id)]["direction"] = "C" else: app.cbp['CURRENT_TASK'][int(id)]["direction"] = "H" else: app.cbp['CURRENT_TASK'].pop(int(id), None) db.session.commit() reload_fermenter(int(id)) return ('', 204)
def user_dict(user): """Turn a User object into a dictionary suitable for serialization""" data = to_dict(user) del data['password_crypt'] if Admin_permission.can() or user.user_id == current_user.user_id: data['roles'] = [r.name for r in user.roles] return data
def to_dict_simple(self): metadivision = to_dict(self) if self.divisions: metadivision['divisions'] = {} for division in self.divisions: metadivision['divisions'][ division.division_id] = division.to_dict_simple() return metadivision
def to_dict_simple(self): export_dict = to_dict(self) if self.player: export_dict['player'] = self.player.to_dict_simple() if self.team: export_dict['player'] = self.team.to_dict_simple() export_dict['player']['full_name'] = self.team.team_name return export_dict
def to_dict_simple(self): export_dict = to_dict(self) if len(self.finals_match_game_player_results) > 0: export_dict['finals_match_game_player_results'] = [] for result in self.finals_match_game_player_results: export_dict['finals_match_game_player_results'].append( result.to_dict_simple()) return export_dict
def image_view(): """ This view allows users to upload photos of locations from their mobile device. """ # get the accompanying data data = request.form for field in ['location_id', 'lat', 'lon', 'date_acquired']: if field not in data: print "missing %s" % field raise BadRequest(description='Image requires %s.' % field) if 'file' in request.files and request.files['file'] is not None: # get the file from the request object f = request.files['file'] # sanitize the file name filename = secure_filename(f.filename) # check that file type is allowed NAIVE check if not allowed_file(filename): print "bad file type" raise BadRequest('Bad File Type') # get file for processing and uploading f_io = cStringIO.StringIO() f.save(dst=f_io) # create key for file url = 'images/mobile/' + str(uuid.uuid4()) + '.jpg' # upload image to s3 bucket upload_image(f_io, encoded_image=False, filename=url) elif 'url' in data: url = data['url'] else: raise BadRequest(description='Not enough data') # save to database image = Image(location_id=data['location_id'], lat=data['lat'], lon=data['lon'], url=url, date_acquired=data['date_acquired']) # get the user from the token if not is_anonymous(): image.user_id = current_user.id if 'source' in data: image.source = data['source'] db.session.add(image) db.session.commit() return jsonify(to_dict(image)), 201
def getAsDict(obj, key, deep=None, order=None): if order is not None: result = obj.query.order_by(order).all() else: result = obj.query.all() ar = {} for t in result: ar[getattr(t, key)] = to_dict(t, deep=deep) return ar
def init(): ## REST API FOR STEP manager.create_api(Step, methods=['GET', 'POST', 'DELETE', 'PUT'],allow_patch_many=True, results_per_page=None, postprocessors= {'GET_MANY': [post_get]}) s = Step.query.filter_by(state='A').first() if(s != None): app.brewapp_current_step = to_dict(s) if(s.timer_start != None): app.brewapp_current_step["endunix"] = int((s.timer_start - datetime(1970,1,1)).total_seconds())*1000
def to_dict_simple(self): export_dict = to_dict(self) if self.final_player: export_dict['final_player']=self.final_player.to_dict_simple() # if len(self.qualifiers) > 0: # division_final_dict = [] # for qualifier in self.qualifiers: # division_final_dict.append(qualifier.to_dict_simple()) return export_dict
def getAsArray(obj, order=None): if order is not None: result = obj.query.order_by(order).all() else: result = obj.query.all() ar = [] for t in result: ar.append(to_dict(t)) return ar
def create_tournament(): """Create a new tournament""" tournament_data = json.loads(request.data) new_tournament = Tournament( name = tournament_data['name'] ) DB.session.add(new_tournament) DB.session.commit() return jsonify(to_dict(new_tournament))
def export_book(): r = RecipeBooks.query.all() ar = [] for t in r: ar.append(to_dict(t, deep={'steps': []})) return Response(json.dumps(ar), mimetype='application/json', headers={'Content-Disposition':'attachment;filename=CraftBeerPI_RecipeBook.json'})
def add_division(tournament): """Create a new division""" division_data = json.loads(request.data) new_division = Division( name = division_data['name'] ) tournament.divisions.append(new_division) DB.session.add(new_division) DB.session.commit() return jsonify(to_dict(new_division))
def to_dict_simple(self): division_final_round_dict = to_dict(self) if len(self.division_final_matches) > 0: division_final_round_dict['division_final_matches'] = [] for match in self.division_final_matches: division_final_round_dict['division_final_matches'].append(match.to_dict_simple()) sorted_list = sorted(division_final_round_dict['division_final_matches'], key= lambda e: e['division_final_match_id']) division_final_round_dict['division_final_matches']=sorted_list return division_final_round_dict
def to_dict_fast(self): player_dict = to_dict(self) player_dict['pin'] = None player_dict['full_name'] = self.get_full_name() if self.teams and len(self.teams) > 0: player_dict['team_id'] = self.teams[0].team_id player_dict['team_name'] = self.teams[0].team_name # if self.division_machine: # player_dict['on_division_machine']=True return player_dict
def resetCurrentSteps(): resetBeep() active = Step.query.filter_by(state='A').first() active.start = datetime.utcnow() active.end = None active.timer_start = None setTargetTemp(active.kettleid, active.temp) app.brewapp_current_step = to_dict(active) db.session.add(active) db.session.commit() socketio.emit('step_update', getSteps(), namespace ='/brew')
def start_timer_of_current_step(): resetBeep() active = Step.query.filter_by(state='A').first() active.timer_start = datetime.utcnow() setTargetTemp(active.kettleid, active.temp) app.brewapp_current_step = to_dict(active) app.brewapp_current_step["endunix"] = int((active.timer_start - datetime(1970, 1, 1)).total_seconds()) * 1000 db.session.add(active) db.session.commit() socketio.emit('step_update', getSteps(), namespace ='/brew')
def resetCurrentSteps(): resetBeep() active = Step.query.filter_by(state='A').first() active.start = datetime.utcnow() active.end = None active.timer_start = None setTargetTemp(active.kettleid, active.temp) app.brewapp_current_step = to_dict(active) db.session.add(active) db.session.commit() socketio.emit('step_update', getSteps(), namespace='/brew')
def to_dict_simple(self): tournament = to_dict(self) if self.single_division: if self.divisions[0].active: tournament['active'] = True else: tournament['active'] = False tournament['divisions'] = [ division.division_id for division in self.divisions ] return tournament
def export_book(): r = RecipeBooks.query.all() ar = [] for t in r: ar.append(to_dict(t, deep={'steps': []})) return Response(json.dumps(ar), mimetype='application/json', headers={ 'Content-Disposition': 'attachment;filename=CraftBeerPI_RecipeBook.json' })
def to_dict_simple(self): division_final_dict = to_dict(self) # if len(self.qualifiers) > 0: # division_final_dict['qualifiers'] = [] # for qualifier in self.qualifiers: # division_final_dict['qualifiers'].append(qualifier.to_dict_simple()) if len(self.division_final_rounds) > 0: division_final_dict['division_final_rounds'] = [] for round in sorted(self.division_final_rounds, key= lambda e: e.round_number): division_final_dict['division_final_rounds'].append(round.to_dict_simple()) return division_final_dict
def start_timer_of_current_step(): resetBeep() active = Step.query.filter_by(state='A').first() active.timer_start = datetime.utcnow() setTargetTemp(active.kettleid, active.temp) app.brewapp_current_step = to_dict(active) app.brewapp_current_step["endunix"] = int( (active.timer_start - datetime(1970, 1, 1)).total_seconds()) * 1000 db.session.add(active) db.session.commit() socketio.emit('step_update', getSteps(), namespace='/brew')
def stepjob(): ## Skip if no step is active if (app.brewapp_current_step == None): return ## current step cs = app.brewapp_current_step ## get current temp of target kettle try: id = int(app.brewapp_kettle_state[cs.get("kettleid")]["sensorid"]) ct = app.brewapp_thermometer_last[id] except: ct = 0 #print cs.get("timer") #print cs.get("timer_start") #print cs.get("temp") #print ct ## check if target temp reached and timer can be started if (cs.get("timer") is not None and cs.get("timer_start") == None and ct >= cs.get("temp")): s = Step.query.get(cs.get("id")) s.timer_start = datetime.utcnow() app.brewapp_current_step = to_dict(s) if (s.timer_start != None): app.brewapp_current_step["endunix"] = int( (s.timer_start - datetime(1970, 1, 1)).total_seconds()) * 1000 timerBeep() db.session.add(s) db.session.commit() socketio.emit('step_update', getSteps(), namespace='/brew', broadcast=True) ## if Automatic step and timer is started if (cs.get("timer_start") != None): # check if timer elapsed end = cs.get("endunix") + cs.get("timer") * 60000 now = int( (datetime.utcnow() - datetime(1970, 1, 1)).total_seconds()) * 1000 ## switch to next step if timer is over if (end < now): if (cs.get("type") == 'A'): nextStep() if (cs.get("type") == 'M' and app.brewapp_current_step.get( "finished", False) == False): nextStepBeep() app.brewapp_current_step["finished"] = True
def route_generate_brackets(division_final_id): division_final = fetch_entity(current_app.tables.DivisionFinal, division_final_id) division = fetch_entity(current_app.tables.Division, division_final.division_id) rollcall_list = json.loads(request.data) #['data'] final_rounds = generate_brackets(current_app, division_final_id, rollcall_list, division.finals_num_qualifiers) final_rounds_dicts = [ final_round.to_dict_simple() for final_round in final_rounds ] return jsonify({'data': to_dict(final_rounds_dicts)})
def get_all_problems_route(): problems = current_app.table_proxy.problems.get_problems(g.event_id) machines = current_app.table_proxy.machines.get_machines(g.event_id) machines_dict = { machine.machine_id: to_dict(machine) for machine in machines } return jsonify({ 'data': [serialize_problem(problem, machines_dict) for problem in problems], 'status': 'success' })
def add_player(): """Add a player""" player_data = json.loads(request.data) new_player = Player( first_name = player_data['first_name'], last_name = player_data['last_name'], search_name = "".join( player_data[field].lower() for field in ['first_name', 'last_name'] ) ) DB.session.add(new_player) DB.session.commit() return jsonify(to_dict(new_player))
def init(): ## REST API FOR STEP manager.create_api(Step, methods=['GET', 'POST', 'DELETE', 'PUT'], allow_patch_many=True, results_per_page=None, postprocessors={'GET_MANY': [post_get]}) s = Step.query.filter_by(state='A').first() if (s != None): app.brewapp_current_step = to_dict(s) if (s.timer_start != None): app.brewapp_current_step["endunix"] = int( (s.timer_start - datetime(1970, 1, 1)).total_seconds()) * 1000
def stepjob(): ## Skip if no step is active if(app.brewapp_current_step == None): return ## current step cs = app.brewapp_current_step; ## get current temp of target kettle try: id = int(app.brewapp_kettle_state[cs.get("kettleid")]["sensorid"]) ct = app.brewapp_thermometer_last[id]; except: ct = 0 #print cs.get("timer") #print cs.get("timer_start") #print cs.get("temp") #print ct ## check if target temp reached and timer can be started if(cs.get("timer") is not None and cs.get("timer_start") == None and ct >= cs.get("temp")): s = Step.query.get(cs.get("id")) s.timer_start = datetime.utcnow() app.brewapp_current_step = to_dict(s) if(s.timer_start != None): app.brewapp_current_step["endunix"] = int((s.timer_start - datetime(1970,1,1)).total_seconds())*1000 timerBeep() db.session.add(s) db.session.commit() socketio.emit('step_update', getSteps(), namespace ='/brew', broadcast=True) ## if Automatic step and timer is started if(cs.get("timer_start") != None): # check if timer elapsed end = cs.get("endunix") + cs.get("timer")*60000 now = int((datetime.utcnow() - datetime(1970,1,1)).total_seconds())*1000 ## switch to next step if timer is over if(end < now ): if(cs.get("type") == 'A'): nextStep() if(cs.get("type") == 'M' and app.brewapp_current_step.get("finished", False) == False): nextStepBeep() app.brewapp_current_step["finished"] = True
def to_dict_simple(self): division_machine = to_dict(self) division_machine[ 'division_machine_name'] = self.machine.machine_name division_machine['team_tournament'] = self.division.team_tournament division_machine['abbreviation'] = self.machine.abbreviation if self.player_id: division_machine['player'] = { 'player_id': self.player_id, 'player_name': "%s %s" % (self.player.first_name, self.player.last_name) } if self.team_id: division_machine['team'] = { 'team_id': self.team_id, 'team_name': "%s" % (self.team.team_name) } return division_machine
def next(id): active = FermenterStep.query.filter_by(fermenter_id=int(id), state='A').first() inactive = FermenterStep.query.filter_by(fermenter_id=int(id), state='I').order_by(FermenterStep.order).first() if active is not None: active.state = "D" active.end = datetime.datetime.utcnow() if inactive is not None: setTargetTemp(int(id), inactive.temp) inactive.start = datetime.datetime.utcnow() inactive.state = "A" app.cbp['CURRENT_TASK'][int(id)] = to_dict(inactive) temp = app.brewapp_thermometer_last[app.cbp['FERMENTERS'][int(id)]["sensorid"]] if temp >= inactive.temp: app.cbp['CURRENT_TASK'][int(id)]["direction"] = "C" else: app.cbp['CURRENT_TASK'][int(id)]["direction"] = "H" else: app.cbp['CURRENT_TASK'].pop(int(id), None) db.session.commit() reload_fermenter(int(id)) return ('', 204)
def get_tournaments(): """Get a list of tournaments""" return jsonify(tournaments=[ to_dict(t) for t in Tournament.query.order_by(Tournament.name.asc()).all() ])
def get_roles(): """Get a list of roles""" return jsonify(roles=[to_dict(r) for r in Role.query.all()])
def start_tournament(tournament): tournament.active = True DB.session.commit() return jsonify(to_dict(tournament))
def end_tournament(tournament): tournament.active = False DB.session.commit() return jsonify(to_dict(tournament))
def get_division(division): """Get a division""" division_dict = to_dict(division) division_dict['tournament'] = to_dict(division.tournament) return jsonify(division_dict)
def search_players(): """Get a list of players matching a query""" return jsonify(players = [to_dict(p) for p in Player.query.filter( Player.search_name.contains(request.args.get('substring')) ).order_by(Player.last_name.asc(), Player.first_name.asc()).limit(10)])
def to_dict(self): return to_dict(self, deep={'roles': []})
def to_dict(self): return to_dict(self)
def get_player(player): """Get a player""" player_data = to_dict(player) return jsonify(player_data)
def get_tournament(tournament): """Get a tournament""" tournament_data = to_dict(tournament) tournament_data['divisions'] = [to_dict(d) for d in tournament.divisions] return jsonify(tournament_data)
def reload_fermenter(id): f = Fermenter.query.get(id) d = to_dict(f, deep={'steps': []}) app.cbp['FERMENTERS'][f.id] = d socketio.emit('fermenter_update', d, namespace='/brew')
def get_players(): """Get a list of players""" return jsonify(players=[ to_dict(p) for p in Player.query.order_by(Player.last_name.asc(), Player.first_name.asc()).all() ])