コード例 #1
0
    def mutate(
        args: Dict,
        info: graphql.execution.base.ResolveInfo,
        user_study: InputUserStudy,
    ):
        """ Upserts a `ModelUserStudy` record based on the `user_study` input.

        Returns
            MutationUserStudyUpsert: The result of the mutation.
        """

        # Cleanup the Auth0 user ID.
        auth0_user_id = clean_auth0_user_id(auth0_user_id=str(
            user_study.auth0_user_id), )

        # Retrieve the NCT ID of the defined study.
        nct_id = str(user_study.nct_id)

        # Check that the requesting user is authorized to upsert the user with
        # the given Auth0 ID.
        check_auth(info=info, auth0_user_id=auth0_user_id)

        # Retrieve the session out of the context as the `get_query` method
        # automatically selects the model.
        session = info.context.get("session")  # type: sqlalchemy.orm.Session

        # Retrieve the `ModelUser` record object.
        user = get_user(session=session, auth0_user_id=auth0_user_id)

        # Raise an exception if the requested user could not be found.
        if not user:
            msg = "User with Auth0 ID '{}' could not be found."
            msg_fmt = msg.format(auth0_user_id)
            raise graphql.GraphQLError(message=msg_fmt)

        # Retrieve the `ModelStudy` record object.
        study = get_study(session=session, nct_id=nct_id)

        # Raise an exception if the requested study could not be found.
        if not study:
            msg = "Study with NCT ID '{}' could not be found."
            msg_fmt = msg.format(nct_id)
            raise graphql.GraphQLError(message=msg_fmt)

        # Upsert the `ModelUserStudy` record.
        statement = insert(ModelUserStudy,
                           values={
                               "user_id": user.user_id,
                               "study_id": study.study_id,
                           }).on_conflict_do_nothing()  # type: Insert

        # Execute the upsert.
        result = session.execute(statement)  # type: ResultProxy

        # Retrieve the newly upserted `ModelUser` record object.
        obj = get_user(session=session, auth0_user_id=auth0_user_id)

        session.commit()

        return MutationUserStudyUpsert(user=obj)
コード例 #2
0
    def mutate_and_get_payload(cls, root, info, **input):
        house_query = HouseNode.get_query(info)
        house = house_query.filter(HouseModel.name == input['house_name']).first()
        if not house:
            raise gq.GraphQLError(f'Could not find house with name {input["house_name"]}')

        student = StudentModel(
            name=input['name'],
            house=house,
            wand_wood=input.get('wand_wood'),
            wand_core=input.get('wand_core'),
            wand_length=input.get('wand_length', 0),
            wand_length_unit=input.get('wand_length_unit'),
        )

        student_query = StudentNode.get_query(info)
        # trying to follow PEP8
        # https://www.python.org/dev/peps/pep-0008/#should-a-line-break-before-or-after-a-binary-operator
        found_students = student_query.filter(
            (StudentModel.name == student.name)
        and (StudentModel.house_id == student.house_id)
        and (StudentModel.wand_wood == student.wand_wood)
        and (StudentModel.wand_core == student.wand_core)
        and (StudentModel.wand_length == student.wand_length)
        and (StudentModel.wand_length_unit == student.wand_length_unit)).all() # yapf: disable

        if len(found_students):
            for s in found_students:
                print(s.id)
            raise gq.GraphQLError(f'Student with attributes {input} already exists')

        db.db_session.add(student)
        db.db_session.commit()
        return CreateStudent(student=student, success=True)
コード例 #3
0
    def resolve_calculatePrice(self, info, arg):
        # get input data
        type = arg.get('type')
        margin = arg.get('margin')
        exchangeRate = arg.get('exchangeRate')

        # make api call
        url = 'https://api.coindesk.com/v1/bpi/currentprice/USD.json'
        try:
            request = requests.get(url)
        except:
            raise graphql.GraphQLError('request failed')

        if request.status_code is not 200:
            raise graphql.GraphQLError('request failed')

        result = request.json()
        currentPrice = result['bpi']['USD']['rate_float']

        if type is 'sell':
            val = currentPrice - (margin / 100)
        else:
            val = currentPrice + (margin / 100)

        return exchangeRate * val
