Example #1
0
class Match(HTTPEndpoint):
    @use_args(
        {
            "players": fields.Dict(required=True),
            "maps": fields.Dict(required=True),
            "team_names": fields.Dict(required=True),
        }, )
    async def post(self, request, args):
        """ Creates match. """

        return responder.render(await
                                request.state.league.match().create(**args))

    @use_args({
        "match_id": fields.String(required=True),
    })
    async def delete(self, request, args):
        """ Deletes match. """

        return responder.render(await request.state.league.match(**args).end())

    @use_args({
        "match_id": fields.String(required=True),
    })
    async def get(self, request, args):
        """ Gets base details of match. """

        return responder.render(await request.state.league.match(**args).get())
Example #2
0
    class FilterSchema(Schema):
        query = fields.Dict(missing=dict)
        view = fields.Nested(ViewSchema, missing=dict)
        schema = fields.String(missing='__schema__')

        class Meta:
            strict = True
Example #3
0
class Prediction(Resource):
    @use_args({
        "dataset":
        fields.Str(required=True),
        "query":
        fields.Dict(keys=fields.Str, values=fields.Float, required=True)
    })
    def post(self, args):
        try:
            dataset_meta = DatasetMeta.objects.raw({"_id": args["dataset"]})
            target_meta = dataset_meta.first().as_dict()
            if strip_neural_meta(target_meta["keys"]) != set(
                    args["query"].keys()):
                return {"error": "wrong keys for the specified dataset"}, 422
            if args["dataset"] != classifier.dataset:
                data = get_dataset(args["dataset"])
                logging.info(
                    "Starting the training session with dataset {}".format(
                        args["dataset"]))
                classifier.train(args["dataset"], list(target_meta["keys"]),
                                 data)
            stripped_keys = list(strip_neural_meta(target_meta["keys"]))
            ordered_query = to_ordered_list(stripped_keys, args["query"])
            return {"situation": int(classifier.predict(ordered_query))}, 200
        except DoesNotExist:
            return {"error": "no such dataset"}, 404
Example #4
0
class RHSignURL(RH):
    """Create a persistent signed URL for a user.

    This build a url and adds a signature that authenticates the user without
    requiring them to have session cookies. It is meant for cases where the
    user actively requests a persistent link to use outside their browser,
    e.g. for a calendar feed.

    When called without authentication, no token is added, so it just behaves
    as the normal ``url_for`` in order to allow client-side code to be more
    straightforward and always call this API regardless of whether the user is
    authenticated or not.
    """

    @use_kwargs({
        'endpoint': fields.String(required=True,
                                  validate=validate_with_message(lambda ep: ep in current_app.view_functions,
                                                                 'Invalid endpoint')),
        'params': fields.Dict(keys=fields.String(), load_default={},
                              validate=validate_with_message(lambda params: not any(x.startswith('_') for x in params),
                                                             'Params starting with an underscore are not allowed'))
    })
    def _process(self, endpoint, params):
        try:
            if session.user:
                url = signed_url_for_user(session.user, endpoint, _external=True, **params)
                Logger.get('url_signing').info("%s signed URL for endpoint '%s' with params %r", session.user, endpoint,
                                               params)
            else:
                url = url_for(endpoint, _external=True, **params)
        except BuildError as exc:
            # if building fails for a valid endpoint we can be pretty sure that it's due to
            # some required params missing
            abort(422, messages={'params': [str(exc)]})
        return jsonify(url=url)
Example #5
0
class FunctionResource(Resource):

    #UNCOMMENT FOR REQUIRED AUTHENTICATION
    #method_decorators = [jwt_required]
    base_directory = "neuroapi.api.neuro."

    query_args = {
        'function': fields.Str(required=True),
        'params': fields.Dict(required=True)
    }

    @use_args(query_args)
    def post(self, args):
        return self.call_function(args["function"], args["params"])

    @use_args(query_args)
    def get(self, args):
        return self.call_function(args["function"], args["params"])

    def call_function(self, function, params):
        function_call = "neurocore." + function
        func = eval(function_call)
        try:
            ret = func(**params)
        except Exception as e:
            return {"error": str(e)}, 400
        return {"result": ret}, 200
Example #6
0
class RHWebhook(RH):
    CSRF_ENABLED = False

    def _check_access(self):
        token = request.headers.get('Authorization')
        expected_token = current_plugin.settings.get('webhook_token')
        if not expected_token or not token or token != expected_token:
            raise Forbidden

    @use_kwargs({
        'event': fields.String(required=True),
        'payload': fields.Dict(required=True)
    }, unknown=EXCLUDE)
    def _process(self, event, payload):
        meeting_id = payload['object']['id']
        vc_room = VCRoom.query.filter(VCRoom.data.contains({'zoom_id': meeting_id})).first()

        if not vc_room:
            # This usually happens when a room wasn't created via indico
            current_plugin.logger.debug('Action for unhandled Zoom room: %s', meeting_id)
            return

        if event in ('meeting.updated', 'webinar.updated'):
            current_plugin.refresh_room(vc_room, None)
        elif event in ('meeting.deleted', 'webinar.deleted'):
            current_plugin.logger.info('Zoom room deleted: %s', meeting_id)
            vc_room.status = VCRoomStatus.deleted
        else:
            current_plugin.logger.warning('Unhandled Zoom webhook payload: %s', event)
