Esempio n. 1
0
    def get(self, id):
        e = Election.query.get(id)

        if e is None:
            abort(404)

        el_cands = ElectionCandidate.query.filter(ElectionCandidate.election_id.in_([id])).all()
        ec = [el_cand.candidate for el_cand in el_cands]

        ec_ids = [el_cand.id for el_cand in el_cands]

        # candidate votes
        ec_votes = (
            db.session.query(
                func.sum(ElectionCandidateConstituencyVote.votes),
                ElectionCandidateConstituencyVote.election_candidate_id,
            )
            .filter(ElectionCandidateConstituencyVote.election_candidate_id.in_(ec_ids))
            .group_by(ElectionCandidateConstituencyVote.election_candidate_id)
            .order_by(ElectionCandidateConstituencyVote.votes)
            .all()
        )

        ec_votes_fields = [
            [marshal(ElectionCandidate.query.get(ec_vote[1]).candidate, candidate_fields), ec_vote[0]]
            for ec_vote in ec_votes
        ]

        #'candidates': marshal(ec,candidate_fields,

        # e_constituency_result''
        return {"election": marshal(e, election_fields), "candidate_votes": ec_votes_fields}
Esempio n. 2
0
    def get(self, **kwargs):
        """ 资源获取
        :param kwargs:
        :return: dict
        """
        if not self.can_read:
            raise APIMethodNotAllowed

        if kwargs.get('id'):
            item = self.get_item(**kwargs)
            return marshal(item, self.get_model_fields())

        if self.can_paginate:
            pagination = self.get_pagination(**kwargs)
            return {
                'items': marshal(pagination.items, self.get_model_fields()),
                'pagination': self.get_pagination_data(pagination, **kwargs)
            }
        else:
            items = self.get_items(**kwargs)

            if not self.can_empty and not items:
                raise APINotFound

            return marshal(items, self.get_model_fields())
Esempio n. 3
0
    def get(self):

        # handle pagination
        parser = paginageParser.copy()
        parser.add_argument('active', type=str)
        parser.add_argument('patient_id', type=int)
        parser.add_argument('service_id', type=int)

        args = parser.parse_args()
        page = args.get('page')
        limit = args.get('limit')

        active = args.get('active')
        patient_id = args.get('patient_id')
        service_id = args.get('service_id')
        # type = args.get('type')

        # handle search 
        q = request.args.get('q')

        if q:
            return marshal(doctorRepo.search(q), users_fields)

        service = None
        patient = None
        if service_id:
            service = serviceRepo.get( service_id )

        if patient_id:
            patient = patientRepo.get( patient_id )


        result = doctorRepo.getDoctors(patient=patient, service=service, active=active, page=page ,limit=limit)
        return marshal(result, users_fields)
Esempio n. 4
0
    def get(self, contributor, navitia, id=None):
        self.navitia = navitia
        if id:
            return marshal(
                {'disruption': models.Disruption.get(id, contributor.id)},
                one_disruption_fields
            )
        else:
            args = self.parsers['get'].parse_args()
            page_index = args['start_page']
            if page_index == 0:
                abort(400, message="page_index argument value is not valid")
            items_per_page = args['items_per_page']
            if items_per_page == 0:
                abort(400, message="items_per_page argument value is not valid")
            publication_status = args['publication_status[]']
            tags = args['tag[]']
            uri = args['uri']
            statuses = args['status[]']

            g.current_time = args['current_time']
            result = models.Disruption.all_with_filter(
                page_index=page_index,
                items_per_page=items_per_page,
                contributor_id=contributor.id,
                publication_status=publication_status,
                tags=tags,
                uri=uri,
                statuses=statuses
            )
            response = {'disruptions': result.items, 'meta': make_pager(result, 'disruption')}
            return marshal(response, disruptions_fields)
Esempio n. 5
0
    def put(self, id):
        """
	Product id, rating, comment (optional), and time frame (UTC) are
	added to the ProductsRatings table. First we check the id which
	clients wants to rate, is exist or not. Then, we check the entered
	rating is with in our ratings or not.
	"""
	products = [marshal(product, product_fields) for product in 
	                  db.session.query(Products).all()]
        product = [product for product in products if product['product_id'] == id]
	if len(product) == 0:
	    abort(404)
	
	args = self.reqparse.parse_args()
        # retrive the all allowed ratings from database
	allowed_ratings = [marshal(r, rating_field) for r in 
	                          db.session.query(Ratings).all()]
	rating = [ r['rating'] for r in allowed_ratings 
	                       if r['rating'] == int(args['rating'])]
	if len(rating) == 0:
	    return {'result': 'Failed! Please enter your rating betweeen 1 to 5'}
	   # abort(404)
	rating = rating[0]
        product = [product for product in products if product['product_id'] == id]
	product = product[0]
	product_id = id
	comment = args['comment']
	time_frame = datetime.utcnow()
	feedback = ProductsRatings(product_id=product_id, rating=rating,
	                          comment=comment, time_frame=time_frame)
	feedback_add = feedback.add(feedback)
	if not feedback_add:
	    return make_response(jsonify({'result': 'Your rating successfully added'}), 202)
	else:
	    return make_response(jsonify({'result': 'Failed!'}), 400)
Esempio n. 6
0
 def get(self, client, id=None):
     if id:
         response = {'tag': models.Tag.get(id, client.id)}
         return marshal(response, one_tag_fields)
     else:
         response = {'tags': models.Tag.all(client.id), 'meta': {}}
         return marshal(response, tags_fields)
Esempio n. 7
0
    def get(self):

        # handle pagination
        parser = paginageParser.copy()
        parser.add_argument('active', type=str)
        parser.add_argument('employee_id', type=int)
        parser.add_argument('attendanceDate', type=str)

        args = parser.parse_args()
        page = args.get('page')
        limit = args.get('limit')

        active = args.get('active')
        employee_id = args.get('employee_id')
        attendanceDate = args.get('attendanceDate')
        # type = args.get('type')

        # handle search
        q = request.args.get('q')

        if q:
            return marshal(attendanceRepo.search(q), attendances_fields)

        if attendanceDate:
            attendanceRepo.getByDate(attendanceDate)

        if employee_id:
            attendanceRepo.getByEmployee(employee_id)

        if q:
            return marshal(attendanceRepo.search(q), attendances_fields)

        return marshal(attendanceRepo.paginate(page, limit, False), attendances_fields)
Esempio n. 8
0
    def post(self, course_uuid, assignment_uuid):
        course = Course.get_active_by_uuid_or_404(course_uuid)
        assignment = Assignment.get_active_by_uuid_or_404(assignment_uuid)
        require(CREATE, AssignmentComment(course_id=course.id))

        new_assignment_comment = AssignmentComment(assignment_id=assignment.id)

        params = new_assignment_comment_parser.parse_args()

        new_assignment_comment.content = params.get("content")
        if not new_assignment_comment.content:
            return {"error": "The comment content is empty!"}, 400

        new_assignment_comment.user_id = current_user.id

        db.session.add(new_assignment_comment)
        db.session.commit()

        on_assignment_comment_create.send(
            self,
            event_name=on_assignment_comment_create.name,
            user=current_user,
            course_id=course.id,
            assignment_comment=new_assignment_comment,
            data=marshal(new_assignment_comment, dataformat.get_assignment_comment(False)))

        return marshal(new_assignment_comment, dataformat.get_assignment_comment())
Esempio n. 9
0
    def post(self):
        params = new_consumer_parser.parse_args()

        consumer = LTIConsumer()
        require(CREATE, consumer,
            title="Consumer Not Saved",
            message="Sorry, your system role does not allow you to save LTI consumers.")

        consumer.oauth_consumer_key = params.get("oauth_consumer_key")
        consumer.oauth_consumer_secret = params.get("oauth_consumer_secret")
        consumer.global_unique_identifier_param = params.get("global_unique_identifier_param")
        consumer.student_number_param = params.get("student_number_param")

        try:
            db.session.add(consumer)
            db.session.commit()
            on_consumer_create.send(
                self,
                event_name=on_consumer_create.name,
                user=current_user,
                consumer=consumer,
                data={'consumer': marshal(consumer, dataformat.get_lti_consumer())}
            )
        except exc.IntegrityError:
            db.session.rollback()
            abort(409, title="Consumer Not Saved", message="An LTI consumer with the same consumer key already exists. Please double-check the consumer key and try saving again.")

        return marshal(consumer, dataformat.get_lti_consumer(include_sensitive=True))