コード例 #4
0
    def mutate(root, info, **kwargs):
        threshold = Threshold()
        thresholdInput = kwargs.get("thresholdInput")
        thresholdId = kwargs.get("thresholdId")

        if thresholdId is None:
            raise graphql.GraphQLError("Missing argument: thresholdId")
        threshold = Threshold.objects.filter(id=thresholdId).first()
        if threshold is None:
            raise graphql.GraphQLError(
                f"threshold with id {thresholdId} not found")

        args = ["name", "default", "min", "max", "current", "moduleId"]
        for arg in args:
            valueFromInput = getattr(thresholdInput, arg)
            if valueFromInput is not None:
                setattr(threshold, arg, valueFromInput)

        moduleIdOfThreshold = thresholdInput.get("moduleId")
        if moduleIdOfThreshold is not None:
            moduleOfThreshold = Module.objects.filter(
                id=moduleIdOfThreshold).first()
            if moduleOfThreshold is None:
                raise graphql.GraphQLError(
                    "module #{} does not exist !".format(moduleIdOfThreshold))
            threshold.module = moduleOfThreshold

        threshold.save(force_update=True)
        return UpdateThreshold(threshold=threshold)
コード例 #5
0
ファイル: Module.py プロジェクト: querat/graphQL
    def mutate(root, info, **kwargs):

        requiredArgs = ["moduleId", "boxId", "boxAuthCode", "moduleAuthCode"]
        for requiredArg in requiredArgs:
            if kwargs.get(requiredArg) is None:
                raise GraphQLError(f"missing argument: {requiredArg}")

        affectedModule = Module.objects.filter(pk=kwargs["moduleId"]).first()
        if affectedModule is None:
            raise graphql.GraphQLError("Module #{} does not exist".format(
                kwargs["moduleId"]))

        if affectedModule.authCode != kwargs["moduleAuthCode"]:
            raise GraphQLError(
                f"Invalid auth code provided for module #{kwargs['moduleId']}")

        box = Box.objects.filter(pk=kwargs["boxId"]).first()
        if box is None:
            raise graphql.GraphQLError(
                f"Box #{kwargs['boxId']} does not exist")

        if box.authCode != kwargs["boxAuthCode"]:
            raise graphql.GraphQLError(
                f"Invalid auth code provided for box {kwargs['boxId']}")

        affectedModule.box = box
        affectedModule.save(force_update=True)

        return AssignModuleToBox(module=affectedModule)
コード例 #6
0
ファイル: task.py プロジェクト: ninodinatale/creditask
    def mutate(root,
               info,
               create_input: TaskInputCreate = None,
               update_input: TaskInputUpdate = None):
        if create_input is None and update_input is None:
            raise graphql.GraphQLError(
                'Either create_input or update_input need '
                'to be set')

        if create_input is not None and update_input is not None:
            raise graphql.GraphQLError(
                'Only one of create_input or update_input '
                'may be set')

        if create_input is not None:
            if create_input.credits_calc == CreditsCalc.FIXED and \
                    create_input.fixed_credits is None:
                raise graphql.GraphQLError(
                    'If CreditsCalc is FIXED, fixed_credits needs to be set, '
                    'but is None')
            if create_input.credits_calc == CreditsCalc.BY_FACTOR and \
                    create_input.factor is None:
                raise graphql.GraphQLError(
                    'If CreditsCalc is BY_FACTOR, factor needs to be set, '
                    'but is None')

        new_task_props: dict = create_input or update_input or dict()

        new_task_props = remove_none_values(new_task_props)

        task = save_task(info.context.user, **new_task_props)
        return SaveTask(task=task)
コード例 #7
0
    def resolve_getBoxById(self, _, **kwargs):
        boxId = kwargs.get("boxId")
        authCode = kwargs.get("boxAuthCode")
        box = None

        try:
            box = Box.objects.get(pk=boxId)
        except Box.DoesNotExist:
            raise graphql.GraphQLError("box #{} does not exist".format(boxId))
        if authCode != box.authCode:
            raise graphql.GraphQLError(
                "invalid authcode for box #".format(boxId))
        return box