Example #7
0
class MaskSchema(Schema):
  id = fields.Int(required=True)
  name = fields.Str(required=True)
  description = fields.Str(required=True)
  genome_build = fields.Str(required=True)
  group_type = fields.Str(required=True)
  identifier_type = fields.Str(required=True)
  groups = fields.Dict(keys=fields.Str(), values=fields.List(VariantField))
Example #8
0
class Task2Schema(Task2ListSchema, ma.SQLAlchemyAutoSchema):
    calculation = fields.Nested(CalculationListSchema)
    infiles = fields.Nested(ArtifactSchema, many=True)
    outfiles = fields.Nested(ArtifactSchema, many=True)
    data = fields.Dict()

    class Meta:
        model = Task2
Example #9
0
class EventEndpointsSchema(Schema):
    tags = fields.Nested(ListEndpointSchema)
    editable_types = fields.String(required=True)
    file_types = fields.Dict(
        keys=fields.String(),
        values=fields.Nested(ListEndpointSchema),
        required=True,
    )
class PowerPlantLoadSchema(Schema):
    load = fields.Float(validate=lambda load: load >= 0)
    fuels = fields.Dict(fields.String(
        validate=lambda fuel_name: fuel_name in
        ["gas(euro/MWh)", "kerosine(euro/MWh)", "co2(euro/ton)", "wind(%)"]),
                        fields.Float(),
                        required=True,
                        validate=validate.Length(min=1))
    powerplants = fields.List(fields.Nested(PowerPlantSchema),
                              required=True,
                              validate=validate.Length(min=1))
Example #11
0
class ConfigFile(Resource):
    configRequest = {'config': fields.Dict(required=True)}

    def get(self):
        dataConfigFile = ConfigHelper.getDataFromConfigFile()
        return {"config": dataConfigFile}

    @use_args(configRequest)
    def put(self, request):
        messageResult = ConfigHelper.putDataToConfigFile(request['config'])
        return {"message": messageResult}
Example #12
0
class RHCreateRoomBlocking(RHRoomBookingBase):
    @use_args({
        'room_ids': fields.List(fields.Int(), missing=[]),
        'start_date': fields.Date(),
        'end_date': fields.Date(),
        'reason': fields.Str(),
        'allowed_principals': fields.List(fields.Dict())
    })
    def _process(self, args):
        blocking = create_blocking(created_by=session.user, **args)
        return jsonify(blockings_schema.dump(blocking, many=False).data)
Example #13
0
class RHCreateRoomBlocking(RHRoomBookingBase):
    @use_args({
        'room_ids': fields.List(fields.Int(), missing=[]),
        'start_date': fields.Date(),
        'end_date': fields.Date(),
        'reason': fields.Str(),
        'allowed_principals': fields.List(fields.Dict())
    })
    def _process(self, args):
        blocking = create_blocking(created_by=session.user, **args)
        approve_or_request_blocking(blocking)
        return jsonify_data(flash=False)
Example #14
0
class EventEndpointsSchema(Schema):
    tags = fields.Nested({
        "create": fields.String(required=True),
        "list": fields.String(required=True)
    })
    editable_types = fields.String(required=True)
    file_types = fields.Dict(
        keys=fields.String(),
        values=fields.Nested({
            "create": fields.String(required=True),
            "list": fields.String(required=True),
        }),
        required=True,
    )
Example #15
0
class AllocationsTarget(MethodResource):
    @jwt_required
    @use_kwargs(post_args, locations=('json', 'form'))
    @use_kwargs_doc(post_args, locations=('json', 'form'))
    @doc(tags=['Cube'],
         description='Retrieves target asset allocations for Cube.')
    def post(self, cube_id):
        # email = get_jwt_identity()
        cube = Cube.query.get(cube_id)
        # is_owner(cube, email)
        if cube:
            try:
                # Target asset allocations
                allocations = asset_allocations(cube)
                if not allocations:
                    balances, total = get_balance_data([cube], cube.user)
                    allocations = asset_allocations_from_balances(balances)
                return {'allocations_target': allocations}
            except:
                return {}
        else:
            return {}

    ext_args = {
        **post_args,
        **{
            'new_allocations':
            fields.List(
                fields.Dict(required=True, description='New allocations')),
        }
    }

    @jwt_required
    @use_kwargs(ext_args, locations=('json', 'form'))
    @use_kwargs_doc(ext_args, locations=('json', 'form'))
    @doc(tags=['Cube'],
         description='Updates target asset allocations for Cube.')
    def put(self, cube_id, new_allocations):
        # email = get_jwt_identity()
        cube = Cube.query.get(cube_id)
        # is_owner(cube, email)
        if cube:
            # New target asset allocations
            return asset_allocations_set(cube, new_allocations)
        else:
            message = 'No cube associated with ID {}'.format(cube_id)
            abort(404, message=message)