Esempio n. 10
0
    def get(self):

        # handle pagination
        parser = paginageParser.copy()
        parser.add_argument('patient_id', type=int)
        parser.add_argument('orderDateTime', type=str)
        parser.add_argument('service_id', type=int)
        # parser.add_argument('limit', type=int)

        args = parser.parse_args()
        page = args.get('page')
        limit = args.get('limit')

        patient_id = args.get('patient_id')
        orderDateTime = args.get('orderDateTime')
        service_id = args.get('service_id')

        # handle search 
        q = request.args.get('q')

        if patient_id:
            serviceOrderRepo.addFilter((ServiceOrder.patient_id == patient_id))

        if orderDateTime:
            serviceOrderRepo.addFilter((ServiceOrder.orderDateTime == orderDateTime))

        if service_id:
            serviceOrderRepo.addFilter((ServiceOrder.service_id == service_id))

        if q:
            return marshal([entity for entity in
                            serviceOrderRepo.search(q)], serviceOrder_fields)

        return marshal(serviceOrderRepo.paginate(page, limit, False), serviceOrders_fields)
Esempio n. 11
0
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: flask_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': flask_restful.marshal(data, marshal_table),
	})
    def get(self):
        """
        获取拼车信息
        API请求地址:
        /interaction/api/v2/carpool
        方法: GET
        参数:
        type 可选, 默认为0, 位置: query参数, 0 表示按照拼车id获取拼车信息(即返回指定的单个拼车信息)
        id  位置: query参数, 值意为用户的uid, 或者拼车信息的id(由参数type决定)
        """
        # 决定搜索类型
        self.GET_PARSER.add_argument("type", type=int, location="args")
        self.GET_PARSER.add_argument("id", required=True, type=int, location="args")

        args = self.GET_PARSER.parse_args()
        # 默认按照拼车id寻找
        type_ = args["type"] or self.QUERY_BY_ID
        id_ = args['id']

        if type_ == self.QUERY_BY_ID:
            carpool = common.query_single_by_id(models.Carpool, id_)
            if carpool is not None:
                return marshal(carpool, CARPOOL_STRUCTURE)
            else:
                return {"error": "not found"}, 404
        else:
            carpools = models.Carpool.query\
                .join(models.Passenger, models.Carpool.id == models.Passenger.carpool_id)\
                .filter(models.Passenger.uid == id_)\
                .all()
            if len(carpools) == 0:
                return {"error": "not found"}, 404
            else:
                return marshal(carpools, CARPOOL_STRUCTURE)
Esempio n. 13
0
 def post(self):
     data = request.get_json(force=True)
     userId = data['userId']  # 对方id
     userType = data['userType']  # 对方type
     number = data.get('number')
     if userType == 0:  # 卖家查看买家的评论
         if number:
             OrderComments = OrderComment.query.filter(OrderComment.client_comment != None,
                                                       OrderComment.client_user_id == userId).order_by(
                 OrderComment.client_comment_ts.desc()).limit(number).all()
         else:
             OrderComments = OrderComment.query.filter(OrderComment.client_comment != None,
                                                       OrderComment.client_user_id == userId).order_by(
                 OrderComment.client_comment_ts.desc()).all()
         if OrderComments:
             return jsonify(code='ACK', message='获取买家信息成功', data=marshal(OrderComments, client_orderComment_fields))
         else:
             return jsonify(code='NACK', message='该买家暂未收到评论')
     if userType == 1:  # 买家查看卖家的评论
         if number:
             OrderComments = OrderComment.query.filter(OrderComment.courier_comment != None,
                                                       OrderComment.courier_user_id == userId).order_by(
                 OrderComment.courier_comment_ts.desc()).limit(number).all()
         else:
             OrderComments = OrderComment.query.filter(OrderComment.courier_comment != None,
                                                       OrderComment.courier_user_id == userId).order_by(
                 OrderComment.courier_comment_ts.desc()).all()
         if OrderComments:
             return jsonify(code='ACK', message='获取卖家信息成功', data=marshal(OrderComments, courier_orderComment_fields))
         else:
             return jsonify(code='NACK', message='改卖家暂未收到评论')
Esempio n. 14
0
 def get(self, client, id=None):
     if id:
         response = {'category': models.Category.get(id, client.id)}
         return marshal(response, one_category_fields)
     else:
         response = {'categories': models.Category.all(client.id), 'meta': {}}
         return marshal(response, categories_fields)
Esempio n. 15
0
    def post(self):
        args = self.reqparse.parse_args()

        email = args['email']
        username = args['username']
        user = User.query.filter(db.or_(User.email == email, User.username == username)).first()
        if user:
            return marshal({}, user_fields), 301
        user = User()
        user.id = args['id']
        user.username = username
        user.email = email
        user.head_ico = args['head_ico']
        user.role = args['role']
        user.password = args['password']

        detail_args = self.parse_detail(**args)
        if detail_args:
            user.detail = UserDetail()
            user.detail.id = detail_args['id']
            user.detail.real_name = detail_args['real_name']
            user.detail.intro = detail_args['intro']
        db.session.add(user)
        db.session.commit()
        return {'user': marshal(user.to_dict(), user_fields)}, 201
Esempio n. 16
0
 def get(self, client, id=None):
     if id:
         response = {'channel': models.Channel.get(id, client.id)}
         return marshal(response, one_channel_fields)
     else:
         response = {'channels': models.Channel.all(client.id), 'meta': {}}
         return marshal(response, channels_fields)
Esempio n. 17
0
    def delete(self, client, id):
        property = models.Property.get(client.id, id)

        if property is None:
            return marshal({
                'error': {'message': 'Property {} not found'.format(id)}
            }, error_fields), 404

        can_be_deleted = property.disruptions.filter(
            models.Disruption.status != 'archived',
            models.AssociateDisruptionProperty.disruption_id == models.Disruption.id
        ).count() == 0

        if can_be_deleted:
            db.session.delete(property)
            db.session.commit()
        else:
            return marshal({
                'error': {
                    'message': 'The current {} is linked to at least one disruption\
 and cannot be deleted'.format(property)
                }
            }, error_fields), 409

        return None, 204
Esempio n. 18
0
def format_entity_revision(revision, base):
    entity_revision_fields = structures.ENTITY_REVISION.copy()

    if base is None:
        right = revision.children
    else:
        try:
            right = [db.session.query(Revision).
                     filter_by(revision_id=base).one()]
        except NoResultFound:
            return marshal(revision, entity_revision_fields)

    if revision.entity_data is None:
        return marshal(revision, entity_revision_fields)

    changes = [revision.entity_data.diff(r.entity_data) for r in right]
    if not changes:
        changes = [revision.entity_data.diff(None)]
    data_fields = DATA_MAPPER[type(revision.entity_data)]

    entity_revision_fields['changes'] = \
        fields.List(fields.Nested(data_fields, allow_null=True))
    revision.changes = changes

    return marshal(revision, entity_revision_fields)
Esempio n. 19
0
def format_relationship_revision(revision, base):
    relationship_revision_fields = structures.RELATIONSHIP_REVISION.copy()

    if base is None:
        right = revision.children
    else:
        try:
            right = [db.session.query(Revision).
                     filter_by(revision_id=base).one()]
        except NoResultFound:
            return marshal(revision, relationship_revision_fields)

    if revision.relationship_data is None:
        return marshal(revision, relationship_revision_fields)

    changes = [revision.relationship_data.diff(r.relationship_data)
               for r in right]
    if not changes:
        changes = [revision.relationship_data.diff(None)]

    relationship_revision_fields['changes'] = fields.List(
        fields.Nested(structures.RELATIONSHIP_DIFF, allow_null=True)
    )
    revision.changes = changes

    return marshal(revision, relationship_revision_fields)