コード例 #8
0
    def mutate_and_get_payload(cls, root, info, house_name, id, client_mutation_id=None):
        student_id = gq_relay.from_global_id(id)[1]
        student_query = StudentNode.get_query(info)
        student = student_query.filter(StudentModel.id == student_id).first()
        if not student:
            raise gq.GraphQLError(f'Could not find student with id {id}')

        house_query = HouseNode.get_query(info)
        house = house_query.filter(HouseModel.name == house_name).first()
        if not house:
            raise gq.GraphQLError(f'Could not find house {house_name}')
        student.house = house
        db.db_session.commit()
        return ChangeStudentHouse(student=student, success=True)
コード例 #9
0
    def resolve_getUser(self, info, **kwargs):
        userName = kwargs.get("userName")
        password = kwargs.get("password")
        user = None

        try:
            user = User.objects.get(name=userName)
        except User.DoesNotExist:
            raise graphql.GraphQLError("User '{}' not found".format(userName))
        if not bcrypt.checkpw(password.encode('utf8'),
                              user.password.encode('utf8')):
            raise graphql.GraphQLError(
                "invalid password for User '{}'".format(userName))
        return user
コード例 #10
0
    def mutate(
        args: Dict,
        info: graphql.execution.base.ResolveInfo,
        auth0_user_id: str,
        search_uuid: uuid.UUID,
    ):
        """ Deletes a `ModelSearch` record and all its `ModelSearchDescriptor`
            records.

        Returns
            MutationSearchUpsert: The result of the mutation.
        """

        # Cleanup the Auth0 user ID.
        auth0_user_id = clean_auth0_user_id(auth0_user_id=str(auth0_user_id))

        # Check that the requesting user is authorized to make changes to the
        # user with the given Auth0 ID.
        check_auth(info=info, auth0_user_id=auth0_user_id)

        # Retrieve the session out of the context as the `get_query` method
        # automatically selects the model.
        session = info.context.get("session")  # type: sqlalchemy.orm.Session

        # Retrieve the `ModelUser` record object.
        user = get_user(session=session, auth0_user_id=auth0_user_id)

        # Raise an exception if the requested user could not be found.
        if not user:
            raise graphql.GraphQLError(
                message=f"User with Auth0 ID '{auth0_user_id}' could not be "
                f"found.")

        # Retrieve the `ModelSearch` record object.
        search = get_search(session=session, search_uuid=search_uuid)

        # Raise an exception if the requested search could not be found.
        if not search:
            raise graphql.GraphQLError(
                message=f"Search with UUID '{search_uuid}' under user with "
                f"Auth0 ID '{auth0_user_id}' could not be found.")

        # Delete the `ModelSearch` record and all its related `ModelUserSearch`
        # and `ModelSearchDescriptor` records.
        delete_search(session=session, search_id=search.search_id)

        session.commit()

        return MutationSearchDelete(search=search)
コード例 #11
0
ファイル: test_server.py プロジェクト: dfee/graphql-ws-next
    async def test_send_execution_result(self, server, conn_context):
        data = {"test": "data"}
        error = graphql.GraphQLError(
            "test message",
            graphql.language.Node(),
            source=graphql.Source("query { something }"),
            positions=[14, 40],
            path=["one", 2],
            original_error=ValueError("original"),
            extensions={"ext": None},
        )
        exec_result = graphql.ExecutionResult(data=data, errors=[error])

        await server.send_execution_result(conn_context, OP_ID, exec_result)
        assert conn_context.send_queue.qsize() == 1

        msg = conn_context.send_queue.get_nowait()
        assert json.loads(msg) == {
            "type": GQLMsgType.DATA.value,
            "id": OP_ID,
            "payload": {
                "data":
                data,
                "errors": [{
                    "message": "test message",
                    "locations": [[1, 15], [1, 20]],
                    "path": ERROR.path,
                    "extensions": ERROR.extensions,
                }],
            },
        }
