def get(self): args = request.args if "page" in args.keys(): page = int(args["page"]) task_count = Task.query.count() if 0 < page <= task_count: tasks = Task.query.paginate(page, 1, False).items return {"tasks": marshal(tasks, task_fields)} else: return {"result": False} if "done" in args.keys(): done = int(args["done"]) if done is 1: tasks = Task.query.filter_by(done=True) return {"tasks": [marshal(task, task_fields) for task in tasks]} elif done is 0: tasks = Task.query.filter_by(done=False) return {"tasks": [marshal(task, task_fields) for task in tasks]} else: return {"result": False} if "ts" in args.keys(): ts = str(args["ts"]) tasks = Task.query.filter(Task.title.startswith(ts)).all() return {"tasks": [marshal(task, task_fields) for task in tasks]} else: tasks = Task.query.all() return {"tasks": [marshal(task, task_fields) for task in tasks]}
def post(self): user = Users() params = new_user_parser.parse_args() user.username = params.get("username") user.password = params.get("password") user.student_no = params.get("student_no", None) user.usertypesforsystem_id = params.get("usertypesforsystem_id") user.email = params.get("email") user.firstname = params.get("firstname") user.lastname = params.get("lastname") user.displayname = params.get("displayname") require(CREATE, user) username_exists = Users.query.filter_by(username=user.username).first() if username_exists: return {"error": "This username already exists. Please pick another."}, 409 student_no_exists = Users.query.filter_by(student_no=user.student_no).first() # if student_no is not left blank and it exists -> 409 error if user.student_no is not None and student_no_exists: return {"error": "This student number already exists. Please pick another."}, 409 try: db.session.add(user) db.session.commit() on_user_create.send( self, event_name=on_user_create.name, user=current_user, data=marshal(user, dataformat.get_users(False))) except exc.IntegrityError: db.session.rollback() current_app.logger.error("Failed to add new user. Duplicate.") return {'error': 'A user with the same identifier already exists.'}, 400 return marshal(user, dataformat.get_users())
def post(self, course_id, question_id): Courses.exists_or_404(course_id) PostsForQuestions.query.options(load_only('id')).get_or_404(question_id) question = PostsForQuestions(post=Posts(courses_id=course_id)) criteria_and_questions = CriteriaAndPostsForQuestions(question=question) judgements = Judgements(question_criterion=criteria_and_questions) require(CREATE, judgements) params = new_comment_parser.parse_args() results = [] for judgement in params['judgements']: judge = Judgements.query.get_or_404(judgement['id']) post = Posts(courses_id=course_id) post.content = judgement['comment'] post.users_id = current_user.id comment = PostsForComments(post=post) selfeval = params.get('selfeval', False) evalcomment = PostsForJudgements(postsforcomments=comment, judgements_id=judge.id, selfeval=selfeval) db.session.add(post) db.session.add(comment) db.session.add(evalcomment) db.session.commit() results.append(evalcomment) on_evalcomment_create.send( self, event_name=on_evalcomment_create.name, user=current_user, course_id=course_id, data=marshal(results, dataformat.get_posts_for_judgements(False))) return {'objects': marshal(results, dataformat.get_posts_for_judgements())}
def get(self, id=None, user=None): """ Returns user info. @param user : current user @param id : id of the queried user """ # TODO: this is for debugging. remove this. if not id: users = models.User.query.all() if users: #return jsonify(users = [u.as_dict() for u in users]) return marshal(users, self.allowed_user_fields), 200 else: return "No users found. Please create a user first.", 404 u = models.User.query.get(int(id)) if not u: return abort(404) #return jsonify(u.as_dict()) return marshal(u, self.allowed_user_fields), 200
def get(self, version, series=None, season=None, entry_type=None, round=None): ''' Handles routes /api/series/season/raceentry/entry_type/race_id Race entry list ''' results = [] if version == 'v1.0': if series and season and entry_type and round: raceentry = RaceEntry.query.\ join(RaceEntry.race).\ join(RaceEntry.entry_type).\ filter(Race.series == series).\ filter(Race.season == season).\ filter(Race.round == round).\ filter(RaceEntryType.entry_type == entry_type) raceentry = raceentry.all() for result in raceentry: rslt = marshal(result, self.race_entry_fields) for p in result.people: prsn = marshal(p.person, self.person_fields) rslt[p.type] = prsn results.append(rslt) return {'raceentry': results}
def get(self): print('FinPlanListAPI GET ') print(json.dumps(FinPlanScenario)) XX = map(lambda plan: marshal(plan, finplan_fields3), FinPlanScenario) print(json.dumps(XX)) return { 'Financial Plans': map(lambda plan: marshal(plan, finplan_fields3), FinPlanScenario) }
def get(self, version, series=None, season=None, round=None, session=None): ''' Handles routes /api/series/season/qualifyingresults/round Qualifying results list /api/series/season/qualifyingresults/round/session Qualifying results list on a given session ''' results = [] if version == 'v1.0': if series and season and round: qualifyingresults = QualifyingResult.query.\ join(QualifyingResult.race).\ filter(Race.series == series).\ filter(Race.season == season).\ filter(Race.round == round) if session: qualifyingresults = qualifyingresults.filter(QualifyingResult.session == session) qualifyingresults = qualifyingresults.all() for result in qualifyingresults: rslt = marshal(result, self.qualifying_result_fields) for p in result.people: prsn = marshal(p.person, self.person_fields) rslt[p.type] = prsn results.append(rslt) return {'qualifyingresults': results}
def get(self, id=None): if id == None: return {'quora': map(lambda t: marshal(t, quora_fields), quora)} quora_member = filter(lambda t: t['id'] == id, quora) if len(quora_member) == 0: abort(404) return marshal(quora_member[0], quora_fields)
def get(self, id): a = Author.query.filter(Author.id == id).first() if a is None: return {} article_author_fields = { 'lastname': fields.String, 'forenames': fields.String, 'id': fields.Integer } article_fields = { 'title': fields.String, 'abstract': fields.String, 'arxiv_id': fields.String, 'id': fields.Integer, 'authors': fields.List(fields.Nested(article_author_fields)) } author_fields = { 'id': fields.Integer, 'lastname': fields.String, 'forenames': fields.String, 'articles': fields.List(fields.Nested(article_fields)) } ans = {} ans['author'] = marshal(a, author_fields) similar_authors = Author.query.filter(Author.lastname.ilike(a.lastname)).filter( Author.forenames.ilike(a.forenames[0] + '%')) if similar_authors is not None: ans['similar_authors'] = map(lambda t: marshal(t, article_author_fields), similar_authors) else: ans['similar_authors'] = [] return ans
def make_response(data, marshal_table, cursors=None): if util.is_iterable(data): response = { 'status': 'success', 'count': len(data), 'now': datetime.utcnow().isoformat(), 'result': map(lambda l: restful.marshal(l, marshal_table), data), } if cursors: if isinstance(cursors, dict): if cursors.get('next'): response['next_cursor'] = cursors['next'] response['next_url'] = util.generate_next_url(cursors['next']) if cursors.get('prev'): response['prev_cursor'] = cursors['prev'] response['prev_url'] = util.generate_next_url(cursors['prev']) else: response['next_cursor'] = cursors response['next_url'] = util.generate_next_url(cursors) return util.jsonpify(response) return util.jsonpify({ 'status': 'success', 'now': datetime.utcnow().isoformat(), 'result': restful.marshal(data, marshal_table), })
def get(self, id=None): if id == None: return {'accelerator': map(lambda t: marshal(t, accelerator_fields), accelerator)} accelerator_member = filter(lambda t: t['id'] == id, accelerator) if len(accelerator_member) == 0: abort(404) return marshal(accelerator_member[0], accelerator_fields)
def get(self): """ Returns all the nodes + sensors on the db. """ args = self.reqparse.parse_args() if args['id'] == None: # We want al the nodes nodes = manager.get_nodes() return jsonify(nodes=nodes) elif args['id'] != None: # We usually want to pair with this node if it has bluetooth node = manager.get_node(args['id']) if node['nic'] == BLUETOOTH: # Unpair the last one global serial_connection temp = serial_connection if temp != None: global serial_connection serial_connection.close() global serial_connection serial_connection = None global serial_connection serial_connection = Connection(node['address'], BLUE_RATE) if node.get('address', None) != None: return {'node' : marshal(node, NodesAPI.node_field_address)} else: return {'node' : marshal(node, NodesAPI.node_field)} else: abort(400)
def post(self) : try : args = self.reqparse.parse_args() user = User.authenticate(args['email'], args['password']) if not user : print "can't find user" abort(404) # first try and get an existing and valid token tokens = Token.query.filter((Token.user_id==user.id and Token.valid)).first() if tokens : return jsonify({"code" : 200, "user" : marshal(user, user_fields), "token" : tokens.value}) # otherwise make them a new one new_token = Token(user_id=user.id) if not new_token : print "can't make new token" abort(403) user.tokens.append(new_token) db.session.add(user) db.session.commit() return jsonify({"code" : 200, "user" : marshal(user, user_fields), "token" : new_token.value}) except Exception, e : print str(e) return abort(403)
def init_data(self): user = create_user( "*****@*****.**", "9527", "Known User" ) client = create_client( user, "Known app", "Official known app for testing", "known://fake/app" ) self.known_client = client access_token = create_access_token( "known_token", user, client, ) self.known_access_token = access_token device = get_or_create_device(access_token) self.known_device = device self.known_device_marshalled = marshal(device, device_fields) # fetch user again, since it might be modified user_dict = User.find_one({"_id": user["_id"]}) user = User() user.update(user_dict) self.known_user = user self.known_user_marshalled = marshal(user, user_fields)
def get(self, project_id=None): user_id = get_current_user_id() if project_id: project = Project.query.filter_by( is_show=True, category=get_enum('COMMON_PROJECT'), id=project_id, user_id=user_id).first() if not project or project.status not in get_enum('PROJECT_SHOW'): abort(406) return marshal(project, get_field('project_detail')) projects = pagination( filtering( sorting( Project.query.filter_by( is_show=True, category=get_enum('COMMON_PROJECT'), user_id=user_id ).filter( Project.status.in_(get_enum('PROJECT_SHOW')) ) ) ) ).all() return marshal(projects, get_field('project_list'))
def get(self, id=None): if id == None: return { 'feedback': map(lambda t: marshal(t, feedback_fields), feedback) } feedback_member = filter(lambda t: t['id'] == id, feedback) if len(feedback_member) == 0: abort(404) return marshal(feedback_member[0], feedback_fields)
def get(self, question_url): args = QuestionResource.parser.parse_args() question = Question.query.filter_by(url=question_url).first_or_404() if args["details"]: return marshal(question, QuestionResource.fields_with_detail) else: return marshal(question, QuestionResource.fields)
def post(self): #import pdb; pdb.set_trace() if login_check(session): return marshal({'status':'already login', 'user_id':None}, app_auth_fields) args = AppAuthArgs().args args['user_name'] = args['user_name'].encode('utf-8') args['password'] = args['password'].encode('utf-8') request_url = APP_AUTH_URL % (args['user_name'], args['password']) r = requests.get(request_url) if r.status_code != requests.codes.ok: return marshal({'status':'can not get rs response', 'user_id':None, 'user_name':None}, app_auth_fields) result = json.loads(r.text) if result['status'] != 'ok': return marshal({'status':result['status'], 'user_id':None, 'user_name':None}, app_auth_fields) session['login_user'] = result['user_id'] #update user table if not user_model.get_user(user_id=result['user_id']): user_model.add_user(result['user_id']) #update login_user table login_user = login_user_model.get_login_user(user_id=result['user_id']) if login_user: login_user_model.delete_login_user(login_user[0]) cookie_key = hashlib.md5(result['user_id']).hexdigest().lower() login_user_model.add_login_user(user_id=result['user_id'], cookie_key=cookie_key, user_name=result['user_name']) return marshal({'status':'success', 'user_id':result['user_id'], 'user_name': result['user_name']}, app_auth_fields)
def get(self, query = ""): if query == "all": result = { 'interfaces': {}, 'modules': {} } for name, face in registry.interfaces.iteritems(): result['interfaces'][name] = marshal(face, interface_spec) for name, mod in interfaces.modules.iteritems(): result['modules'][name] = marshal(mod, module_spec) return result query = query.replace("/", ".") message = "" try: # faster to resolve synchronously rather than go through Celery result, isInterface = resolve(query) if result is None: message = "There is no interface or module at path '/" + query.replace(".", "/") + "'." abort(404, message) res = {} if isInterface: res['apiVersion'] = '1.0' res['type'] = 'interface' res['data'] = marshal(result, interface_spec) return res else: res['apiVersion'] = '1.0' res['type'] = 'module' res['data'] = marshal(result, module_spec) return res except: abort(400, message = message)
def post(self, course_id, question_id): Courses.exists_or_404(course_id) PostsForQuestions.query.options(load_only('id')).get_or_404(question_id) post = Posts(courses_id=course_id) comment = PostsForComments(post=post) comment_for_question = PostsForQuestionsAndPostsForComments(postsforcomments=comment, questions_id=question_id) require(CREATE, comment) params = new_comment_parser.parse_args() post.content = params.get("content") if not post.content: return {"error": "The comment content is empty!"}, 400 post.users_id = current_user.id db.session.add(post) db.session.add(comment) db.session.add(comment_for_question) on_comment_create.send( self, event_name=on_comment_create.name, user=current_user, course_id=course_id, data=marshal(comment, dataformat.get_posts_for_comments_new(False))) db.session.commit() return marshal(comment, dataformat.get_posts_for_comments_new())
def get(self, standardtekst_id=None): if standardtekst_id: standardtekst = self.get_by_id(standardtekst_id) return marshal(standardtekst, standardtekst_fields) else: return marshal(self.repo.find_all(), standardtekst_fields)
def post(self): args = parser.parse_args() # FIXME ou pas # Lorsqu'on bann un auteur de SMS, le provider_user_id dans les args est fatalement déjà hashé # donc ce test ne peut pas marcher ... # conséquence: pas de masquage des messages postés avant le bannissement, il n'y a qu'au post du SMS # que l'on peut tester si dumber ou pas isindb = get_dumber_by_provider_id(args['provider_user_id'], args['provider']) if not isindb: if args['provider'] == 'TWITTER': twuser = TW_Client.api.get_user(args['provider_user_id'], include_entities=1) args['provider_src'] = twuser args['provider_user_id'] = twuser['id_str'] # elif args['provider'] == 'SMS': # args['author'] = 'SMS' # args['provider_id'] = args['id'] dmb_id = dumbers.insert(args) ShoutNamespace.broadcast('dumber_added', {'provider_user_id': args['provider_user_id']} ) if args['provider'] == 'TWITTER': return marshal(args, resource_fields_twitter), 200 elif args['provider'] == 'SMS': return marshal(args, resource_fields_sms), 200 return
def get(self, id=None): if id == None: return { 'relationship': map(lambda t: marshal(t, self.relationship_fields), self.relationship) } relationship_member = filter(lambda t: t['id'] == id, self.relationship) if len(relationship_member) == 0: abort(404) return marshal(relationship_member[0], self.relationship_fields)
def get(self, dmb_id): dmb = get_dumber_or_abort(dmb_id) dumb = json.loads(json_dump(dmb)) if dmb['provider'] == 'TWITTER': return marshal(dumb, resource_fields_twitter), 200 elif dmb['provider'] == 'SMS': return marshal(dumb, resource_fields_sms), 200
def get(self, id=None): if id == None: return {'project': map(lambda t: marshal(t, project_fields), project)} project_member = filter(lambda t: t['id'] == id, project) if len(project_member) == 0: abort(404) return marshal(project_member[0], project_fields)
def get(self, id=None): if id is None: domain_controllers = DomainController.query.order_by('name') domain_controllers = filter( lambda domain_controller: current_user.has_permission( ( ViewDomainPermission, EditDomainPermission, CreateDomainPermission ), domain_controller.id ), domain_controllers ) return { 'domain_controllers': map( lambda t: marshal( t, domain_controller_fields_with_domains ), domain_controllers ), } else: domain_controller = DomainController.query.get(id) return marshal( domain_controller, domain_controller_fields_with_domains )
def get(self, version, series=None, season=None, round=None, session=None): ''' Handles routes /api/series/season/practiceresults/round Practice results list /api/series/season/practiceresults/round/session Practice results list for a given session ''' results = [] if version == 'v1.0': if series and season and round: practiceresults = PracticeResult.query.\ join(PracticeResult.race).\ filter(Race.series == series).\ filter(Race.season == season).\ filter(Race.round == round) if session: practiceresults = practiceresults.filter(PracticeResult.session == session) practiceresults = practiceresults.all() for result in practiceresults: rslt = marshal(result, self.practice_result_fields) for p in result.people: prsn = marshal(p.person, self.person_fields) rslt[p.type] = prsn results.append(rslt) return {'practiceresults': results}
def put(self, zone_name): zone = lookup_zone(zone_name, abort_notfound=False) # we don't allow changing the local zone if zone and zone['type'] == 'local': abort(403, message="Zone %s is local, and cannot be managed" % zone_name) args = self.reqparse.parse_args() (success, reason) = check_zone_endpoint(zone_name, args['endpoint']) if not success: abort(400, message='problem with endpoint: %s' % reason) if zone: # updating an existing zone # only allow the zone creator to make changes if zone['comment'] != 'creator=%s' % auth.username(): abort(403, message="Zone can only be updated by the zone creator") newzone = modify_zone(zone_name, args['endpoint']) if newzone: return marshal(newzone, zone_fields), 200 else: abort(500, message="Server error when modifying zone %s" % zone_name) else: # creating a new zone comment = 'creator=%s' % auth.username() newzone = make_zone(zone_name, args['endpoint'], comment) if newzone: return marshal(newzone, zone_fields), 201 else: abort(500, message="Server error when creating zone %s" % zone_name)
def get(self, version, series=None, season=None, round=None): ''' Handles routes /api/series/season/raceresults/round Race results list ''' results = [] if version == 'v1.0': if series and season and round: raceresults = RaceResult.query.\ join(RaceResult.race).\ filter(Race.series == series).\ filter(Race.season == season).\ filter(Race.round == round) raceresults = raceresults.all() for result in raceresults: rslt = marshal(result, self.race_result_fields) for p in result.people: prsn = marshal(p.person, self.person_fields) rslt[p.type] = prsn results.append(rslt) return {'raceresults': results}
def get(self, device_id): if device_id is None: user = get_user_or_abort() devices = Device \ .find({'_id': {'$in': [oid for oid in user.device_ids]}}) \ .sort('updated_since', -1) devices_marshaled = [] for device in devices: devices_marshaled.append(marshal(device, device_fields)) return jsonify({ "flag": "success", "res": devices_marshaled, }) elif device_id == "from_access_token": device = get_device_or_abort() return jsonify({ "flag": "success", "res": marshal(device, device_fields), }) else: device = Device.find_one({'_id': ObjectId(device_id)}) if not device: raise ApiException( code=404, msg="Device {} doesn't exist".format(device_id), ) return jsonify({ "flag": "success", "res": marshal(device, device_fields), })
def get(self, exp_id, gene_id): isExistExp = session.query(Experiment).filter( Experiment.id == exp_id).scalar() isExistGene = session.query(GeneExpressionTPM.id).filter( GeneExpressionTPM.ensembl_id == gene_id).all() if not isExistExp and not isExistGene: abort(404) else: samples = session.query( Sample.id).filter(Sample.experiment_id == exp_id).all() samples_id = [s[0] for s in samples] gene = session.query(GeneExpressionTPM).filter( GeneExpressionTPM.ensembl_id == gene_id, GeneExpressionTPM.sample_id.in_(samples_id)).all() return ({'gene': marshal(gene, gene_fields)}, 201)
def response_marshaler(cls, response_bragi, uri=None, depth=1): cls._check_response(response_bragi, uri) json_response = response_bragi.json() # Clean dict objects depending on depth passed in request parameter. json_response = cls._clean_response(json_response, depth) if jormungandr.USE_SERPY: from jormungandr.interfaces.v1.serializer.geocode_json import GeocodePlacesSerializer return GeocodePlacesSerializer(json_response).data else: from flask.ext.restful import marshal m = marshal(json_response, geocodejson) # Removing places that are not marshalled (None) if isinstance(m.get('places'), list): m['places'] = [p for p in m['places'] if p is not None] return m
def get(self, id, machineName=None): instance = self._getInstance(id) jeto_infos = None if machineName is None: instance.status, jeto_infos, scripts = instance._status() # instance.jeto_infos = json.dumps(instance.jeto_infos) else: # app.logger.debug(instance._ip(machineName)) return {'ip': instance._ip(machineName)} instance_json = marshal(instance, instance_fields) instance_json['jeto_infos'] = jeto_infos instance_json['scripts'] = scripts return instance_json
def put(self, _id): channel = [ channel for channel in channel_col.find() if str(channel['_id']) == _id ] if len(channel) == 0: abort(404) channel = channel[0] args = self.reqparse.parse_args() for k, v in args.items(): if v is not None: channel[k] = v channel_col.find_one_and_update({'_id': ObjectId(_id)}, {'$set': channel}) return {'channel': marshal(channel, channel_fields)}
def post(self): """ POST /api/actions """ if current_user and current_user.is_authenticated: form_data = request.json log.debug('Delegate Action request: {0}'.format(form_data)) # Validation here form = DelegateActionForm.from_json(form_data['data']) if form.validate(): form_data['data']['author_id'] = current_user.id action = delegate_action(form_data) result = dict(status=200, message='OK', action=action) return marshal(result, action_create_fields) else: abort(400, message="Invalid Parameters", errors=form.errors) abort(401, message="Requires user to login")
def post(self): """ Creates a new atom. If the atom already exists, it updates the atom. """ # Prepare the atom data and validate it data = reqparse.request.get_json() if 'type' in data: if data['type'] in types.__dict__: type = types.__dict__.get(data['type']) else: abort(400, 'Invalid request: type \'' + type + '\' is not a ' 'valid type') else: abort(400, 'Invalid request: required parameter type is missing') # TruthValue tv = ParseTruthValue.parse(data) # Outgoing set if 'outgoing' in data: if len(data['outgoing']) > 0: outgoing = [Handle(h) for h in data['outgoing']] else: outgoing = None # Name name = data['name'] if 'name' in data else None # Nodes must have names if is_a(type, types.Node): if name is None: abort(400, 'Invalid request: node type specified and required ' 'parameter name is missing') # Links can't have names else: if name is not None: abort(400, 'Invalid request: parameter name is not allowed for ' 'link types') try: atom = self.atomspace.add(t=type, name=name, tv=tv, out=outgoing) except TypeError: abort(500, 'Error while processing your request. Check your ' 'parameters.') return {'atoms': marshal(atom, atom_fields)}
def post(self): """Add new quiz""" logs.debug_ ("_________________________________________________") logs.debug_ ("QuizzesAPI post fn: %s\nJson Request\n=============\n %s" %(request, request.json)) userid, username = utls.get_user_from_hdr() if 'username' not in session: response = handle_invalid_usage(InvalidUsageException ('Error: No active session for this user found', status_code=404)) return response # Get values from request args = self.reqparse.parse_args() for key, value in args.iteritems(): if value is not None: if (key == 'title'): title = request.json['title'] if (key == 'difficulty_level'): difficulty_level = request.json['difficulty_level'] if (key == 'text'): text = request.json['text'] # Update tables quiz_obj = models.Quiz(title, difficulty_level, text, userid) models.db.session.add(quiz_obj) models.db.session.commit() # Return response location = "/quizzes/%s" % quiz_obj.qzid query_obj = models.Quiz.query.filter_by(qzid=quiz_obj.qzid).all() resource_fields = {'qzid':fields.Integer, 'title':fields.String, 'difficulty_level':fields.String, 'text':fields.String, 'no_ques':fields.Integer } quiz = marshal(query_obj, resource_fields) response = jsonify(quiz=quiz) response.status_code = 201 response.location = location logs.info_(response) utls.display_tables() return response
def post(self): email = request.json['email'] user = users.first(email=email) if user: abort(409) # user exists password = request.json['password'] password = users.__model__.hash_password(password) user = users.create(email=email, password=password, registered_at=datetime.datetime.utcnow()) send_email.delay('Paperchase registration', 'registration', email, email=email, domain=current_app.config['DOMAIN']) return marshal(user, user_fields)
def post(self): """ POST /api/risk_assessments """ if current_user and current_user.is_authenticated: form_data = request.json log.debug('Propose Risk Action request: {0}'.format(form_data)) # Validation here # form = DelegateActionForm.from_json(form_data['data']) # if form.validate(): risk_assessment = propose_risk(form_data) result = dict(status=200, message='OK', risk_assessment=risk_assessment) return marshal(result, risk_assessment_create_fields) # else: # abort(400, message="Invalid Parameters", errors=form.errors) abort(401, message="Requires user to login")
def patch(self, container_id): """Updates information on a single container. Currently just status.""" args = self.reqparse.parse_args() if 'status' in args: if args['status'] == STOPPED: stop_container.delay(container_id) r.hset('containers:%s' % container_id, 'status', STOPPING) elif args['status'] == RUNNING: try: start_container(container_id) except APIError as exception: abort(500, message=exception.explanation) container = r.hgetall('containers:%s' % container_id) return marshal(container, container_fields)
def post(self): params = { 'name': request.form.get('name', '').strip(), 'year': request.form.get('year'), 'cover_url': request.form.get('cover_url'), } if not params['name']: abort(HTTP.BAD_REQUEST) album = self.create(**params) response = marshal(album, self.get_resource_fields()) headers = {'Location': url_for('albums', id=album.pk)} return response, 201, headers
def post(self): name = request.form.get('name', '').strip() if not name: abort(HTTP.BAD_REQUEST) image_url = request.form.get('image_url') try: artist = self.create(name, image_url) except (IntegrityError, ObjectExistsError): abort(HTTP.CONFLICT) response = marshal(artist, self.get_resource_fields()) headers = {'Location': url_for('artists', id=artist.pk)} return response, 201, headers
def post(self): if g.user is None: abort(HTTP.BAD_REQUEST) name = request.form.get('name', '').strip() if not name: abort(HTTP.BAD_REQUEST) read_only = request.form.get('read_only', True) playlist = self.create(name=name, read_only=read_only, user=g.user) response = marshal(playlist, self.get_resource_fields()) headers = {'Location': url_for('playlists', id=playlist.pk)} return response, 201, headers
def post(self): args = self.reqparse.parse_args() channel = { 'subjects': args['subjects'], 'channel_name': args['channel_name'], 'author_id': args['author_id'], 'subscriber_ids': [], 'video_ids': [] } channel['_id'] = str(channel_col.insert_one(channel).inserted_id) user_col.find_one_and_update( {'_id': ObjectId(channel['author_id'])}, {'$push': { 'channel_ids': channel['_id'] }}) return {'channel': marshal(channel, channel_fields)}, 201
def put(self, controller_id): args = self.reqparse.parse_args() controller = Controller.query.get(controller_id) controller.name = args['name'] controller.description = args['description'] controller.status = args['status'] controller.pipeRead = args['pipeRead'] controller.pipeWrite = args['pipeWrite'] print("Going to set the value of the controller to : %r" % (controller.status)) for element in controller.elements: print(element) controller.updateController() #db.session.update(controller) db.session.commit() return marshal(controller, controller_fields)
def get(self, id): record = UserSurvey.query.filter_by(user=id).first() abort_if_record_doesnt_exist(id, record) output = [] row = {} for field in UserSurvey.__table__.c: field = str(field).replace("user_survey.", "") if field == "induction_completed" and record.induction_completed == True: return {"status": True} row[field] = getattr(record, field, None) output.append(row) return {'data': marshal(output, user_fields)}
def output(self, key, data): value = fields.get_value( key if self.attribute is None else self.attribute, data) # we cannot really test for external dict behavior if fields.is_indexable_but_not_string(value) and not isinstance( value, dict): # Convert all instances in typed list to container type return [ self.container.output(idx, val) for idx, val in enumerate(value) ] if value is None: return self.default return [marshal(value, self.container.nested)]
def post(self, criteria_id): criterion = Criteria.query.get_or_404(criteria_id) require(EDIT, criterion) params = existing_criterion_parser.parse_args() criterion.name = params.get('name', criterion.name) criterion.description = params.get('description', criterion.description) criterion.default = params.get('default', criterion.default) db.session.add(criterion) db.session.commit() criteria_update.send(self, event_name=criteria_update.name, user=current_user) return {'criterion': marshal(criterion, dataformat.get_criteria())}
def get(self, name): """Displays information of a course to both guests and logged in users. only public information is displayed to guests """ if g.user is None: model_fields = public_course_fields else: model_fields = course_fields course = Course.objects.get_or_404(name=name) if not g.user.can_view_course(course): abort( 403, message= "You can not view this course. It is probably not ready for you!" ) return marshal(course.to_dict(), model_fields), 200
def post(self, incident_id): """ POST /api/incidents/<incident_id>/photos """ log.debug("POST Upload Incident Photo request id={0} {1} {2}".format( incident_id, request.files, request.form)) uploaded_file = request.files['file'] if uploaded_file and self.allowed_file(uploaded_file.filename): try: caption = request.form['caption'] if request.form[ 'caption'] is not None else '' photo = upload_photo(incident_id, uploaded_file, caption) result = dict(status=200, message="OK", photo=photo) return marshal(result, incident_photo_create_fields) except IncidentNotFoundError as err: abort(404, message=err.message) else: abort(400, message="Invalid parameters")
def post(self, block_id): """ POST /api/blocks/<block_id>/lots """ form_data = request.json log.debug('Add Lot for Block id={0} request: {1}'.format( block_id, form_data)) # TODO check authenticated user form = AddLotForm.from_json(form_data) try: if form.validate(): lot = lot_service.create_from_dict(block_id, form_data) result = dict(status=200, message='OK', lot=lot) return marshal(result, lot_create_fields) else: abort(400, message="Invalid Parameters", errors=form.errors) except LotPriceNullError as err: abort(403, message=err.message)
def get(self, loc_type_id): # marshal() converts a custom object/dictionary/list using the mapper # into a Python dict data = marshal(services.location_types.get_or_404(pk=loc_type_id), LOCATION_TYPE_FIELD_MAPPER) # for the Url field, the constructor argument must be a full # path, because it will be converted using Flask's url_for(), # in the output() call, and if you don't give something it can # convert, it will fail with a BuildError # also, for a single item, you really don't need the url specced, # but whatever urlfield = fields.Url('locations.api.locationtype') data['uri'] = urlfield.output('uri', {'loc_type_id': data['id']}) return jsonify(data)
def post(self, lot_id): """ POST /api/lots/<lot_id>/deceased """ form_data = request.json log.debug('Add Deceased for Lot id={0} request: {1}'.format( lot_id, form_data)) # TODO check authenticated user form = AddDeceasedForm.from_json(form_data) try: if form.validate(): data = lot_service.add_occupant(lot_id, form_data) result = dict(status=200, message='OK', deceased=data) return marshal(result, deceased_create_fields) else: abort(400, message="Invalid Parameters", errors=form.errors) except LotPriceNullError as err: abort(403, message=err.message)
def get(self, qzid): """Get all questions for quiz""" logs.debug_ ("_________________________________________________") logs.debug_ ("QuestionisAPI get fn: %s" %(request)) # Check if user is auth to get details of this ques userid, username = utls.get_user_from_hdr() query_obj = models.Quiz.query.filter_by(qzid=qzid).first() if (query_obj.userid != userid): response = handle_invalid_usage(InvalidUsageException ('Error: Unauthorized Username for this quiz', \ status_code=401)) return response if 'username' not in session: response = handle_invalid_usage(InvalidUsageException ('Error: No active session for this user found', status_code=404)) return response # Query from questions table query_obj = models.Question.query.join(models.Quiz).join(models.Anschoice).\ filter(models.Quiz.qzid == qzid).all() if not query_obj: response = handle_invalid_usage(InvalidUsageException ('Error: No question for quiz found', status_code=404)) return response # Return response ans_fields = {'ans_choice':fields.String, 'correct':fields.Boolean } resource_fields = {'qid':fields.Integer, 'ques_text':fields.String, 'ans_text':fields.String, 'qzid':fields.Integer, 'anschoices':fields.Nested(ans_fields) } questions = marshal(query_obj, resource_fields) response = jsonify(questions=questions) response.status_code = 200 utls.display_tables() logs.info_(response) return response
def post(self): args = self.postreqparse.parse_args() if not 'run_id' in args: abort(400) sample = Sample() for k, v in args.iteritems(): if v != None: setattr(sample, k, v) session = app.session_maker() session.add(sample) session.commit() return {'sample': marshal(sample, sample_fields)}, 201
def post(self): todo_json = request.get_json() try: # TODO: Should handle "data-validation" better # ...couldn't get it to work with reqparse. todo_data = todo_json["todo"] todo = Todo(todo_data['task'], todo_data['is_done']) g.db.session.add(todo) g.db.session.commit() except: abort(400) return { 'todo': marshal(todo, self.get_resource_fields()) }, 201
def get(self, course_id, question_id, answer_id): Courses.exists_or_404(course_id) answer = PostsForAnswers.query. \ options(joinedload('post').joinedload('files')). \ options(joinedload('post').joinedload('user').joinedload('usertypeforsystem')). \ options(joinedload('scores')). \ get_or_404(answer_id) require(READ, answer) on_answer_get.send( self, event_name=on_answer_get.name, user=current_user, course_id=course_id, data={'question_id': question_id, 'answer_id': answer_id}) return marshal(answer, dataformat.get_posts_for_answers(True))
def put(self, section_id): """ PUT /api/sections/<section_id> """ form_data = request.json log.debug('Update Section request id {0}: {1}'.format( section_id, form_data)) # TODO check authenticated user form = AddSectionForm.from_json(form_data) if form.validate(): try: section = section_service.update_from_dict( section_id, form_data) result = dict(status=200, message='OK', section=section) return marshal(result, section_create_fields) except SectionNotFoundError as err: abort(404, message=err.message) else: abort(400, message="Invalid Parameters", errors=form.errors)
def get(self): """Retrieve all Trees.""" query = """ match (p:Tree) return p.name, p.descr, id(p) order by p.name """ result = graph.cypher.execute(query) output = [] for x in result: tree = marshal({ "name": x[0], "descr": x[1], "tid": x[2] }, tree_fields) output.append(tree) return output
def post(self): form = SessionCreateForm() if not form.validate_on_submit(): logging.warn("validation error on user login") return form.errors, 422 user = User.query.filter_by(email=form.email.data).first() if user and user.check_password(form.password.data): return marshal( { 'token': user.generate_auth_token( app.config['SECRET_KEY']), 'is_admin': user.is_admin, 'user_id': user.id }, token_fields) logging.warn("invalid login credentials for %s" % form.email.data) return {'message': 'Unauthorized', 'status': 401}, 401