Example #16
0
class CalculationSchema(CalculationListSchema):
    id = fields.UUID()
    collection = fields.Str(attribute='collection.name')
    code = fields.Str(attribute='code.name')
    structure = fields.Nested('StructureSchema',
                              only=(
                                  'id',
                                  'name',
                                  '_links',
                              ))
    test = fields.Str(attribute='test.name')
    tasks = fields.Nested('Task2ListSchema', many=True)
    testresults = fields.Nested('TestResultSchema',
                                many=True,
                                exclude=('calculations', ))
    metadata = fields.Dict(attribute='mdata')

    _links = ma.Hyperlinks({
        'self':
        ma.AbsoluteURLFor('calculationresource', cid='<id>'),
        'preview':
        ma.AbsoluteURLFor('calculationpreviewresource', cid='<id>'),
        'collection':
        ma.AbsoluteURLFor('calculationlistresource'),
        'tasks':
        ma.AbsoluteURLFor('calculationtask2listresource', cid='<id>'),
    })

    basis_sets = fields.Nested(CalculationBasisSetAssociationSchema,
                               attribute='basis_set_associations',
                               many=True)

    pseudos = fields.Nested(PseudopotentialSchema,
                            many=True,
                            exclude=(
                                'pseudo',
                                'converted_from',
                            ))

    class Meta:
        model = Calculation
        exclude = (
            'basis_set_associations',
            'tasks_query',
            'testresults_query',
            'mdata',
        )
Example #17
0
class ArtifactSchema(ma.SQLAlchemyAutoSchema):
    _links = ma.Hyperlinks({
        'self':
        ma.AbsoluteURLFor('artifactresource', aid='<id>'),
        'collection':
        ma.AbsoluteURLFor('artifactlistresource'),
        'download':
        ma.AbsoluteURLFor('artifactdownloadresource', aid='<id>'),
        'view':
        ma.AbsoluteURLFor('artifactviewresource', aid='<id>'),
    })

    metadata = fields.Dict(attribute='mdata')

    class Meta:
        model = Artifact
        fields = ('id', 'name', '_links', 'metadata')
Example #18
0
class Dataset(Resource):
    def get(self, name):
        try:
            dataset_meta = DatasetMeta.objects.raw({"_id": name})
            target_meta = dataset_meta.first().as_dict()
            return target_meta, 200
        except DoesNotExist:
            return {"error": "no such dataset"}, 404

    @use_args({
        "situation":
        fields.Integer(required=True),
        "entry":
        fields.Dict(keys=fields.Str, values=fields.Float, required=True)
    })
    def post(self, args, name):
        try:
            dataset_meta = DatasetMeta.objects.raw({"_id": name})
            target_meta = dataset_meta.first().as_dict()

            if strip_neural_meta(target_meta["keys"]) != set(
                    args["entry"].keys()):
                # The keys passed as input via the dataset API are different from the ones
                # used in the dataset.
                return {"error": "wrong keys for the specified dataset"}, 422

            # Decorate the incoming data with information about the situation and the time
            now = datetime.datetime.now()
            args["entry"]["situation"] = args["situation"]
            args["entry"]["hour"] = now.hour
            args["entry"]["minute"] = now.minute
            DatasetEntry(dataset=name,
                         entry=to_ordered_list(target_meta["keys"],
                                               args["entry"])).save()
            return {"dataset": name, "entry": args["entry"]}, 200
        except DoesNotExist:
            return {"error": "no such dataset"}, 404

    def delete(self, name):
        try:
            dataset_meta = DatasetMeta.objects.raw({"_id": name})
            deleted_meta = dataset_meta.first().as_dict()
            dataset_meta.delete()
            return deleted_meta, 200
        except DoesNotExist:
            return {"error": "no such dataset"}, 404
Example #19
0
class RHUpdateRoomBlocking(RHRoomBookingBase):
    def _check_access(self):
        RHRoomBookingBase._check_access(self)
        if not self.blocking.can_edit(session.user):
            raise Forbidden

    def _process_args(self):
        self.blocking = Blocking.get_one(request.view_args['blocking_id'])

    @use_args({
        'room_ids': fields.List(fields.Int(), required=True),
        'reason': fields.Str(required=True),
        'allowed_principals': fields.List(fields.Dict(), missing=[])
    })
    def _process(self, args):
        update_blocking(self.blocking, **args)
        return jsonify(blockings_schema.dump(self.blocking, many=False).data)