コード例 #12
0
 def mutate(self, root, info, **args):
     todo = Todo.objects.filter(user_id__exact=args.get('user_id', 1),
                                id__exact=args.get('todo_id'))
     if not todo:
         raise graphql.GraphQLError('Todo not found')
     todo = todo[0].update_item(item_name=args.get('item_name'))
     return UpdateTodo(todo=todo)
コード例 #13
0
    def resolve_project(parent, info, name):
        try:
            project = REPOSITORY.get_project(name=name)
        except EntityDoesNotExist:
            raise graphql.GraphQLError("Project does not exist!")

        return project
コード例 #14
0
 def resolve_staff_by_position(self, info, position):
     query = StaffNode.get_query(info)
     # for demonstration purposes
     pprint(str(query))
     if not position:
         raise gq.GraphQLError('Please provide staff position')
     return query.filter(StaffModel.position == position).all()
コード例 #15
0
    def mutate(self, root, info, **args):
        todo = Todo.objects.filter(user_id__exact=args.get('user_id', 1),
                                   id__exact=args.get('todo_id'))
        if not todo:
            raise graphql.GraphQLError('Todo not found')
        todo[0].delete()

        return DeleteTodo(todo='Todo was deleted successfully')
コード例 #16
0
def resolveReport(root, info, token, brokerId, accountNumber):
    try:
        auth.decodeToken(token)

        report = makeReport(brokerId, accountNumber, "Current Report")
        return serializeReport(report)
    except AssertionError as e:
        raise graphql.GraphQLError(e)
コード例 #17
0
    def mutate(self, info, name, description, is_internal, is_global):
        try:
            project = REPOSITORY.create_project(
                name, description, is_internal, is_global
            )
        except EntityCreationException:
            raise graphql.GraphQLError("Could not create a project")

        return CreateProjectMutation(project=project)
コード例 #18
0
    def mutate_and_get_payload(cls, root, info, id, client_mutation_id=None):
        student_id = gq_relay.from_global_id(id)[1]
        student_query = StudentNode.get_query(info)
        student = student_query.filter(StudentModel.id == student_id).first()
        if not student:
            raise gq.GraphQLError(f'Could not find student with id {id}')

        db.db_session.delete(student)
        db.db_session.commit()
        return DeleteStudent(student=student, success=True)
コード例 #19
0
    def mutate(self, info, token, _id):
        try:
            auth.decodeToken(token)

            response = requests.delete(
                "{}/brokers/{}".format(config.HARAMBE_DATA_SERVICE_ENDPOINT, _id))

            assert (response.status_code == 200), "Error removing broker"

            return RemoveBrokerAccount(True)
        except AssertionError as e:
            raise graphql.GraphQLError(e)
コード例 #20
0
    def mutate(
        args: Dict,
        info: graphql.execution.base.ResolveInfo,
        auth0_user_id: str,
    ):
        """ Deletes a `ModelUser` record based on the `user` input.

        Returns
            MutationUserDelete: The result of the mutation.
        """

        # Cleanup the Auth0 user ID.
        auth0_user_id = clean_auth0_user_id(auth0_user_id=str(auth0_user_id))

        # Check that the requesting user is authorized to upsert the user with
        # the given Auth0 ID.
        check_auth(info=info, auth0_user_id=auth0_user_id)

        # Retrieve the session out of the context as the `get_query` method
        # automatically selects the model.
        session = info.context.get("session")  # type: sqlalchemy.orm.Session

        # Retrieve the `ModelUser` record object.
        query = session.query(ModelUser)
        query = query.filter(ModelUser.auth0_user_id == auth0_user_id)
        obj = query.one_or_none()  # type: ModelUser

        # Raise an exception if the requested user could not be found.
        if not obj:
            msg = "User with Auth0 ID '{}' could not be found."
            msg_fmt = msg.format(auth0_user_id)
            raise graphql.GraphQLError(message=msg_fmt)

        # Delete the `ModelSearch` records related to this user as well as all
        # `ModelUserSearch` and `ModelSearchDescriptor` records related to
        # those searches.
        delete_user_searches(session=session, user_id=obj.user_id)

        # Delete all `ModelUserStudy` records related to this user.
        query = session.query(ModelUserStudy)
        query = query.filter(ModelUserStudy.user_id == obj.user_id)
        query.delete()

        # Delete all `ModelUserCitation` records related to this user.
        query = session.query(ModelUserCitation)
        query = query.filter(ModelUserCitation.user_id == obj.user_id)
        query.delete()

        # Delete the `ModelUser` record.
        session.delete(obj)
        session.commit()

        return MutationUserDelete(user=obj)
