def login(): try: if current_user.is_authenticated: user = User.query.filter(User.id == current_user.id).first() return make_response( jsonify(to_dict(user, exclude=User.getExclude()))) form_data = json.loads(request.get_data().decode('utf-8')) if ('email' in form_data) and ('password' in form_data): user = User.query.filter( User.email == form_data['email'], User.password == HashValidator.hash( form_data['password'])).first() if user is None: raise Error(name='Failed login', message='Combinatie email/wachtwoord is onbekend') login_user(user) return make_response( jsonify(to_dict(user, exclude=User.getExclude()))) else: raise Error( name='Failed login', message='Kan niet inloggen, email en/of wachtwoord ontbreekt') except Error as e: return make_response(jsonify({e.name: e.message}), 400)
def test_to_dict_hybrid_property(self): """Tests that hybrid properties are correctly serialized.""" young = self.Person(name=u'John', age=15) old = self.Person(name=u'Sally', age=25) self.session.commit() assert to_dict(young)['is_minor'] assert not to_dict(old)['is_minor']
def test_to_dict(self): t = ApiFactory() #d = t.to_dict() d = to_dict(t, exclude=t.__json_hidden__) assert 'integer_attr' in d assert 'string_attr' in d assert 'hidden_attr' not in d
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": "Brew Process Finished"}, 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 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: ct = app.brewapp_kettle_state[cs.get("kettleid")]["temp"] except: ct = 0 ## check if target temp reached and timer can be started if(cs.get("timer") > 0 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 db.session.add(s) db.session.commit() socketio.emit('step_update', getAsArray(Step), namespace ='/brew') ## if Automatic step and timer is started if(cs.get("type") == 'A' and 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): nextStep()
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": "Brew Process Finished"}, 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', getAsArray(Step, order = "order"), namespace ='/brew')
def current(): if current_user.is_authenticated: user = User.query.filter(User.id == current_user.id).first() return make_response( jsonify(to_dict(user, deep={"cook": []}, exclude=User.getExclude()))) else: return make_response(jsonify([]))
def test_uuid(self): """Tests for correct serialization of UUID objects.""" exampleuuid = uuid.uuid1() vehicle = self.Vehicle(uuid=exampleuuid) self.session.commit() d = to_dict(vehicle) assert 'uuid' in d assert str(exampleuuid) == d['uuid']
def init(): ## REST API FOR STEP manager.create_api(Step, methods=['GET', 'POST', 'DELETE', 'PUT'],allow_patch_many=True, postprocessors={'PATCH_SINGLE': [post_patch_many], 'DELETE_SINGLE': [post_patch_many], 'POST': [post_patch_many],'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 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 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 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 test_to_dict_nested_object(self): """Tests that nested objects are correctly serialized.""" person = self.Person(name=u'Test', age=10, other=20) computer = self.Computer(name=u'foo') person.computers.append(computer) data = to_dict(person, include_methods=['first_computer']) assert 'first_computer' in data assert 'foo' == data['first_computer']['name']
def test_date_serialization(self): """Tests that date objects in the database are correctly serialized in the :func:`flask.ext.restless.helpers.to_dict` function. """ person = self.Person(birth_date=date(1986, 9, 15)) self.session.commit() d = to_dict(person) assert 'birth_date' in d assert d['birth_date'] == person.birth_date.isoformat()
def test_datetime_serialization(self): """Tests that datetime objects in the database are correctly serialized in the :func:`flask.ext.restless.helpers.to_dict` function. """ computer = self.Computer(buy_date=datetime.now()) self.session.commit() d = to_dict(computer) assert 'buy_date' in d assert d['buy_date'] == computer.buy_date.isoformat()
def test_to_dict_dynamic_relation(self): """Tests that a dynamically queried relation is resolved when getting the dictionary representation of an instance of a model. """ person = self.LazyPerson(name=u'Lincoln') self.session.add(person) computer = self.LazyComputer(name=u'lixeiro') self.session.add(computer) person.computers.append(computer) self.session.commit() person_dict = to_dict(person, deep={'computers': []}) computer_dict = to_dict(computer, deep={'owner': None}) assert sorted(person_dict), ['computers', 'id' == 'name'] assert not isinstance(computer_dict['owner'], list) assert sorted(computer_dict) == ['id', 'name', 'owner', 'ownerid'] expected_person = to_dict(person) expected_computer = to_dict(computer) assert person_dict['computers'] == [expected_computer] assert computer_dict['owner'] == expected_person
def login(): try: if current_user.is_authenticated: user = User.query.filter(User.id == current_user.id).first() return make_response(jsonify(to_dict(user, exclude=User.getExclude()))) form_data = json.loads(request.get_data().decode('utf-8')) if ('email' in form_data) and ('password' in form_data): user = User.query.filter(User.email == form_data['email'], User.password == HashValidator.hash(form_data['password'])).first() if user is None: raise Error(name='Failed login', message='Combinatie email/wachtwoord is onbekend') login_user(user) return make_response(jsonify(to_dict(user, exclude=User.getExclude()))) else: raise Error(name='Failed login', message='Kan niet inloggen, email en/of wachtwoord ontbreekt') except Error as e: return make_response(jsonify({e.name: e.message}), 400)
def search(): try: dishes = Dish.query # get only dishes that have meals for the current day dishes = dishes.join(Dish.meals) dishes = dishes.filter(Meal.available_from.like('%' + str(date.today()) + '%')) dishes = dishes.options(contains_eager('meals')) dishes = dishes.order_by(asc(Dish.id)) # api/v1/search/dishes?allergies=1,2,3,4 returns all dishes that have no allergies 1,2,3,4 allergies = request.args.get('allergies') if allergies is not None: if allergies is not None: exclude_ids = allergies.split(',') dish_ids = DishAllergy.dish_id_exclude_allergies(exclude_ids) dishes = dishes.filter(~Dish.id.in_(dish_ids)) # api/v1/search/dishes?categories=1,2,3,4 returns all dishes that belong to EITHER (so it's an OR) categories 1,2,3,4 categories = request.args.get('categories') if categories is not None: if categories is not None: include_ids = categories.split(',') dish_ids = DishCategory.dish_id_include_categories(include_ids) dishes = dishes.filter(Dish.id.in_(dish_ids)) # api/v1/search/dishes?term=zalm finds "zalmfilet", "bereid met zalm", "zeezalm" term = request.args.get('term') if term is not None: dishes = dishes.filter(or_(Dish.name.like('%' + term + '%'), Dish.description.like('%' + term + '%'))) # api/v1/search/dishes?location=gro finds "groningen", "grootegast" location = request.args.get('location') if location is not None: dishes = dishes.join(Dish.cook).filter(Cook.location.like('%' + location + '%')) dishes = dishes.limit(100).all() json = {"objects": []} for dish in dishes: # json["objects"].append(to_dict(dish, deep={"allergies": {"id": {"id"}}}, include_relations={"allergies": ["id"]})) json["objects"].append(to_dict(dish, deep={'allergies': [], 'cook': [], 'categories': [], 'meals': [], 'reviews': []}, exclude_relations={'categories': ['parent_id']})) json["num_results"] = len(dishes) return make_response(jsonify(json)) except Error as e: return make_response(jsonify({e.name: e.message}), 400)
def test_to_dict(self): """Test for serializing attributes of an instance of the model by the :func:`flask.ext.restless.helpers.to_dict` function. """ me = self.Person(name=u'Lincoln', age=24, birth_date=date(1986, 9, 15)) self.session.commit() me_dict = to_dict(me) expectedfields = sorted(['birth_date', 'age', 'id', 'name', 'other', 'is_minor', 'is_above_21']) assert sorted(me_dict) == expectedfields assert me_dict['name'] == u'Lincoln' assert me_dict['age'] == 24 assert me_dict['birth_date'] == me.birth_date.isoformat()
def test_to_dict(self): """Test for serializing attributes of an instance of the model by the :func:`flask.ext.restless.helpers.to_dict` function. """ me = self.Person(name=u'Lincoln', age=24, birth_date=date(1986, 9, 15)) self.session.commit() me_dict = to_dict(me) expectedfields = sorted( ['birth_date', 'age', 'id', 'name', 'other', 'is_minor']) assert sorted(me_dict) == expectedfields assert me_dict['name'] == u'Lincoln' assert me_dict['age'] == 24 assert me_dict['birth_date'] == me.birth_date.isoformat()
def test_to_dict_deep(self): """Tests that fields corresponding to related model instances are correctly serialized by the :func:`flask.ext.restless.helpers.to_dict` function. """ now = datetime.now() someone = self.Person(name=u'John', age=25) computer = self.Computer(name=u'lixeiro', vendor=u'Lemote', buy_date=now) someone.computers.append(computer) self.session.commit() deep = {'computers': []} computers = to_dict(someone, deep)['computers'] assert len(computers) == 1 assert computers[0]['name'] == u'lixeiro' assert computers[0]['vendor'] == u'Lemote' assert computers[0]['buy_date'] == now.isoformat() assert computers[0]['owner_id'] == someone.id
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: ct = app.brewapp_kettle_state[cs.get("kettleid")]["temp"] except: ct = 0 ## check if target temp reached and timer can be started if(cs.get("timer") > 0 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') ## 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 serializer(self, instance): result = to_dict(instance) # Add extra information. result['foo'] = 'bar' return result
def current(): if current_user.is_authenticated: user = User.query.filter(User.id == current_user.id).first() return make_response(jsonify(to_dict(user, deep={"cook": [] }, exclude=User.getExclude()))) else: return make_response(jsonify([]))