Esempio n. 20
0
 def wrapper(*args, **kwargs):
     resp = f(*args, **kwargs)
     if isinstance(resp, tuple):
         data, code, headers = unpack(resp)
         if code != 200 or data.get('success') is False:
             return resp
         return marshal(data, self.fields, self.envelope), code, headers
     else:
         return marshal(resp, self.fields, self.envelope)
Esempio n. 21
0
 def get(self, client, id=None):
     args = self.parsers['get'].parse_args()
     category_id = args['category']
     if id:
         response = {'cause': models.Cause.get(id, client.id, category_id)}
         return marshal(response, one_cause_fields)
     else:
         response = {'causes': models.Cause.all(client.id, category_id), 'meta': {}}
         return marshal(response, causes_fields)
Esempio n. 22
0
def marshal_user_data(user):
    if impersonation.is_impersonating() and current_user.id == user.id:
        # when retrieving the profile of the student being impersonated,
        # don't include full profile (i.e. no email)
        return marshal(user, dataformat.get_user(False))
    elif allow(MANAGE, user) or current_user.id == user.id:
        return marshal(user, dataformat.get_full_user())
    else:
        return marshal(user, dataformat.get_user(is_user_access_restricted(user)))
Esempio n. 23
0
    def get(self, id):
        c = Candidate.query.get(id)

        c.e = [e.election for e in c.elections]
        candidate = {}
        candidate["bio"] = c
        candidate["elections"] = c.elections

        return {"candidate": marshal(c, candidate_fields), "elections": marshal(c.e, election_fields)}
Esempio n. 24
0
    def post(self):
        """
        Create new course
        """
        require(CREATE, Course,
            title="Course Not Saved",
            message="Sorry, your role in the system does not allow you to save courses.")
        params = new_course_parser.parse_args()

        new_course = Course(
            name=params.get("name"),
            year=params.get("year"),
            term=params.get("term"),
            sandbox=params.get("sandbox"),
            start_date=params.get('start_date'),
            end_date=params.get('end_date', None)
        )
        if new_course.start_date is not None:
            new_course.start_date = datetime.datetime.strptime(
                new_course.start_date,
                '%Y-%m-%dT%H:%M:%S.%fZ')

        if new_course.end_date is not None:
            new_course.end_date = datetime.datetime.strptime(
                new_course.end_date,
                '%Y-%m-%dT%H:%M:%S.%fZ')

        if new_course.start_date and new_course.end_date and new_course.start_date > new_course.end_date:
            abort(400, title="Course Not Saved", message="Course end time must be after course start time.")

        try:
            # create the course
            db.session.add(new_course)
            # also need to enrol the user as an instructor
            new_user_course = UserCourse(
                course=new_course,
                user_id=current_user.id,
                course_role=CourseRole.instructor
            )
            db.session.add(new_user_course)

            db.session.commit()

        except exc.SQLAlchemyError as e:
            db.session.rollback()
            current_app.logger.error("Failed to add new course. " + str(e))
            raise

        on_course_create.send(
            self,
            event_name=on_course_create.name,
            user=current_user,
            course=new_course,
            data=marshal(new_course, dataformat.get_course()))

        return marshal(new_course, dataformat.get_course())
Esempio n. 25
0
    def post(self, course_uuid, assignment_uuid, answer_uuid):
        """
        Create comment for an answer
        """
        course = Course.get_active_by_uuid_or_404(course_uuid)
        assignment = Assignment.get_active_by_uuid_or_404(assignment_uuid)
        answer = Answer.get_active_by_uuid_or_404(answer_uuid)
        require(CREATE, AnswerComment(course_id=course.id))

        answer_comment = AnswerComment(answer_id=answer.id)

        params = new_answer_comment_parser.parse_args()
        answer_comment.draft = params.get("draft")
        answer_comment.content = params.get("content")
        # require content not empty if not a draft
        if not answer_comment.content and not answer_comment.draft:
            return {"error": "The comment content is empty!"}, 400

        if params.get("user_id") and current_user.system_role == SystemRole.sys_admin:
            user = User.get_by_uuid_or_404(params.get("user_id"))
            answer_comment.user_id = user.id
        else:
            answer_comment.user_id = current_user.id

        comment_types = [
            AnswerCommentType.public.value,
            AnswerCommentType.private.value,
            AnswerCommentType.evaluation.value,
            AnswerCommentType.self_evaluation.value,
        ]

        comment_type = params.get("comment_type")
        if comment_type not in comment_types:
            abort(400)
        answer_comment.comment_type = AnswerCommentType(comment_type)

        db.session.add(answer_comment)
        db.session.commit()

        # update course & assignment grade for user if self-evaluation is completed
        if not answer_comment.draft and answer_comment.comment_type == AnswerCommentType.self_evaluation:
            assignment.calculate_grade(answer_comment.user)
            course.calculate_grade(answer_comment.user)

        on_answer_comment_create.send(
            self,
            event_name=on_answer_comment_create.name,
            user=current_user,
            course_id=course.id,
            answer_comment=answer_comment,
            data=marshal(answer_comment, dataformat.get_answer_comment(False)),
        )

        return marshal(answer_comment, dataformat.get_answer_comment())
Esempio n. 26
0
    def get(self, audit_id):
        """
            .. http:get:: /api/1/issue/1234

            Get a specific issue

            **Example Request**:

            .. sourcecode:: http

                GET /api/1/issue/1234 HTTP/1.1
                Host: example.com
                Accept: application/json

            **Example Response**:

            .. sourcecode:: http

                HTTP/1.1 200 OK
                Vary: Accept
                Content-Type: application/json

                {
                    justification: null,
                    name: "example_name",
                    issue: "Example Audit Issue",
                    notes: "Example Notes on Audit Issue",
                    auth: {
                        authenticated: true,
                        user: "******"
                    },
                    score: 0,
                    item_id: 704,
                    region: "us-east-1",
                    justified: false,
                    justified_date: null,
                    id: 704
                }

            :statuscode 200: no error
            :statuscode 401: Authentication Error. Please login.
        """

        query = ItemAudit.query.join("item").filter(ItemAudit.id == audit_id)
        result = query.first()

        issue_marshaled = marshal(result, AUDIT_FIELDS)
        item_marshaled = marshal(result.item, ITEM_FIELDS)
        issue_marshaled = dict(
            issue_marshaled.items() +
            item_marshaled.items() +
            {'auth': self.auth_dict}.items()
        )
        return issue_marshaled, 200
Esempio n. 27
0
    def post(self):
        data = request.get_json()

        # This will be valid here, due to authentication.
        user = request.oauth.user
        user.total_revisions += 1
        user.revisions_applied += 1

        entity = self.entity_class()
        entity_data = self.entity_data_class.create(data, db.session)

        if entity_data is None:
            abort(400)

        revision = EntityRevision(user_id=user.user_id)
        revision.entity = entity
        revision.entity_data = entity_data

        note_content = data.get('revision', {}).get('note', '')

        if note_content != '':
            note = RevisionNote(user_id=user.user_id,
                                revision_id=revision.revision_id,
                                content=data['revision']['note'])

            revision.notes.append(note)

        entity.master_revision = revision

        db.session.add(revision)

        # Commit entity, data and revision
        try:
            db.session.commit()
        except IntegrityError:
            # There was an issue with the data we received, so 400
            print traceback.format_exc()
            abort(400)

        entity_out = marshal(revision.entity, structures.ENTITY_EXPANDED)
        data_out = marshal(revision.entity_data, self.entity_data_fields)

        entity_out.update(data_out)

        # Don't 500 if we fail to index; commit still succeeded
        try:
            es_conn = Elasticsearch()
            index_entity(es_conn, entity_out)
        except ElasticsearchException:
            pass

        return marshal(revision, {
            'entity': fields.Nested(self.entity_stub_fields)
        })