コード例 #21
0
ファイル: searches.py プロジェクト: bearnd/fightfor-graphql
    def resolve_by_search_uuid(
        args: dict,
        info: graphene.ResolveInfo,
        auth0_user_id: str,
        search_uuid: str,
    ) -> ModelSearch:
        """ Retrieves a `ModelUser` record object through its Auth0 IDs.

        Args:
            args (dict): The resolver arguments.
            info (graphene.ResolveInfo): The resolver info.
            auth0_user_id (str): The Auth0 ID of the user to which the search
                belongs.
            search_uuid (uuid.UUID): The search UUID for which the
                `ModelSearch` record object will be retrieved.

        Returns:
             ModelSearch: The retrieved `ModelSearch` record object or `None`
                if no matches were found.
        """

        # Cleanup the Auth0 user ID.
        auth0_user_id = clean_auth0_user_id(auth0_user_id=str(auth0_user_id))

        # Check that the requesting user is authorized to retrieve the user with
        # the given Auth0 ID.
        check_auth(info=info, auth0_user_id=auth0_user_id)

        # Retrieve the query on `ModelSearch`.
        query = TypeSearch.get_query(
            info=info,
        )  # type: sqlalchemy.orm.query.Query

        # Filter to the `ModelSearch` record matching the `search_uuid`.
        query = query.filter(ModelSearch.search_uuid == search_uuid)

        # Limit query to fields requested in the GraphQL query adding
        # `load_only` and `joinedload` options as required.
        query = apply_requested_fields(
            info=info,
            query=query,
            orm_class=ModelSearch,
        )

        obj = query.one_or_none()

        # Raise an exception if the requested search could not be found.
        if not obj:
            msg = "Search with UUID '{}' could not be found."
            msg_fmt = msg.format(search_uuid)
            raise graphql.GraphQLError(message=msg_fmt)

        return obj
コード例 #22
0
    def resolve_search_by_house(self, info, house_name):
        staff_query = StaffNode.get_query(info)
        student_query = StudentNode.get_query(info)
        house_query = HouseNode.get_query(info)
        if not house_name:
            raise gq.GraphQLError('Please provide house name')

        house = house_query.filter(HouseModel.name == house_name).first()

        staff_results = staff_query.filter(StaffModel.house == house).all()
        student_results = student_query.filter(StudentModel.house == house).all()
        return staff_results + student_results
コード例 #23
0
def resolveUser(root, info, token):
    try:
        decoded = auth.decodeToken(token)

        response = requests.get("{}/users/{}".format(config.HARAMBE_DATA_SERVICE_ENDPOINT, decoded.get("user_id")))

        assert(response.status_code == 200), "Could not retrieve user"

        data = response.json()
        return serializeUser(data)
    except AssertionError as e:
        raise graphql.GraphQLError(e)
コード例 #24
0
def getBrokerAccounts(user_id, user_token):
    try:
        accountResponse = requests.post(
            "{}/getAccounts".format(config.HARAMBE_TRADING_SERVICE_ENDPOINT),
            json={"user_id": user_id, "user_token": user_token}
        )

        assert (accountResponse.status_code == 200), "Could not retrieve list of broker accounts"

        accountData = accountResponse.json()
        return accountData.get("accounts")
    except AssertionError as e:
        raise graphql.GraphQLError(e)
コード例 #25
0
    def mutate_and_get_payload(cls, root, info, **input):
        course_id = input.get('id')
        object_type, object_id = from_global_id(course_id)
        if object_type != 'Course':
            raise graphql.GraphQLError('Bad course id')

        index, course = [(i, c) for i, c in enumerate(COURSES)
                         if c.id == object_id][0]

        course.description = input.get('description')
        COURSES[index] = course

        return UpdateCourseDescription(course=course)