Example #20
0
class TestResultSchema(ma.SQLAlchemyAutoSchema):
    _links = ma.Hyperlinks({
        'collection':
        ma.AbsoluteURLFor('testresultlistresource'),
        'self':
        ma.AbsoluteURLFor('testresultresource', trid='<id>'),
    })

    test = fields.Str(attribute='test.name')
    calculations = fields.Nested(CalculationListSchema, many=True)
    collections = fields.Nested('TestResultCollectionSchema',
                                exclude=('testresults', ),
                                many=True)
    metadata = fields.Dict(attribute='mdata')

    class Meta:
        model = TestResult2
        exclude = ('mdata', )
Example #21
0
class RHProgramCodesAPIContributions(RHManageEventBase):
    """RESTful API to bulk-update contribution codes."""
    def _process_GET(self):
        return jsonify(
            {c.friendly_id: c.code
             for c in self.event.contributions})

    @use_kwargs({
        'codes':
        fields.Dict(keys=fields.Int, values=fields.String, required=True)
    })
    def _process_PATCH(self, codes):
        contribs = {
            c.friendly_id: c
            for c in Contribution.query.with_parent(self.event).filter(
                Contribution.friendly_id.in_(codes))
        }
        if invalid := (codes - contribs.keys()):
            abort(422,
                  messages={
                      'codes':
                      [f'Invalid IDs: {", ".join(map(str, invalid))}']
                  })

        updates = {}
        for friendly_id, code in codes.items():
            contrib = contribs[friendly_id]
            if code != contrib.code:
                updates[contrib] = (contrib.code, code)
                contrib.code = code

        self.event.log(EventLogRealm.management,
                       LogKind.change,
                       'Program',
                       'Program codes assigned to contributions',
                       session.user,
                       data=_get_update_log_data(updates))
        return jsonify({
            contrib.friendly_id: changes
            for contrib, changes in updates.items()
        })
Example #22
0
class RHCreateRoomBlocking(RHRoomBookingBase):
    @use_kwargs({
        'room_ids': fields.List(fields.Int(), missing=[]),
        'start_date': fields.Date(),
        'end_date': fields.Date(),
        'reason': fields.Str(),
        'allowed_principals': fields.List(fields.Dict(), missing=[])
    })
    def _process(self, room_ids, start_date, end_date, reason,
                 allowed_principals):
        rooms = Room.query.filter(Room.id.in_(room_ids)).all()
        allowed = []
        for obj in allowed_principals:
            if obj.get('is_group'):
                allowed.append(GroupProxy(obj['id'], provider=obj['provider']))
            else:
                allowed.append(User.query.filter(User.id == obj['id']).one())
        blocking = create_blocking(rooms, start_date, end_date, reason,
                                   allowed)
        approve_or_request_blocking(blocking)
        return jsonify_data(flash=False)
