def put(self, name): """ Create or update group. """ args = self.new_group_parser.parse_args() args['visibility'] = GroupVisibility.unserialize(args['visibility']) name = name.encode(db.encoding) result_code = 200 try: # find and update all attributes group = utils.get_group(name, 'name', 'Group') changes = False if group.visibility != args['visibility']: group.visibility = args['visibility'] changes = True if group.description != args['description']: group.description = args['description'].encode(db.encoding) changes = True if changes: group.write_db() except utils.EntityLookupError: # create group group = Factory.get('Group')(db.connection) bad_name = group.illegal_name(name) if bad_name: abort(400, message="Illegal group name: {!s}".format(bad_name)) group.new(auth.account.entity_id, args['visibility'], name, args['description']) result_code = 201 return self.group_info(group), result_code
def driver_form(): db = current_app.extensions['sqlalchemy'].db form = None if request.args.get("id"): driver = taxis_models.Driver.query.get(request.args.get("id")) if not driver: abort(404, message="Unable to find driver") if not driver.can_be_edited_by(current_user): abort(403, message="You can't edit this driver") form = DriverUpdateForm(obj=driver) else: form = DriverCreateForm() if request.method == "POST": if request.args.get("id"): driver.last_update_at = datetime.now().isoformat() form.populate_obj(driver) if form.validate(): current_app.extensions['sqlalchemy'].db.session.commit() return redirect(url_for('api.drivers')) else: driver = taxis_models.Driver() form.populate_obj(driver) current_app.extensions['sqlalchemy'].db.session.add(driver) current_app.extensions['sqlalchemy'].db.session.commit() return redirect(url_for('api.drivers')) return render_template('forms/driver.html', form=form, form_method="POST", submit_value="Modifier")
def get(self, service_id, application_name): """Get application for the service""" service = self._find_service(service_id) for app in service.applications: if app.name == application_name: return app abort(404, error="No such application")
def post(self): schema = UserSchema() user, errors = schema.load(current_app.api.payload) if errors: abort(409, errors) user.save() return schema.dump(user)
def delete(self, aid, sid, cid): '''Delete reviews given assignment id, reviewee id, and criterion id''' if not self.dal.is_record_exist(aid, reviewee_id=sid, criterion_id=cid): abort(404, message=MESSAGE_DOESNT_EXIST) else: self.dal.del_reviews_by_assignment_criterion_reviewee(aid, sid, cid) return marshal({'message':MESSAGE_DELETED}, message_marshaller), 200
def put(self): j = request.json try: id = int(request.args.get('id',None)) except: abort(400, 'Malformed request') u = authorize(request) u_username = u[1] if not j or not id: abort(400, 'Malformed request') if not db.exists('POST').where(id=id): abort(400, 'Malformed request') # check the logged in user made this post post_author = db.select('POST').where(id=id).execute()[1] if u[1] != post_author: # exposing what post id's are valid and unvalid # may be a security issue lol abort(403, 'You Are Unauthorized To Edit That Post') (desc,src) = unpack(j,'description_text','src',required=False) if desc == None and src == None: abort(400, 'Malformed Request') updated = {} if desc: updated['description'] = desc if src: updated['src'] = src db.update('POST').set(**updated).where(id=id).execute() return { 'message': 'success' }
def find_person(id): pe = Factory.get('Person')(db.connection) try: pe.find(id) except Errors.NotFoundError: abort(404, message=u"No such person with entity_id={}".format(id)) return pe
def get(self, aid, sid): '''Summarize reviews given assignment id and reviewee id''' results = self.sum.get_summary_by_assignment_reviewee(aid, sid) try: return marshal({'summary':results}, summary_marshaller), 200 except Exception as e: abort(500, message=str(e))
def delete(self, aid, sid, cid): """Delete reviews given assignment id, reviewee id, and criterion id""" if not self.dal.is_record_exist(aid, reviewee_id=sid, criterion_id=cid): abort(404, message=MESSAGE_DOESNT_EXIST) else: self.dal.del_reviews_by_assignment_criterion_reviewee(aid, sid, cid) return {"message": MESSAGE_DELETED}, 200
def get(self, aid, sid, cid): """Summarize reviews given assignment id, reviewee id and criterion id""" results = self.sum.get_summary_by_assignment_criterion_reviewee(aid, cid, sid) try: return {"summary": results}, 200 except Exception as e: abort(500, message=str(e))
def get(self, aid, sid, cid): """Fetch reviews given assignment id, reviewee id, and criterion id""" results = self.dal.get_reviews_by_assignment_criterion_reviewee(aid, sid, cid) try: return {"reviews": results}, 200 except Exception as e: abort(500, message=str(e))
def get(self, aid, sid, len): """Summarize reviews given assignment id, reviewee id and length of the summary""" results = self.sum.get_summary_by_assignment_reviewee(aid, sid, length=len) try: return {"summary": results}, 200 except Exception as e: abort(500, message=str(e))
def get(self, aid, sid): """Fetch reviews given assignment id and reviewee id""" results = self.dal.get_reviews_by_assignment_reviewee(aid, sid) try: return {"summary": results}, 200 except Exception as e: abort(500, message=str(e))
def get(self): """List accounts.""" args = self.account_search_filter.parse_args() filters = {key: value for (key, value) in args.items() if value is not None} if 'owner_type' in filters: try: owner_type = db.const.EntityType(filters['owner_type']) filters['owner_type'] = int(owner_type) except Errors.NotFoundError: abort(404, message=u'Unknown entity type for owner_type={}'.format( filters['owner_type'])) ac = Factory.get('Account')(db.connection) accounts = list() for row in ac.search(**filters): account = dict(row) account.update({ 'id': account['name'], 'owner': { 'id': account['owner_id'], 'type': account['owner_type'], } }) accounts.append(account) return {'accounts': accounts}
def get(self, cluster_id, provider_name): """List cluster provider details""" cluster = self._find_cluster(cluster_id) for provider in cluster.providers: if provider.name == provider_name: return provider abort(404, 'No such provider')
def get(self, aid, cid): '''Fetch list of reviews on an assignment based on a criteria''' results = self.dal.get_reviews_by_assignment_criterion(aid,cid) try: return marshal({'reviews':results}, review_list_marshaller), 200 except Exception as e: abort(500, message=str(e))
def find_ou(ou_id): ou = Factory.get('OU')(db.connection) try: ou.find(ou_id) except Errors.NotFoundError: abort(404, message=u"No such OU with entity_id={}".format(ou_id)) return ou
def get(self, aid, cid): """Fetch list of reviews on an assignment based on a criteria""" results = self.dal.get_reviews_by_assignment_criterion(aid, cid) try: return {"reviews": results}, 200 except Exception as e: abort(500, message=str(e))
def get(self, id): """Show user details""" try: user = User.objects.get(id=id) except (User.DoesNotExist, ValidationError): abort(404, message='User does not exist') return user
def get(self, aid, sid, cid, length): '''Summarize reviews given assignment id, reviewee id, criterion id, and length of the summary''' results = self.sum.get_summary_by_assignment_criterion_reviewee(aid,cid,sid, length=length) try: return marshal({'summary':results}, summary_marshaller), 200 except Exception as e: abort(500, message=str(e))
def get(self, cluster_id, service_id): """Run provision""" try: cluster = Cluster.objects.get(id=cluster_id) except: abort(404, 'No such cluster') try: service = Service.objects.get(id=service_id) except: abort(404, 'No such service') task = Task( cluster=cluster, service=service, room=str(current_identity.pk), ) task.save() context = zmq.Context() socket = context.socket(zmq.REQ) socket.connect('tcp://worker:5555') socket.send(str(task.pk)) socket.recv() socket.close() context.term() return task
def get(self, cluster_id, service_id): """Run provision""" try: cluster = Cluster.objects.get(id=cluster_id) except: abort(404, 'No such cluster') try: service = Service.objects.get(id=service_id) except: abort(404, 'No such service') user_id = str(current_identity['id']) user = User.objects.get(id=user_id) provision = Provision( cluster=cluster, service=service, user=user, ) provision.save() context = zmq.Context() socket = context.socket(zmq.REQ) socket.connect('tcp://worker:5555') socket.send(str(provision.pk)) socket.recv() socket.close() context.term() return provision
def get(self, id): """Find task by id""" try: task = Task.objects.get(id=id) except: abort(404, 'No such task') return task
def get(self): """List users""" schema = UserSchema(many=True) response, errors = schema.dump(User.select()) if errors: abort(409, errors) return response
def post(self): db = current_app.extensions['sqlalchemy'].db hj = request.json taxi_json = hj['data'][0] departement = administrative_models.Departement.filter_by_or_404( numero=str(taxi_json['driver']['departement'])) driver = taxis_models.Driver.filter_by_or_404( professional_licence=taxi_json['driver']['professional_licence'], departement_id=departement.id) vehicle = taxis_models.Vehicle.filter_by_or_404( licence_plate=taxi_json['vehicle']['licence_plate']) ads = taxis_models.ADS.filter_by_or_404( numero=taxi_json['ads']['numero'],insee=taxi_json['ads']['insee']) taxi = taxis_models.Taxi.query.filter_by(driver_id=driver.id, vehicle_id=vehicle.id, ads_id=ads.id).first() if taxi_json.get('id', None): if current_user.has_role('admin'): taxi = taxis_models.Taxi.query.get(taxi_json['id']) else: del taxi_json['id'] if not taxi: taxi = taxis_models.Taxi(driver=driver, vehicle=vehicle, ads=ads, id=taxi_json.get('id', None)) #This can happen if this is posted with a admin user if 'status' in taxi_json and taxi.vehicle.description: try: taxi.status = taxi_json['status'] except AssertionError: abort(400, message='Invalid status') db.session.add(taxi) db.session.commit() return {'data':[taxi]}, 201
def get_or_404(cls, hail_id): m = Hail.query.from_statement( text("SELECT * FROM hail where id=:hail_id") ).params(hail_id=hail_id).one() if not m: abort(404, "Unable to find hail: {}".format(hail_id)) return m
def get(self, id): """Get account quarantines.""" args = self.account_quarantines_filter.parse_args() spreads = None if args.context: try: spreads = [int(db.const.Spread(args.context))] except Errors.NotFoundError: abort(404, message=u'Unknown context {!r}'.format( args.context)) ac = find_account(id) qh = QuarantineHandler.check_entity_quarantines( db=db.connection, entity_id=ac.entity_id, spreads=spreads) locked = qh.is_locked() quarantines = [] for q in ac.get_entity_quarantine(only_active=True): quarantines.append({ 'type': q['quarantine_type'], # 'description': q['description'], 'end': q['end_date'], 'start': q['start_date'], # 'disable_until': q['disable_until'], }) return { 'locked': locked, 'quarantines': quarantines }
def get(self, name, context): """ Check if group has context. """ name = name.encode(db.encoding) gr = find_group(name) spread = self.get_spread(context) if not gr.has_spread(spread): abort(404, "No such context on group")
def get(self, aid, sid, cid): '''Fetch reviews given assignment id, reviewee id, and criterion id''' results = self.dal.get_reviews_by_assignment_criterion_reviewee(aid, sid, cid) try: return marshal({'reviews':results}, review_list_marshaller), 200 except Exception as e: abort(500, message=str(e))
def get(self): u = authorize(request) u_id = request.args.get('id',None) username = request.args.get('username',None) # extract information from paramtaters if u_id or username: if u_id and db.exists("USER").where(id=u_id): u_id = int(u_id) elif username and db.exists("USER").where(username=username): u_id = int(db.select("USER").where(username=username).execute()[0]) else: abort(400,'Malformed Request') else: u_id = int(u[0]) # get information u = db.select('USER').where(id=u_id).execute() u_username = u[1] follow_list = text_list_to_set(u[4]) posts_raw = db.select_all('POST').where(author=u_username).execute() posts = [post[0] for post in posts_raw] return { 'username': u[1], 'name': u[2], 'id' : int(u[0]), 'email': u[3], 'following': [int(x) for x in follow_list], 'followed_num': u[5], 'posts': posts }
def get(self, index): if index <= 0 or index >= len(words): abort(404, message='Index out of range.') return words[index - 1]
def get(self, id): opus = Opus.get_by_id(id) # type: Opus if opus is None: abort(404, 'Requested opus not found!') return opus
def unauthorized(message: str): """ Handler function for a unauthorized api access """ log_unauthorized(message) abort(401, message)
def invalid_token(message: str): """ Handler function for a invalid token """ log_unauthorized(message) abort(401, message)
def delete_user(cls, id): if mongo.db.users.delete_one({'_id': ObjectId(id)}).deleted_count: return '', 204 abort(404, 'User not found')
def check_for_ownership(user_id): if g.current_user.id != user_id: abort(403, 'You are not allowed to access the resource')