コード例 #26
0
ファイル: Sample.py プロジェクト: querat/graphQL
    def mutate(root, info, **kwargs):
        boxId           = kwargs.get("boxId")
        boxAuthCode     = kwargs.get("boxAuthCode")
        sampleInputs    = kwargs.get("samples")
        box             = None

        try:
            box = Box.objects.get(pk=boxId)
        except Box.DoesNotExist:
            raise graphql.GraphQLError("Box #{} does not exist".format(boxId))

        if box.authCode != boxAuthCode:
            raise graphql.GraphQLError("Invalid box authentication code")

        nbSentSamples = 0
        for sampleInput in sampleInputs:
            dbSample        = Sample()
            sampleModule    = None
            try:
                sampleModule = Module.objects.get(pk=sampleInput.moduleId)
            except:
                raise graphql.GraphQLError("module #{} does not exist".format(sampleInput.moduleId))
            [setattr(dbSample, key, value) for key, value in sampleInput.items()]
            dbSample.module = sampleModule
            dbSample.save(force_insert=True)
            nbSentSamples += 1

        # Send the new samples to the analyzer.
        # If an environmental anomaly is detected,
        # it will notify the user owning the box
        DataMonitor.analyzeNewSamples(
            user=box.user
            , box=box
            , sampleList=sampleInputs
        )

        return SendSamples(nbSentSamples=nbSentSamples)
コード例 #27
0
def resolveReports(root, info, token, accountNumber):
    try:
        response = requests.get(
            "{}/reports?broker_account_number__$eq={}".format(
                config.HARAMBE_DATA_SERVICE_ENDPOINT, accountNumber))

        assert (
            response.status_code == 200), "Could not retrieve list of reports"

        data = response.json()
        reports = [serializeReport(r) for r in data]

        return reports
    except AssertionError as e:
        raise graphql.GraphQLError(e)
コード例 #28
0
    def mutate(self, info, token, brokerId, accountNumber, description):
        try:
            auth.decodeToken(token)

            report = makeReport(brokerId, accountNumber, description)

            response = requests.post("{}/reports".format(
                config.HARAMBE_DATA_SERVICE_ENDPOINT),
                                     json=report)

            assert (response.status_code == 200), "Could not create report"

            return serializeReport(report)
        except AssertionError as e:
            raise graphql.GraphQLError(e)
コード例 #29
0
    def mutate(root, info, **kwargs):
        threshold = Threshold()
        thresholdInput = kwargs.get("thresholdInput")

        requiredArgs = ["name", "default", "min", "max", "current"]
        for requiredArgKey in requiredArgs:
            valueFromInput = getattr(thresholdInput, requiredArgKey)
            if valueFromInput is None:
                raise graphql.GraphQLError(
                    f"Missing argument: {requiredArgKey}")
            setattr(threshold, requiredArgKey, valueFromInput)

        moduleIdOfThreshold = thresholdInput.get("moduleId")
        if moduleIdOfThreshold is None:
            raise graphql.GraphQLError(f"Missing argument: moduleId")
        moduleOfThreshold = Module.objects.filter(
            id=moduleIdOfThreshold).first()
        if moduleOfThreshold is None:
            raise graphql.GraphQLError(
                "module #{} does not exist !".format(moduleIdOfThreshold))
        threshold.module = moduleOfThreshold

        threshold.save(force_insert=True)
        return CreateThreshold(threshold=threshold)
コード例 #30
0
def resolveBroker(root, info, _id, token):
    try:
        # decode token
        auth.decodeToken(token)

        response = requests.get(
            "{}/brokers/{}".format(config.HARAMBE_DATA_SERVICE_ENDPOINT, _id))
        assert (response.status_code == 200), "Could not retrieve broker"

        data = response.json()

        broker = serializeBroker(data)
        return broker
    except AssertionError as e:
        raise graphql.GraphQLError(e)