Esempio n. 28
0
    def get(self, id):
        """
            .. http:get:: /api/1/auditscores/<int:id>

            Get the overide audit score with given ID.

            **Example Request**:

            .. sourcecode:: http

                GET /api/1/auditscores/123 HTTP/1.1
                Host: example.com
                Accept: application/json, text/javascript

            **Example Response**:

            .. sourcecode:: http

                HTTP/1.1 200 OK
                Vary: Accept
                Content-Type: application/json

                {
                    "id": 123,
                    "method": "check_xxx",
                    "technology": "policy",
                    "score": "1",
                    auth: {
                        authenticated: true,
                        user: "******"
                    }
                }

            :statuscode 200: no error
            :statuscode 404: item with given ID not found
            :statuscode 401: Authentication failure. Please login.
        """

        result = ItemAuditScore.query.filter(ItemAuditScore.id == id).first()

        if not result:
            return {"status": "Override Audit Score with the given ID not found."}, 404

        auditscore_marshaled = marshal(result.__dict__, AUDIT_SCORE_FIELDS)
        auditscore_marshaled['auth'] = self.auth_dict

        account_pattern_scores_marshaled = []
        for account_pattern_score in result.account_pattern_scores:
            account_pattern_score_marshaled = marshal(account_pattern_score, ACCOUNT_PATTERN_AUDIT_SCORE_FIELDS)
            account_pattern_scores_marshaled.append(account_pattern_score_marshaled)
        auditscore_marshaled['account_pattern_scores'] = account_pattern_scores_marshaled

        return auditscore_marshaled, 200
Esempio n. 29
0
    def output(self, key, val):
        if isinstance(val, dict) and 'impacts' in val:
            return marshal(val, {
                'pagination': FieldPaginateImpacts(),
                'impacts': PaginateObjects(fields.Nested(impact_fields, display_null=False))
            }, display_null=False)

        val.impacts = [impact for impact in val.impacts if impact.status == 'published']
        return marshal(val, {
            'pagination': FieldPaginateImpacts(attribute='impacts'),
            'impacts': PaginateObjects(fields.Nested(impact_fields, display_null=False,
                                                    attribute='impacts'))
        }, display_null=False)
Esempio n. 30
0
    def get(self, item_type):
        args = self.parser.parse_args()
        callback = args['callback']
        top_classifys = []
        classifys = []
        for tc, c in db.session.query(TopClassify, Classify).filter(TopClassify.id==Classify.top_classify).filter(TopClassify.item_type==item_type).all():
            #tc_json = json.dumps(marshal(tc, top_classify_fields))
            #c_json = json.dumps(marshal(c, classify_fields))
            #classifys.append({'top_classify':tc_json, 'classify':c_json})
            top_classifys.append(marshal(tc, top_classify_fields))
            classifys.append(marshal(c, classify_fields))

        return json_response(top_classifys=top_classifys, classifys=classifys)
Esempio n. 31
0
 def post(self):
     data = author_parser.parse_args()
     data['created_at'] = datetime.now()
     db.author.insert_one(data)
     return marshal(data, author_field), 201
Esempio n. 32
0
    def execute_query(self,
                      resource_name,
                      query,
                      service_class,
                      filter_args={},
                      sort_args={},
                      search_args={},
                      paging_args={},
                      resource_fields={},
                      operator_args={},
                      from_cache=True,
                      **kwargs):

        resp = {"endpoint": resource_name}
        order_by, asc_desc = sort_args.get("order_by"), sort_args.get(
            "asc_desc")
        page, per_page, error_out = paging_args.get("page"), paging_args.get(
            "per_page"), paging_args.get("error_out")
        search_q = search_args.get("query")
        search_id = search_args.get("id")
        op = operator_args.get("op")

        # TODO implement permission check here
        self.is_permitted()

        # execute limit query:
        query = self.limit_query(query)

        # apply the query filters
        for name, value in filter_args.items():
            query = operator_func(query, service_class, op, name, value)

        # apply sorting
        _sort = sort_func(
            asc_desc)  # Extracts which sorting direction is required
        query = query.order_by(
            _sort(getattr(service_class.model_class, order_by)))

        if self.first_result_only:
            res = query.first()

            if not res:
                abort(404, status='Result not Found', message='')

            output_fields = self.output_fields

            output_fields.update(self.resource_fields)

            return marshal(res, output_fields), 200

        # execute the query and include paging
        paging = query.paginate(page, per_page, error_out)

        resp["order_by"] = order_by
        resp["asc_desc"] = asc_desc
        resp["page"] = paging.page
        resp["total"] = paging.total
        resp["pages"] = paging.pages
        resp["per_page"] = per_page
        resp["op"] = op
        resp["pagers"] = self.pagers
        resp["filters"] = self.filters
        resp["sorters"] = self.sorters

        # extract the request args and modify them for paging
        request_args = copy_dict(request.args, {})

        if paging.has_next:
            # build next page query parameters
            request_args["page"] = paging.next_num
            resp["next"] = paging.next_num
            resp["next_page"] = "%s%s" % ("?", urllib.urlencode(request_args))

        if paging.has_prev:
            # build previous page query parameters
            request_args["page"] = paging.prev_num
            resp["prev"] = paging.prev_num
            resp["prev_page"] = "%s%s" % ("?", urllib.urlencode(request_args))

        output_fields = self.output_fields

        _resource_fields = resource_fields or self.resource_fields

        output_fields.update(_resource_fields)

        resp["results"] = marshal(paging.items, output_fields)

        # TODO: Figure out how to handle exceptions so that it works out well

        return resp, 200
Esempio n. 33
0
 def post(self):
     args = self.reqparse.parse_args()
     tarefa = {'id': tarefa[-1]['id'] + 1, 'title': args['title']}
     tarefas.append(tarefa)
     return {'tarefas    ': marshal(tarefa, campos_tarefas)}, 201
Esempio n. 34
0
 def test_marshal_field(self):
     fields = {'foo': flask_restful.fields.Raw()}
     output = flask_restful.marshal({'foo': 'bar', 'bat': 'baz'}, fields)
     self.assertEquals(output, {'foo': 'bar'})
Esempio n. 35
0
 def get(self):
     new_quotes = [marshal(quote, quote_fields) for quote in models.Quote.select()]
     return (new_quotes, 201)
Esempio n. 36
0
 def get(self):
     todos = [marshal(todos, todo_fields) for todos in models.Todo.select()]
     return todos
Esempio n. 37
0
 def get(self):
     PackageListUpdate.get_os()
     return {'agent': [marshal(host, pack_fields) for host in packs]}
Esempio n. 38
0
 def get(self):
     user = current_token.user
     return {'user': marshal(user.serialize, user_fields)}
Esempio n. 39
0
 def get(self):
     claims = get_jwt_claims()
     qry = Clients.query.get(claims['id'])
     if qry is not None:
         return marshal(qry, Clients.response_fields_jwt), 200, {'Content-Type': 'application/json'}
     return {'status': 'Client Not Found'}, 404, {'Content-Type': 'application/json'}