Example #23
0
def add_file_routes(app, is_local, server_path):
    """ Create routes related to file submission for flask app """

    # Keys for the post route will correspond to the four types of files
    @app.route("/v1/upload_dabs_files/", methods=["POST"])
    @requires_agency_perms('writer')
    def upload_dabs_files():
        if "multipart/form-data" not in request.headers['Content-Type']:
            return JsonResponse.error(
                ValueError("Request must be a multipart/form-data type"),
                StatusCode.CLIENT_ERROR)
        file_manager = FileHandler(request,
                                   is_local=is_local,
                                   server_path=server_path)
        return file_manager.validate_upload_dabs_files()

    @app.route("/v1/check_status/", methods=["GET"])
    @convert_to_submission_id
    @requires_submission_perms('reader')
    @use_kwargs({'type': webargs_fields.String(missing='')})
    def check_status(submission, type):
        return get_status(submission, type)

    @app.route("/v1/submission_metadata/", methods=["GET"])
    @convert_to_submission_id
    @requires_submission_perms('reader')
    def submission_metadata(submission):
        return JsonResponse.create(StatusCode.OK,
                                   get_submission_metadata(submission))

    @app.route("/v1/submission_data/", methods=["GET"])
    @convert_to_submission_id
    @requires_submission_perms('reader')
    @use_kwargs({'type': webargs_fields.String(missing='')})
    def submission_data(submission, type):
        return get_submission_data(submission, type)

    @app.route("/v1/revalidation_threshold/", methods=["GET"])
    @requires_login
    def revalidation_threshold():
        return JsonResponse.create(StatusCode.OK, get_revalidation_threshold())

    @app.route("/v1/window/", methods=["GET"])
    def window():
        return list_windows()

    @app.route("/v1/error_metrics/", methods=["POST"])
    @convert_to_submission_id
    @requires_submission_perms('reader')
    def submission_error_metrics(submission):
        return get_error_metrics(submission)

    @app.route("/v1/list_submissions/", methods=["POST"])
    @requires_login
    @use_kwargs({
        'page':
        webargs_fields.Int(missing=1),
        'limit':
        webargs_fields.Int(missing=5),
        'certified':
        webargs_fields.String(required=True,
                              validate=webargs_validate.OneOf(
                                  ('mixed', 'true', 'false'))),
        'sort':
        webargs_fields.String(missing='modified'),
        'order':
        webargs_fields.String(missing='desc'),
        'd2_submission':
        webargs_fields.Bool(missing=False),
        'filters':
        webargs_fields.Dict(keys=webargs_fields.String(), missing={})
    })
    def list_submissions(page, limit, certified, sort, order, d2_submission,
                         filters):
        """ List submission IDs associated with the current user """
        return list_submissions_handler(page, limit, certified, sort, order,
                                        d2_submission, filters)

    @app.route("/v1/list_certifications/", methods=["POST"])
    @convert_to_submission_id
    @requires_submission_perms('reader')
    def submission_list_certifications(submission):
        """ List all certifications for a specific submission """
        return list_certifications(submission)

    @app.route("/v1/get_certified_file/", methods=["POST"])
    @use_kwargs({
        'submission_id': webargs_fields.Int(required=True),
        'certified_files_history_id': webargs_fields.Int(required=True),
        'is_warning': webargs_fields.Bool(missing=False)
    })
    @requires_submission_perms('reader')
    def get_certified_file(submission, certified_files_history_id, is_warning):
        """ Get the signed URL for the specified file history """
        return file_history_url(submission, certified_files_history_id,
                                is_warning, is_local)

    @app.route("/v1/get_protected_files/", methods=["GET"])
    @requires_login
    def get_protected_files():
        """ Return signed URLs for all help page files """
        file_manager = FileHandler(request,
                                   is_local=is_local,
                                   server_path=server_path)
        return file_manager.get_protected_files()

    @app.route("/v1/check_current_page/", methods=["GET"])
    @convert_to_submission_id
    @requires_submission_perms('reader')
    def check_current_page(submission):
        return check_current_submission_page(submission)

    @app.route("/v1/get_fabs_meta/", methods=["POST"])
    @convert_to_submission_id
    @requires_submission_perms('reader')
    def get_fabs_metadata(submission):
        """ Return metadata of FABS submission """
        return JsonResponse.create(StatusCode.OK,
                                   get_fabs_meta(submission.submission_id))

    @app.route("/v1/upload_fabs_file/", methods=["POST"])
    @requires_sub_agency_perms('editfabs')
    def upload_fabs_file():
        if "multipart/form-data" not in request.headers['Content-Type']:
            return JsonResponse.error(
                ValueError("Request must be a multipart/form-data type"),
                StatusCode.CLIENT_ERROR)
        params = RequestDictionary.derive(request)
        fabs = params.get('_files', {}).get('fabs', None)
        file_manager = FileHandler(request,
                                   is_local=is_local,
                                   server_path=server_path)
        return file_manager.upload_fabs_file(fabs)

    @app.route("/v1/submit_detached_file/", methods=["POST"])
    @convert_to_submission_id
    @requires_submission_perms('fabs', check_owner=False)
    def submit_detached_file(submission):
        file_manager = FileHandler(request,
                                   is_local=is_local,
                                   server_path=server_path)
        return file_manager.publish_fabs_submission(submission)

    @app.route("/v1/get_obligations/", methods=["GET"])
    @convert_to_submission_id
    @requires_submission_perms('reader')
    def get_obligations(submission):
        return JsonResponse.create(
            StatusCode.OK, get_submission_stats(submission.submission_id))

    @app.route("/v1/submission/<int:submission_id>/narrative", methods=['GET'])
    @requires_submission_perms('reader')
    def get_submission_narratives(submission):
        return narratives_for_submission(submission)

    @app.route("/v1/submission/<int:submission_id>/narrative",
               methods=['POST'])
    @requires_submission_perms('writer')
    def post_submission_narratives(submission):
        return update_narratives(submission, request.json)

    @app.route("/v1/submission/<int:submission_id>/report_url",
               methods=['GET'])
    @requires_submission_perms('reader')
    @use_kwargs({
        'warning':
        webargs_fields.Bool(),
        'file_type':
        webargs_fields.String(required=True,
                              validate=webargs_validate.OneOf(
                                  FILE_TYPE_DICT.keys() -
                                  {'executive_compensation', 'sub_award'})),
        'cross_type':
        webargs_fields.String(validate=webargs_validate.OneOf([
            'program_activity', 'award_financial', 'award_procurement', 'award'
        ]))
    })
    def post_submission_report_url(submission, warning, file_type, cross_type):
        return submission_report_url(submission, bool(warning), file_type,
                                     cross_type)

    @app.route("/v1/get_file_url", methods=['GET'])
    @convert_to_submission_id
    @requires_submission_perms('reader')
    @use_kwargs({
        'file_type':
        webargs_fields.String(required=True,
                              validate=webargs_validate.OneOf(
                                  FILE_TYPE_DICT_LETTER.values()))
    })
    def get_file_url(submission, file_type):
        return get_upload_file_url(submission, file_type)

    @app.route("/v1/delete_submission/", methods=['POST'])
    @convert_to_submission_id
    @requires_submission_perms('writer', check_fabs='editfabs')
    def delete_submission(submission):
        """ Deletes all data associated with the specified submission
            NOTE: THERE IS NO WAY TO UNDO THIS
        """
        return delete_all_submission_data(submission)

    @app.route("/v1/check_year_quarter/", methods=["GET"])
    @requires_login
    @use_kwargs({
        'cgac_code': webargs_fields.String(),
        'frec_code': webargs_fields.String(),
        'reporting_fiscal_year': webargs_fields.String(required=True),
        'reporting_fiscal_period': webargs_fields.String(required=True)
    })
    def check_year_and_quarter(cgac_code, frec_code, reporting_fiscal_year,
                               reporting_fiscal_period):
        """ Check if cgac (or frec) code, year, and quarter already has a published submission """
        return find_existing_submissions_in_period(cgac_code, frec_code,
                                                   reporting_fiscal_year,
                                                   reporting_fiscal_period)

    @app.route("/v1/certify_submission/", methods=['POST'])
    @convert_to_submission_id
    @requires_submission_perms('submitter', check_owner=False)
    def certify_submission(submission):
        file_manager = FileHandler(request,
                                   is_local=is_local,
                                   server_path=server_path)
        return certify_dabs_submission(submission, file_manager)

    @app.route("/v1/restart_validation/", methods=['POST'])
    @convert_to_submission_id
    @requires_submission_perms('writer', check_fabs='editfabs')
    @use_kwargs({'d2_submission': webargs_fields.Bool(missing=False)})
    def restart_validation(submission, d2_submission):
        return FileHandler.restart_validation(submission, d2_submission)
Example #24
0
    return result


@blueprint.route("/", methods=("GET", ))
@permission_taxonomy_read_all.require(http_exception=403)
def taxonomy_list():
    """List all available taxonomies."""
    return jsonify([
        jsonify_taxonomy(t) for t in current_flask_taxonomies.taxonomy_list()
    ])


@blueprint.route("/", methods=("POST", ))
@use_kwargs({
    "code": fields.Str(required=True),
    "extra_data": fields.Dict(location='extra_data')
})
@permission_taxonomy_create_all.require(http_exception=403)
def taxonomy_create(code: str, extra_data: dict = None):
    """Create a new Taxonomy."""
    try:
        created = current_flask_taxonomies.create_taxonomy(
            code=code, extra_data=extra_data)
        created_dict = jsonify_taxonomy(created)

        response = jsonify(created_dict)
        response.status_code = 201
        response.headers['Location'] = created_dict['links']['self']
        return response
    except IntegrityError:
        raise BadRequest("Taxonomy with this code already exists.")
Example #25
0
    class UpdateSchema(Schema):
        query = fields.Dict(required=True)
        data = fields.Dict(required=True)

        class Meta:
            strict = True
def add_dashboard_routes(app):
    """ Create routes related to agency data dashboard for flask app """

    @app.route('/v1/get_rule_labels/', methods=['POST'])
    @use_kwargs({
        'files': webargs_fields.List(webargs_fields.String(), required=True),
        'fabs': webargs_fields.Bool(missing=False),
        'error_level': webargs_fields.String(validate=webargs_validate.
                                             OneOf(['warning', 'error', 'mixed'],
                                                   error='Must be either warning, error, or mixed'),
                                             missing='warning')
    })
    def get_rule_labels(**kwargs):
        """ Returns the rule labels based on the filters provided """
        files = kwargs.get('files')
        fabs = kwargs.get('fabs')
        error_level = kwargs.get('error_level')
        return list_rule_labels(files, error_level, fabs)

    @app.route("/v1/historic_dabs_graphs/", methods=["POST"])
    @requires_login
    @use_kwargs({
        'filters': webargs_fields.Dict(keys=webargs_fields.String(), missing={})
    })
    def historic_dabs_graphs(**kwargs):
        """ Returns the historic DABS graphs based on the filters provided """
        filters = kwargs.get('filters')
        return historic_dabs_warning_graphs(filters)

    @app.route("/v1/historic_dabs_table/", methods=["POST"])
    @requires_login
    @use_kwargs({
        'page': webargs_fields.Int(missing=1),
        'limit': webargs_fields.Int(missing=5),
        'sort': webargs_fields.String(missing='period'),
        'order': webargs_fields.String(missing='desc'),
        'filters': webargs_fields.Dict(keys=webargs_fields.String(), required=True)
    })
    def historic_dabs_table(**kwargs):
        """ List warning metadata for selected  """
        page = kwargs.get('page')
        limit = kwargs.get('limit')
        sort = kwargs.get('sort')
        order = kwargs.get('order')
        filters = kwargs.get('filters')
        return historic_dabs_warning_table(filters, page, limit, sort, order)

    @app.route("/v1/active_submission_overview/", methods=["GET"])
    @convert_to_submission_id
    @requires_submission_perms('reader')
    @use_kwargs({
        'file': webargs_fields.String(validate=webargs_validate.
                                      OneOf(['A', 'B', 'C', 'cross-AB', 'cross-BC', 'cross-CD1', 'cross-CD2'],
                                            error='Must be A, B, C, cross-AB, cross-BC, cross-CD1, or cross-CD2'),
                                      required=True),
        'error_level': webargs_fields.String(validate=webargs_validate.
                                             OneOf(['warning', 'error', 'mixed'],
                                                   error='Must be either warning, error, or mixed'),
                                             missing='warning')
    })
    def get_active_submission_overview(submission, file, **kwargs):
        """ Returns an overview of the requested submission for the active dashboard """
        error_level = kwargs.get('error_level')
        return active_submission_overview(submission, file, error_level)

    @app.route("/v1/get_impact_counts/", methods=["GET"])
    @convert_to_submission_id
    @requires_submission_perms('reader')
    @use_kwargs({
        'file': webargs_fields.String(validate=webargs_validate.
                                      OneOf(['A', 'B', 'C', 'cross-AB', 'cross-BC', 'cross-CD1', 'cross-CD2'],
                                            error='Must be A, B, C, cross-AB, cross-BC, cross-CD1, or cross-CD2'),
                                      required=True),
        'error_level': webargs_fields.String(validate=webargs_validate.
                                             OneOf(['warning', 'error', 'mixed'],
                                                   error='Must be either warning, error, or mixed'),
                                             missing='warning')
    })
    def impact_counts(submission, file, **kwargs):
        """ Returns the impact counts of the requested submission for the active dashboard """
        error_level = kwargs.get('error_level')
        return get_impact_counts(submission, file, error_level)

    @app.route("/v1/get_significance_counts/", methods=["GET"])
    @convert_to_submission_id
    @requires_submission_perms('reader')
    @use_kwargs({
        'file': webargs_fields.String(validate=webargs_validate.
                                      OneOf(['A', 'B', 'C', 'cross-AB', 'cross-BC', 'cross-CD1', 'cross-CD2'],
                                            error='Must be A, B, C, cross-AB, cross-BC, cross-CD1, or cross-CD2'),
                                      required=True),
        'error_level': webargs_fields.String(validate=webargs_validate.
                                             OneOf(['warning', 'error', 'mixed'],
                                                   error='Must be either warning, error, or mixed'),
                                             missing='warning')
    })
    def significance_counts(submission, file, **kwargs):
        """ Returns the significance counts of the requested submission for the active dashboard """
        error_level = kwargs.get('error_level')
        return get_significance_counts(submission, file, error_level)

    @app.route("/v1/active_submission_table/", methods=["GET"])
    @convert_to_submission_id
    @requires_submission_perms('reader')
    @use_kwargs({
        'file': webargs_fields.String(validate=webargs_validate.
                                      OneOf(FILE_TYPES,
                                            error='Must be one of the following: {}'.format(', '.join(FILE_TYPES))),
                                      required=True),
        'error_level': webargs_fields.String(validate=webargs_validate.
                                             OneOf(['warning', 'error', 'mixed'],
                                                   error='Must be either warning, error, or mixed'),
                                             missing='warning'),
        'page': webargs_fields.Int(missing=1),
        'limit': webargs_fields.Int(missing=5),
        'sort': webargs_fields.String(missing='significance'),
        'order': webargs_fields.String(missing='asc')
    })
    def get_active_submission_table(submission, file, **kwargs):
        """ Returns an overview of the requested submission for the active dashboard """
        error_level = kwargs.get('error_level')
        page = kwargs.get('page')
        limit = kwargs.get('limit')
        sort = kwargs.get('sort')
        order = kwargs.get('order')
        return active_submission_table(submission, file, error_level, page, limit, sort, order)