Esempio n. 40
0
    def post(self):
        if not current_app.config.get('DEMO_INSTALLATION', False):
            abort(
                404,
                title="Demo Accounts Unavailable",
                message=
                "Sorry, the system settings do now allow the use of demo accounts."
            )

        params = new_user_demo_parser.parse_args()

        user = User()
        user.password = "******"

        system_role = params.get("system_role")
        check_valid_system_role(system_role)
        user.system_role = SystemRole(system_role)

        user_count = User.query \
            .filter_by(system_role=user.system_role) \
            .count()
        user_count += 1

        # username
        while True:
            if user.system_role == SystemRole.sys_admin:
                user.username = "******" + str(user_count)
            elif user.system_role == SystemRole.instructor:
                user.username = "******" + str(user_count)
            else:
                user.username = "******" + str(user_count)

            username_exists = User.query.filter_by(
                username=user.username).first()
            if not username_exists:
                break
            else:
                user_count += 1

        if user.system_role == SystemRole.sys_admin:
            user.firstname = "Admin"
            user.lastname = str(user_count)
            user.displayname = "Admin " + str(user_count)
        elif user.system_role == SystemRole.instructor:
            user.firstname = "Instructor"
            user.lastname = str(user_count)
            user.displayname = "Instructor " + str(user_count)

            # create new enrollment
            new_user_course = UserCourse(user=user,
                                         course_id=1,
                                         course_role=CourseRole.instructor)
            db.session.add(new_user_course)
        else:
            user.firstname = "Student"
            user.lastname = str(user_count)
            user.displayname = display_name_generator()

            while True:
                user.student_number = random_generator(8, string.digits)
                student_number_exists = User.query.filter_by(
                    student_number=user.student_number).first()
                if not student_number_exists:
                    break

            # create new enrollment
            new_user_course = UserCourse(user=user,
                                         course_id=1,
                                         course_role=CourseRole.student)
            db.session.add(new_user_course)

        try:
            db.session.add(user)
            db.session.commit()
            on_user_demo_create.send(self,
                                     event_name=on_user_demo_create.name,
                                     user=current_user,
                                     data=marshal(user,
                                                  dataformat.get_user(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

        authenticate(user, login_method="Demo")

        return marshal(user, dataformat.get_user())
Esempio n. 41
0
 def get(self, id):
     qry = ProductTypes.query.get(id)
     if qry is not None:
         return marshal(qry, ProductTypes.response_field), 200
     return {'status': 'NOT_FOUND'}, 404
Esempio n. 42
0
 def get(self):
     schemas = models.Schema.query.filter_by()
     data = [marshal(schema, schema_fields) for schema in schemas]
     return {'data': data}, HTTP_OK
Esempio n. 43
0
 def marshal_response(*args, **kwargs):
     return marshal(func(*args, **kwargs), ListResponse.resource_fields)
Esempio n. 44
0
    def patch(self, id):
        movie = MovieModel.query.get(id)
        if not movie:
            abort(404, message='没有此电影信息')

        movie_patch_parser_args = movie_patch_parser.parse_args()
        show_name = movie_patch_parser_args.get('show_name') or movie.show_name
        show_name_en = movie_patch_parser_args.get(
            'show_name_en') or movie.show_name_en
        director = movie_patch_parser_args.get('director') or movie.director
        leading_role = movie_patch_parser_args.get(
            'leading_role') or movie.leading_role
        movie_type = movie_patch_parser_args.get('type') or movie.type
        country = movie_patch_parser_args.get('country') or movie.country
        language = movie_patch_parser_args.get('language') or movie.language
        duration = movie_patch_parser_args.get('duration') or movie.duration
        screening_model = movie_patch_parser_args.get(
            'screening_model') or movie.screening_model
        flag = movie_patch_parser_args.get('flag') or movie.flag
        is_delete = movie_patch_parser_args.get(
            'is_delete') if movie_patch_parser_args.get(
                'is_delete') is None else movie.is_delete

        if bool(movie_patch_parser_args.get('is_delete')) != movie.is_delete:
            is_delete = not movie.is_delete

        open_day = movie_patch_parser_args.get(
            'open_day') if movie_patch_parser_args.get(
                'open_day') else movie.open_day

        background_picture = movie_patch_parser_args.get(
            'background_picture') or movie.background_picture

        if movie_patch_parser_args.get('background_picture'):
            old_background_picture = os.path.join(
                current_app.config.get('PROJECT_PATH'),
                movie.background_picture)
            if not del_file(old_background_picture):
                abort(400, message='更换电影背景图失败')

            new_filename, path = uploads_images_path(
                filename=background_picture.filename)
            movie.background_picture = os.path.join(
                current_app.config.get('UPLOADS_IMAGES_REL_PATH'),
                new_filename)
            background_picture.save(
                os.path.join(current_app.config.get('UPLOADS_IMAGES_PATH'),
                             new_filename))

        movie.show_name = show_name
        movie.show_name_en = show_name_en
        movie.director = director
        movie.leading_role = leading_role
        movie.type = movie_type
        movie.country = country
        movie.language = language
        movie.duration = duration
        movie.screening_model = screening_model
        movie.open_day = open_day
        movie.flag = flag
        movie.is_delete = is_delete
        if not movie.save():
            abort(400, message='修改电影信息失败')

        data = {
            'status': current_app.config.get('HTTP_CREATE_OK'),
            'msg': '成功更新一条电影信息',
            'data': marshal(movie, movie_field),
        }
        return data
Esempio n. 45
0
 def wrap_list_items(response):
     wrapped_items = self.wrap_with_response_object(response.items)
     response.items = marshal(wrapped_items, fields_to_include)
     return response
Esempio n. 46
0
    def put(self, book_id):
        # Take input from users
        parser = reqparse.RequestParser()
        parser.add_argument('id_kategori', location = 'json', required = True, type = int)
        parser.add_argument('judul', location = 'json', required = True)
        parser.add_argument('penerbit', location = 'json', required = True)
        parser.add_argument('nomor_isbn', location = 'json', required = True)
        parser.add_argument('id_penulis', location = 'json', required = True, type = list)
        args = parser.parse_args()

        # Check emptyness
        if (
            args['id_kategori'] == '' or args['id_kategori'] is None
            or args['judul'] == '' or args['judul'] is None
            or args['penerbit'] == '' or args['penerbit'] is None
            or args['nomor_isbn'] == '' or args['nomor_isbn'] is None
            or args['id_penulis'] == [] or args['id_penulis'] == '' or args['id_penulis'] is None
        ):
            return {'pesan': 'Tidak boleh ada kolom yang dikosongkan'}, 400
        
        # Check duplicate ISBN
        related_book = Buku.query.filter_by(id = book_id).first()
        duplicate_isbn = Buku.query.filter_by(nomor_isbn = args['nomor_isbn']).first()
        if duplicate_isbn is not None and duplicate_isbn.nomor_isbn != related_book.nomor_isbn:
            return {'pesan': 'Buku dengan nomor ISBN tersebut sudah ada di database'}, 409
        
        # ----- Edit record in database -----
        # Search for the book
        if related_book is None:
            return {'pesan': 'Buku yang ingin kamu edit tidak ditemukan'}, 404

        # Check the existence of writer
        writers = []
        for writer_id in args['id_penulis']:
            # Check whether the id exists or not
            related_writer = Penulis.query.filter_by(id = writer_id).first()
            if related_writer is None:
                return {'pesan': 'Penulis dengan nomor ID ' + writer_id + ' tidak ada'}, 400
            writers.append(related_writer.nama)
        writers = ", ".join(writers)
        
        # Edit the record in "Buku" table
        related_book.id_kategori = args['id_kategori']
        related_book.judul = args['judul']
        related_book.penerbit = args['penerbit']
        related_book.nomor_isbn = args['nomor_isbn']
        related_book.updated_at = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        db.session.commit()

        # Remove the old record in "PenulisBuku" table
        old_book_writers = PenulisBuku.query.filter_by(id_buku = book_id)
        for old_book_writer in old_book_writers:
            db.session.delete(old_book_writer)
            db.session.commit()
        
        # Add new record in "PenulisBuku" table
        for writer_id in args['id_penulis']:
            new_record = PenulisBuku(book_id, writer_id)
            db.session.add(new_record)
            db.session.commit()

        # Return the result
        related_book = marshal(related_book, Buku.response_fields)
        related_book['penulis'] = writers
        return {'pesan': 'Sukses mengubah informasi buku', 'buku': related_book}, 200
Esempio n. 47
0
 def get(self):
     return {'agent': [marshal(host, pack_fields) for host in packs]}
Esempio n. 48
0
    def get(self, id=None):
        current_user = get_jwt_identity()

        if (id != None):
            qry = Posting.query.filter_by(user_UserID=current_user)
            qry = qry.filter_by(PostID=id)
            posts = marshal(qry.first(), posting_field)

            qry = Comment.query.filter_by(posting_PostID=id)
            comments = marshal(qry.all(), comment_field)

            if posts["Title"] == None:
                return {'status': 'Post not found!'}, 404

            else:
                postComm = {"Post": posts, "Comment": comments}
                return postComm, 200

        parser = reqparse.RequestParser()
        parser.add_argument("p", type=int, location='args', default=1)
        parser.add_argument("rp", type=int, location='args', default=5)
        parser.add_argument("PostID",
                            type=int,
                            help='PostID must be an integer',
                            location='args')
        parser.add_argument("Title",
                            type=str,
                            help='Title must be string type',
                            location='args')
        parser.add_argument("Likes",
                            type=str,
                            help='Likes must be an integer',
                            location='args')
        parser.add_argument("Watch",
                            type=str,
                            help='Watch must be string type',
                            location='args')
        parser.add_argument("user_UserID",
                            type=int,
                            help='user_UserID must be an integer',
                            location='args')
        parser.add_argument("orderBy",
                            help='invalid orderBy',
                            location='args',
                            choices=('PostID', 'Title', 'Likes', 'Watch',
                                     'CreatedAt', 'UpdatedAt', 'user_UserID'))
        parser.add_argument("sort",
                            help='invalid sort value',
                            location='args',
                            choices=('asc', 'desc'),
                            default='asc')

        args = parser.parse_args()

        qry = Posting.query.filter_by(user_UserID=current_user)

        if args['p'] == 1:
            offset = 0
        else:
            offset = (args['p'] * args['rp']) - args['rp']

        if args["PostID"] != None:
            qry = qry.filter_by(PostID=args["PostID"])
        if args["Title"] != None:
            qry = qry.filter_by(Title=args["Title"])
        if args["Likes"] != None:
            qry = qry.filter_by(Likes=args["Likes"])
        if args["Watch"] != None:
            qry = qry.filter_by(Watch=args["Watch"])

        if args['orderBy'] != None:

            if args["orderBy"] == "PostID":
                field_sort = Posting.PostID
            elif args["orderBy"] == "Title":
                field_sort = Posting.Title
            elif args["orderBy"] == "Likes":
                field_sort = Posting.Likes
            elif args["orderBy"] == "Watch":
                field_sort = Posting.Watch
            elif args["orderBy"] == "CreatedAt":
                field_sort = Posting.CreatedAt
            elif args["orderBy"] == "UpdatedAt":
                field_sort = Posting.UpdatedAt
            elif args["orderBy"] == "user_UserID":
                field_sort = Posting.user_UserID

            if args['sort'] == 'desc':
                qry = qry.order_by(desc(field_sort))

            else:
                qry = qry.order_by(field_sort)

        rows = qry.count()
        qry = qry.limit(args['rp']).offset(offset)
        tp = math.ceil(rows / args['rp'])

        ans = {
            "page": args['p'],
            "total_page": tp,
            "per_page": args['rp'],
            "data": []
        }

        rows = []
        for row in qry.all():
            rows.append(marshal(row, posting_field))

        ans["data"] = rows

        return ans, 200
    def patch(self, id):
        #check id in querry or not
        qry_file_subject = FilesSubject.query.filter_by(status=True).filter_by(
            id=id).first()
        if qry_file_subject is None:
            return {'status': 'File Subject is NOT_FOUND'}, 404

        parser = reqparse.RequestParser()
        parser.add_argument("subject_id", location="form")
        parser.add_argument("name", location="form")
        parser.add_argument("content_file",
                            type=werkzeug.datastructures.FileStorage,
                            location='files')
        parser.add_argument("category_file",
                            location="form",
                            help='category file not available',
                            choices=("presentation", "video"))
        args = parser.parse_args()

        if args['subject_id'] is not None:
            qry_file_subject.subject_id = args["subject_id"]

        if args['name'] is not None:
            qry_file_subject.name = args["name"]

        if args['content_file'] is not None:
            #Check content file subject in query
            if qry_file_subject.content_file is not None:
                filename = qry_file_subject.content_file

                #Remove content file subject in storage
                if qry_file_subject.category_file == "presentation":
                    UPLOAD_FOLDER = app.config["UPLOAD_MEDIA_PRESENTATION"]
                elif qry_file_subject.category_file == "video":
                    UPLOAD_FOLDER = app.config["UPLOAD_MEDIA_VIDEO"]

                os.remove(os.path.join("." + UPLOAD_FOLDER, filename))

                content_file = args["content_file"]

                #Change content file subject in storage
                if content_file:
                    if args["category_file"] == "presentation":
                        UPLOAD_FOLDER = app.config["UPLOAD_MEDIA_PRESENTATION"]
                    elif args["category_file"] == "video":
                        UPLOAD_FOLDER = app.config["UPLOAD_MEDIA_VIDEO"]

                    randomstr = uuid.uuid4().hex
                    filename = randomstr + "_" + content_file.filename
                    content_file.save(
                        os.path.join("." + UPLOAD_FOLDER, filename))

                qry_file_subject.content_file = filename

            else:
                if args["category_file"] == "presentation":
                    UPLOAD_FOLDER = app.config["UPLOAD_MEDIA_PRESENTATION"]
                elif args["category_file"] == "video":
                    UPLOAD_FOLDER = app.config["UPLOAD_MEDIA_VIDEO"]

                content_file = args["content_file"]

                #Change content file subject in storage
                if content_file:
                    randomstr = uuid.uuid4().hex
                    filename = randomstr + "_" + content_file.filename
                    content_file.save(
                        os.path.join("." + UPLOAD_FOLDER, filename))

                qry_file_subject.content_file = filename

        if args['category_file'] is not None:
            qry_file_subject.category_file = args["category_file"]

        db.session.commit()

        return marshal(qry_file_subject, FilesSubject.response_fields), 200
Esempio n. 50
0
 def get(self):
     prov = [
         marshal(prov, prov_fields) for prov in models.GeoProvinsi.select()
     ]
     return {'success': True, 'data': prov}
Esempio n. 51
0
    def post(self, obj_id=None, resource_name=None):
        """ Execute a post request based on criteria given by the above parameters.
            If obj_id isn't passed. It implies a create function call. If there's an obj_id, it implies and update.
            if resource_name is passed, it implies a sub update method call
            It also contains logic for a bulk update
         """

        # extract bulk ids from the list to see how it works
        group_args = self.group_parser()
        obj_ids = group_args.get("group_ids", None)

        if obj_id is None and obj_ids is None:
            # when obj_id isn't passed, this executes the save function call
            self.is_permitted()  # check if you're permitted first
            attrs, files = self.validate(self.validation_form,
                                         adjust_func=self.adjust_form_fields)

            # update the form data using this interceptor. i.e inject a domain group id (merchant_id, courier_id etc.)
            attrs = self.adjust_form_data(attrs)

            try:
                res = self.save(attrs,
                                files)  # execute save method [self.save()]
                output_fields = self.output_fields
                output_fields.update(self.resource_fields or {})

                return marshal(res, output_fields), 201
            except Exception as e:
                raise IntegrityException(e)

        elif obj_id is not None and resource_name is None:
            # when an obj_id is passed but resource_name doesn't exist, this implies an update method call
            obj = self.service_class.get(obj_id)
            obj = self.is_permitted(obj)  # check if you're permitted first
            attrs, files = self.validate(self.validation_form,
                                         obj=obj,
                                         adjust_func=self.adjust_form_fields)
            attrs = self.adjust_form_data(attrs)
            try:
                res = self.update(
                    obj_id, attrs,
                    files)  # execute update method [self.update()]
                output_fields = self.output_fields
                output_fields.update(self.resource_fields or {})

                return marshal(res, output_fields), 201
            except Exception as e:
                logger.error(e)
                raise IntegrityException(e)

        elif obj_id is not None and resource_name is not None:
            # when obj_id is passed along with a resource_name. this implies a do_method call.
            obj = self.service_class.get(obj_id)
            self.is_permitted(obj)  # check if you're permitted first

            adjust_func = getattr(self,
                                  "%s_adjust_form_fields" % resource_name,
                                  None)
            do_method = getattr(self, "do_%s" % resource_name, None)
            validation_form = getattr(self,
                                      "%s_validation_form" % resource_name,
                                      None)

            if do_method is None:
                abort(
                    405,
                    status="Not Authorized",
                    message=
                    "The requested resource is not yet authorized for access")

            try:
                attrs = request.data or {}
                files = None

                # if there is a validation form, use it
                if validation_form:
                    attrs, files = self.validate(validation_form,
                                                 obj,
                                                 adjust_func=adjust_func)
                    attrs = self.adjust_form_data(attrs)

                res = do_method(
                    obj_id, attrs,
                    files)  # Functionality for saving data implemented here
                output_fields = self.output_fields
                output_fields.update(self.resource_fields or {})

                return marshal(res, output_fields), 201
            except Exception:
                raise

        elif obj_id is None and resource_name is None and obj_ids is not None:
            # attempting a bulk update. only occurs when bulk_ids values are present and there's not obj_id
            self.is_permitted()  # check if you're permitted first

            # cannot use validation form here, values will be derived from an update parser
            attrs = self.group_action_parser()
            files = None

            try:
                resp, status = self.execute_group_action(obj_ids, attrs, files)

                return resp, status
            except Exception as e:

                raise IntegrityException(e)
    def post(self):
        """
            .. http:post:: /api/1/ignorelistentries

            Create a new ignore list entry.

            **Example Request**:

            .. sourcecode:: http

                POST /api/1/ignorelistentries HTTP/1.1
                Host: example.com
                Accept: application/json

                {
                    "prefix": "noisy_",
                    "notes": "Security Monkey shouldn't track noisy_* objects",
                    "technology": "securitygroup"
                }

            **Example Response**:

            .. sourcecode:: http

                HTTP/1.1 201 Created
                Vary: Accept
                Content-Type: application/json

                {
                    "id": 123,
                    "prefix": "noisy_",
                    "notes": "Security Monkey shouldn't track noisy_* objects",
                    "technology": "securitygroup"
                }

            :statuscode 201: created
            :statuscode 401: Authentication Error. Please Login.
        """

        self.reqparse.add_argument(
            'prefix',
            required=True,
            type=text_type,
            help=
            'A prefix must be provided which matches the objects you wish to ignore.',
            location='json')
        self.reqparse.add_argument('notes',
                                   required=False,
                                   type=text_type,
                                   help='Add context.',
                                   location='json')
        self.reqparse.add_argument('technology',
                                   required=True,
                                   type=text_type,
                                   help='Technology name required.',
                                   location='json')
        args = self.reqparse.parse_args()

        prefix = args['prefix']
        technology = args.get('technology', True)
        notes = args.get('notes', None)

        entry = IgnoreListEntry()
        entry.prefix = prefix

        if notes:
            entry.notes = notes

        technology = Technology.query.filter(
            Technology.name == technology).first()
        if not technology:
            return {
                "status": "Could not find a technology with the given name"
            }, 500

        entry.tech_id = technology.id

        db.session.add(entry)
        db.session.commit()
        db.session.refresh(entry)

        ignorelistentry_marshaled = marshal(entry.__dict__, IGNORELIST_FIELDS)
        ignorelistentry_marshaled['technology'] = entry.technology.name
        ignorelistentry_marshaled['auth'] = self.auth_dict
        return ignorelistentry_marshaled, 201
Esempio n. 53
0
 def get(self, id_tarefa):
     tarefa = [tarefa for tarefa in tarefas if tarefa['id'] == id_tarefa]
     if len(tarefa) == 0:
         abort(404)
     return {'tarefa': marshal(tarefa[0], campos_tarefas)}
    def get(self):
        """
            .. http:get:: /api/1/ignorelistentries

            Get a list of Ignorelist entries.

            **Example Request**:

            .. sourcecode:: http

                GET /api/1/ignorelistentries HTTP/1.1
                Host: example.com
                Accept: application/json, text/javascript

            **Example Response**:

            .. sourcecode:: http

                HTTP/1.1 200 OK
                Vary: Accept
                Content-Type: application/json

                {
                    count: 1,
                    items: [
                        {
                            "id": 123,
                            "prefix": "noisy_",
                            "notes": "Security Monkey shouldn't track noisy_* objects",
                            "technology": "securitygroup"
                        },
                    ],
                    total: 1,
                    page: 1,
                    auth: {
                        authenticated: true,
                        user: "******"
                    }
                }

            :statuscode 200: no error
            :statuscode 401: Authentication failure. Please login.
        """

        self.reqparse.add_argument('count',
                                   type=int,
                                   default=30,
                                   location='args')
        self.reqparse.add_argument('page',
                                   type=int,
                                   default=1,
                                   location='args')

        args = self.reqparse.parse_args()
        page = args.pop('page', None)
        count = args.pop('count', None)

        result = IgnoreListEntry.query.order_by(IgnoreListEntry.id).paginate(
            page, count, error_out=False)

        items = []
        for entry in result.items:
            ignorelistentry_marshaled = marshal(entry.__dict__,
                                                IGNORELIST_FIELDS)
            ignorelistentry_marshaled["technology"] = entry.technology.name
            items.append(ignorelistentry_marshaled)

        marshaled_dict = {
            'total': result.total,
            'count': len(items),
            'page': result.page,
            'items': items,
            'auth': self.auth_dict
        }
        return marshaled_dict, 200
Esempio n. 55
0
 def get(self):
     # dates = Bing.query.filter_by()
     return Common.returnTrueJson(
         Common, marshal(Bing.query.all(), resource_full_fields))
    def put(self, item_id):
        """
            .. http:get:: /api/1/ignorelistentries/<int:id>

            Update the ignorelist entry with the given ID.

            **Example Request**:

            .. sourcecode:: http

                PUT /api/1/ignorelistentries/123 HTTP/1.1
                Host: example.com
                Accept: application/json, text/javascript

                {
                    "id": 123,
                    "prefix": "noisy_",
                    "notes": "Security Monkey shouldn't track noisy_* objects",
                    "technology": "securitygroup"
                }

            **Example Response**:

            .. sourcecode:: http

                HTTP/1.1 200 OK
                Vary: Accept
                Content-Type: application/json

                {
                    "id": 123,
                    "prefix": "noisy_",
                    "notes": "Security Monkey shouldn't track noisy_* objects",
                    "technology": "securitygroup",
                    auth: {
                        authenticated: true,
                        user: "******"
                    }
                }

            :statuscode 200: no error
            :statuscode 404: item with given ID not found
            :statuscode 401: Authentication failure. Please login.
        """

        self.reqparse.add_argument(
            'prefix',
            required=True,
            type=text_type,
            help=
            'A prefix must be provided which matches the objects you wish to ignore.',
            location='json')
        self.reqparse.add_argument('notes',
                                   required=False,
                                   type=text_type,
                                   help='Add context.',
                                   location='json')
        self.reqparse.add_argument('technology',
                                   required=True,
                                   type=text_type,
                                   help='Technology name required.',
                                   location='json')
        args = self.reqparse.parse_args()

        prefix = args['prefix']
        technology = args.get('technology', True)
        notes = args.get('notes', None)

        result = IgnoreListEntry.query.filter(
            IgnoreListEntry.id == item_id).first()

        if not result:
            return {
                "status": "Ignore list entry with the given ID not found."
            }, 404

        result.prefix = prefix
        result.notes = notes

        technology = Technology.query.filter(
            Technology.name == technology).first()
        if not technology:
            return {
                "status": "Could not find a technology with the given name"
            }, 500

        result.tech_id = technology.id

        db.session.add(result)
        db.session.commit()
        db.session.refresh(result)

        ignorelistentry_marshaled = marshal(result.__dict__, IGNORELIST_FIELDS)
        ignorelistentry_marshaled['technology'] = result.technology.name
        ignorelistentry_marshaled['auth'] = self.auth_dict

        return ignorelistentry_marshaled, 200
Esempio n. 57
0
 def get(self):
     courses = [
         marshal(add_reviews(course), course_fields)
         for course in models.Course.select()
     ]
     return {'courses': courses}
Esempio n. 58
0
 def get(self):
     """Get all existing Todo items"""
     todos = [marshal(todo, todo_fields) for todo in models.Todo.select()]
     return todos, 200, {'Location': url_for('resources.todos.todos')}
Esempio n. 59
0
    def post(self, org_id, location_id, role_id):
        """
        create a new shift
        """

        parser = reqparse.RequestParser()
        parser.add_argument("start", type=str, required=True)
        parser.add_argument("stop", type=str, required=True)
        parser.add_argument("user_id", type=int)
        parser.add_argument("published", type=inputs.boolean)
        parser.add_argument("description", type=str)
        parameters = parser.parse_args()

        # Filter out null values
        parameters = dict((k, v) for k, v in parameters.iteritems()
                          if v is not None)

        default_tz = get_default_tz()
        local_tz = Location.query.get(location_id).timezone_pytz

        # start time
        try:
            start = iso8601.parse_date(parameters.get("start"))
        except iso8601.ParseError:
            return {
                "message": "Start time needs to be in ISO 8601 format"
            }, 400
        else:
            start = (start + start.utcoffset()).replace(tzinfo=default_tz)

        # stop time
        try:
            stop = iso8601.parse_date(parameters.get("stop"))
        except iso8601.ParseError:
            return {"message": "Stop time needs to be in ISO 8601 format"}, 400
        else:
            stop = (stop + stop.utcoffset()).replace(tzinfo=default_tz)

        # stop can't be before start
        if start >= stop:
            return {"message": "Stop time must be after start time"}, 400

        # shifts are limited to 23 hours in length
        if int((stop - start).total_seconds()) > MAX_SHIFT_LENGTH:
            return {
                "message":
                "Shifts cannot be more than %s hours long" %
                (MAX_SHIFT_LENGTH / SECONDS_PER_HOUR)
            }, 400

        shift = Shift2(
            role_id=role_id,
            start=start,
            stop=stop,
            published=parameters.get("published", False))

        if "description" in parameters:
            description = parameters.get("description")

            if len(description) > Shift2.MAX_DESCRIPTION_LENGTH:
                return {
                    "message":
                    "Description cannot me more than %s characters" %
                    Shift2.MAX_DESCRIPTION_LENGTH
                }, 400

            shift.description = description

        user_id = parameters.get("user_id")

        # if user_id defined, and if not for unassigned shift, check if user is in role
        # and make sure it won't overlap with existing shifts
        if user_id is not None:
            if user_id > 0:
                role_to_user = RoleToUser.query.filter_by(
                    user_id=user_id, role_id=role_id, archived=False).first()

                if role_to_user is None:
                    return {
                        "message":
                        "User does not exist or is not apart of role"
                    }, 400

                # check if this shift can be assigned to the user
                shift.user_id = user_id

                if shift.has_overlaps():
                    return {
                        "message": "This shift overlaps with an existing shift"
                    }, 400

        db.session.add(shift)
        try:
            db.session.commit()
        except:
            abort(500)

        g.current_user.track_event("created_shift")

        # check if a schedule exists during this time - if so, bust the cache
        schedule = Schedule2.query \
            .filter(
                Schedule2.role_id == role_id,
                Schedule2.start <= shift.start,
                Schedule2.stop > shift.start,
            ).first()

        if schedule is not None:
            Shifts2Cache.delete(schedule.id)

        # timezone stuff
        local_datetime = default_tz.localize(shift.start).astimezone(local_tz)

        # only send emails if future and published
        if not shift.is_in_past and shift.published:

            # if shift is unassigned - alert people that it's available
            if shift.user_id is None:

                # get all users who are eligible for the shift
                eligible_users, _ = shift.eligible_users()

                alert_available_shifts(org_id, location_id, role_id,
                                       local_datetime, eligible_users)

            # Otherwise send an alert_changed_shift notification
            # (function has logic for whether to send)
            elif (g.current_user.id != shift.user_id):
                alert_changed_shift(org_id, location_id, role_id,
                                    local_datetime, shift.user_id)

        return marshal(shift, shift_fields), 201
Esempio n. 60
0
    def get(self, org_id, location_id, role_id):
        # NOTE - we always include user's name with shifts. This helps the front-end.

        parser = reqparse.RequestParser()
        parser.add_argument("start", type=str, required=True)
        parser.add_argument("end", type=str, required=True)
        parser.add_argument("user_id", type=int)
        parser.add_argument("csv_export", type=inputs.boolean, default=False)
        parser.add_argument(
            "include_summary", type=inputs.boolean, default=False)
        parser.add_argument(
            "filter_by_published", type=inputs.boolean, default=False)
        parameters = parser.parse_args(
        )  # Strict breaks calls from parent methods? Sigh.

        # Filter out null values
        parameters = dict((k, v) for k, v in parameters.iteritems()
                          if v is not None)

        default_tz = get_default_tz()

        shifts = Shift2.query.filter_by(role_id=role_id)

        # start and end must be supplied - check if in ok format
        try:
            start = iso8601.parse_date(parameters.get("start"))
        except iso8601.ParseError:
            return {
                "message":
                "Start time parameter needs to be in ISO 8601 format"
            }, 400
        else:
            start = (start + start.utcoffset()).replace(tzinfo=default_tz)

        try:
            end = iso8601.parse_date(parameters.get("end"))
        except iso8601.ParseError:
            return {
                "message":
                "End time parameter time needs to be in ISO 8601 format"
            }, 400
        else:
            end = (end + end.utcoffset()).replace(tzinfo=default_tz)

        shifts = shifts \
            .filter(
                Shift2.start < end,
                Shift2.start >= start,
            )

        if "user_id" in parameters:
            user_id_value = parameters["user_id"]
            if user_id_value == 0:
                user_id_value = None

            shifts = shifts.filter_by(user_id=user_id_value)

        # filter by only published shifts
        if parameters.get("filter_by_published"):
            shifts = shifts.filter_by(published=True)

        # now execute the query
        shifts = shifts \
            .order_by(
                Shift2.start.asc(),
            ) \
            .all()

        # determine if csv export
        if parameters.get("csv_export"):

            csv_rows = [self.CSV_HEADER]

            role_name = Role.query.get_or_404(role_id).name
            download_name = "shifts-%s-%s-%s.csv" % (role_name, start, end)

            for shift in shifts:
                if shift.user_id is None:
                    user_name = "Unassigned Shift"
                    shift_status = "open"
                else:
                    user = User.query.get_or_404(shift.user_id)

                    user_name = user.name if user.name else user.email
                    shift_status = "closed"

                start_date = shift.start.strftime("%-m/%-d/%y")
                start_time = shift.start.strftime("%-I%p")
                stop_date = shift.stop.strftime("%-m/%-d/%y")
                stop_time = shift.stop.strftime("%-I%p")
                open_value = 1 if shift_status == "open" else ""

                csv_rows.append('"%s","%s","%s","%s","%s","%s","","%s","%s"' %
                                (user_name, role_name, start_date, stop_date,
                                 start_time, stop_time, shift_status,
                                 open_value))

            response = make_response("\n".join(csv_rows))
            response.headers[
                "Content-Disposition"] = "attachment; filename=%s" % download_name

            return response

        output = {
            API_ENVELOPE:
            map(lambda shift: marshal(shift, shift_fields), shifts)
        }

        if parameters.get("include_summary"):
            users_summary = {}

            for shift in shifts:
                user_id = shift.user_id if shift.user_id else 0

                if user_id in users_summary.keys():
                    users_summary[user_id]["shifts"] += 1
                    users_summary[user_id]["minutes"] += int(
                        (shift.stop - shift.start).total_seconds() / 60)
                else:
                    if user_id == 0:
                        name = "Unassigned shifts"
                    else:
                        user = User.query.get_or_404(shift.user_id)
                        name = user.name if user.name else user.email

                    users_summary[user_id] = {
                        "user_id":
                        user_id,
                        "user_name":
                        name,
                        "shifts":
                        1,
                        "minutes":
                        int((shift.stop - shift.start).total_seconds() / 60)
                    }

            output["summary"] = users_summary.values()

        return output