Example #27
0
from liblio.helpers import flake_id, printable_id
from . import API_PATH

BLUEPRINT_PATH="{api}/settings".format(api=API_PATH)

blueprint = Blueprint('settings', __name__, url_prefix=BLUEPRINT_PATH)

### Request schemas

request_schemas = {
    'edit_profile': {
        'name': fields.Str(),
        'bio': fields.Str(),
        'tags': fields.List(fields.Str()),
        'private': fields.Boolean(missing=False),
        'settings': fields.Dict()
    }
}

### Routes

@blueprint.route('/my-profile', methods=('GET',))
@jwt_required
def get_my_profile():
    """Get the profile for the logged-in user. (This may have sensitive/private info.)"""

    username = get_jwt_identity()
    origin = current_app.config['SERVER_ORIGIN']

    profile = User.query.filter_by(username=username, origin=origin).first()
    if profile is None:
Example #28
0
blueprint = Blueprint("inspirehep_curation", __name__, url_prefix="/curation")
parser = FlaskParser()


@parser.error_handler
def handle_error(error, req, schema, error_status_code, error_headers):
    message = f"Incorrect input type for fields: {''.join(error.field_names)}"
    abort(400, message)


@blueprint.route("/literature/<int:pid_value>/keywords", methods=["PUT"])
@login_required_with_roles([Roles.cataloger.value])
@parser.use_args(
    {
        "_desy_bookkeeping": fields.Dict(required=False),
        "keywords": fields.List(fields.String, required=False),
        "energy_ranges": fields.List(fields.String, required=False),
    },
    locations=("json",),
)
def add_keywords(args, pid_value):
    keywords = args.get("keywords")
    desy_bookkeeping = args.get("_desy_bookkeeping")
    energy_ranges = args.get("energy_ranges")
    if not any([keywords, desy_bookkeeping, energy_ranges]):
        return (
            jsonify(
                success=False,
                message="None of required fields was passed",
            ),
Example #29
0
@app.route("/orders/<int:order_id>", methods=["GET"])
@marshal_with(OrderSchema())
def route_order_get_by_id(order_id):
    order = Order.query.filter(Order.id == order_id).first()
    if not order:
        return abort(400,
                     "The order with id: {0} does not exists".format(order_id))
    return order


@app.route("/orders", methods=["POST"])
@marshal_with(OrderSchema())
@use_kwargs({
    "buyer_id": fields.Int(),
    "seller_id": fields.Int(),
    "line_items": fields.List(fields.Dict()),
})
def route_order_create(buyer_id, seller_id, line_items):
    order = Order(buyer_id=buyer_id, seller_id=seller_id, line_items=[])
    total = 0
    for li in line_items:
        product = Product.query.filter(Product.id == li['product_id']).first()
        total += li['quantity'] * product.price
        item = LineItem(product=product,
                        order=order,
                        quantity=li['quantity'],
                        unit_price=li['quantity'] * product.price)
        order.line_items.append(item)
    order.total = total
    db.session.add(order)
    db.session.commit()
Example #30
0
class WorkflowsRecordSourcesResource(MethodView):

    view_name = "workflows_record_sources"
    decorators = [
        login_required_with_roles(
            [Roles.superuser.value, Roles.cataloger.value])
    ]

    @parser.error_handler
    def handle_error(error, req, schema, error_status_code, error_headers):
        message = f"Incorrect input for fields: {''.join(error.field_names)}"
        abort(400, message)

    @parser.use_args({
        "record_uuid": fields.String(required=True),
        "source": fields.String()
    })
    def get(self, args):
        record_uuid = args["record_uuid"]
        required_fields_mapping = {
            "created": WorkflowsRecordSources.created,
            "json": WorkflowsRecordSources.json,
            "record_uuid": WorkflowsRecordSources.record_uuid,
            "source": WorkflowsRecordSources.source,
            "updated": WorkflowsRecordSources.updated,
        }
        query = WorkflowsRecordSources.query.with_entities(
            *required_fields_mapping.values()).filter_by(
                record_uuid=str(record_uuid))
        source = args.get("source")
        if source:
            query = query.filter_by(source=source.lower())
        results = query.all()
        if not results:
            return jsonify({"message": "Workflow source not found"}), 404
        results_data = [{
            key: val
            for key, val in zip(required_fields_mapping.keys(), result)
        } for result in results]
        return jsonify({"workflow_sources": results_data}), 200

    @parser.use_args({
        "record_uuid": fields.String(required=True),
        "source": fields.String(required=True),
        "json": fields.Dict(required=True),
    })
    def post(self, args):
        record_uuid = args["record_uuid"]
        source = args["source"]
        root_json = args["json"]
        root = WorkflowsRecordSources(source=source,
                                      record_uuid=record_uuid,
                                      json=root_json)
        db.session.merge(root)
        db.session.commit()
        if root:
            return (
                jsonify({
                    "message":
                    f"workflow source for record {record_uuid} and source {source} added"
                }),
                200,
            )

    @parser.use_args({
        "record_uuid": fields.String(required=True),
        "source": fields.String(required=True),
    })
    def delete(self, args):
        record_uuid = args.get("record_uuid")
        source = args.get("source")
        result = WorkflowsRecordSources.query.filter_by(
            record_uuid=str(record_uuid), source=source.lower()).one_or_none()
        if not result:
            return (
                jsonify({
                    "message":
                    "No record found for given record_uuid and source!"
                }),
                404,
            )
        db.session.delete(result)
        db.session.commit()
        return jsonify({"message": "Record succesfully deleted"}), 200