Example #1
0
class AlumnoType(DjangoObjectType):
    padre = graphene.Field(PadreDeFamiliaType)
    madre = graphene.Field(PadreDeFamiliaType)
    representante = GenericScalar()
    contacto_emergencia = GenericScalar()
    test = GenericScalar()

    persona_str = graphene.String()

    class Meta:
        model = Alumno

    def resolve_padre(self, info):
        return self.padre

    def resolve_madre(self, info):
        return self.madre

    def resolve_representante(self, info):
        return self.representante

    def resolve_contacto_emergencia(self, info):
        return self.contacto_emergencia

    def resolve_persona_str(self: Alumno, info):
        return self.persona.__str__()
Example #2
0
class Parameters(ObjectType):
    class Meta:
        interfaces = relay.Node,

    _path = String(
        description="The true path to the parameter file. Internal use only")
    keys = List(String, description="list of parameter keys")
    value = GenericScalar(description="the json value for the parameters")
    raw = GenericScalar(description="the raw data object for the parameters")
    flat = GenericScalar(description="the raw data object for the parameters")

    def resolve_keys(self, info):
        value = reduce(assign,
                       read_json(join(Args.logdir, self.id[1:])) or [{}])
        return dot_keys(value)

    def resolve_value(self, info, **kwargs):
        return reduce(assign,
                      read_json(join(Args.logdir, self.id[1:])) or [{}])

    def resolve_raw(self, info, **kwargs):
        return read_json(join(Args.logdir, self.id[1:]))

    def resolve_flat(self, info, **kwargs):
        value = reduce(assign,
                       read_json(join(Args.logdir, self.id[1:])) or [{}])
        return dot_flatten(value)

    # description = String(description='string serialized data')
    # experiments = List(lambda: schema.Experiments)

    @classmethod
    def get_node(cls, info, id):
        return get_parameters(id)
Example #3
0
class PostMeta(graphene.ObjectType):
    # image = GenericScalar(first=graphene.Boolean())
    app = GenericScalar()
    # location = GenericScalar()
    tags = GenericScalar()
    # format = graphene.String()
    meta = GenericScalar()

    def resolve_meta(self, info):
        return prepare_json(self)

    # def resolve_format(self, info):
    #     return self.get('format', None)

    def resolve_tags(self, info):
        meta = prepare_json(self)
        return meta.get('tags', [])

    # def resolve_image(self, info, first=False):
    #     images = self.get('image', [])

    #     if images:
    #         return images[0] if first else images

    #     return []

    def resolve_app(self, info):
        meta = prepare_json(self)
        return meta.get('app', 'undefined')
Example #4
0
class TransactionType(graphene.ObjectType):
    name = 'Transaction'
    description = '...'

    id = graphene.String()
    operation = graphene.String()
    version = graphene.String()
    asset = GenericScalar()
    metadata = GenericScalar()
    inputs = graphene.List(InputType)
    outputs = graphene.List(OutputType)

    @classmethod
    def from_json(cls, retrieved_tx):
        outputs = [
            OutputType.from_json(output) for output in retrieved_tx['outputs']
        ]
        inputs = [
            InputType.from_json(input_) for input_ in retrieved_tx['inputs']
        ]

        return cls(
            id=retrieved_tx['id'],
            version=retrieved_tx['version'],
            inputs=inputs,
            outputs=outputs,
            operation=retrieved_tx['operation'],
            asset=retrieved_tx['asset'],
            metadata=retrieved_tx['metadata'],
        )
Example #5
0
class PostMeta(graphene.ObjectType):
    image = GenericScalar(first=graphene.Boolean())
    app = GenericScalar()
    location = GenericScalar()
    tags = GenericScalar()
    format = graphene.String()
    json_metadata = GenericScalar()

    def resolve_json_metadata(self, info):
        return prepare_json(self.json_metadata)

    def resolve_format(self, info):
        return self.get('format', None)

    def resolve_tags(self, info):
        return self.get('tags', [])

    def resolve_image(self, info, first=False):
        images = self.get('image', [])

        if images:
            return images[0] if first else images

        return []

    def resolve_app(self, info):
        return self.get('app', 'undefined')

    def resolve_location(self, info):
        return self.get('location', {})
 def generate(cls, node_class, connection_class, arguments={}, returns={}):
     pk_field_name = node_class._meta.model._meta.primary_key.name
     args = {pk_field_name: node_class._meta.fields[pk_field_name].type.Argument(),
             RELATED_FIELD: GenericScalar(),
             DATA_FIELD: GenericScalar()}
     args.update(arguments)
     attrs = {AFFECTED_FIELD: PeeweeNodeField(node_class)}
     attrs.update(returns)
     return super().generate(node_class, connection_class, args, attrs)
Example #7
0
class File(ObjectType):
    class Meta:
        interfaces = relay.Node,

    name = String(description='name of the directory')
    stem = String(description="stem of the file name")
    path = String(description='path to the file')

    def resolve_stem(self, info, ):
        return self.name.split('.')[0]

    def resolve_path(self, info):
        return self.id

    text = String(description='text content of the file',
                  start=Int(required=False, default_value=0),
                  stop=Int(required=False, default_value=None))

    def resolve_text(self, info, start=0, stop=None):
        from ml_dash.config import Args
        with open(join(Args.logdir, self.id[1:]), "r") as f:
            lines = list(f)[start: stop]
            return "".join(lines)

    json = GenericScalar(description="the json content of the file")

    def resolve_json(self, info):
        import json
        try:
            from ml_dash.config import Args
            with open(join(Args.logdir, self.id[1:]), "r") as f:
                return json.load(f)
        except FileNotFoundError:
            return None

    yaml = GenericScalar(description="the content of the file using yaml")

    def resolve_yaml(self, info):
        import ruamel.yaml
        if ruamel.yaml.version_info < (0, 15):
            yaml = ruamel.yaml
            load_fn = yaml.safe_load
        else:
            from ruamel.yaml import YAML
            yaml = YAML()
            yaml.explict_start = True
            load_fn = yaml.load

        from ml_dash.config import Args
        with open(join(Args.logdir, self.id[1:]), "r") as f:
            return load_fn('\n'.join(f))

    @classmethod
    def get_node(cls, info, id):
        return get_file(id)
Example #8
0
class UserType(DjangoObjectType):
    class Meta:
        model = User
        only_fields = ('username', 'display_name', 'school', 'company',
                       'location', 'about', 'tried', 'solved')

    gravataremail = graphene.String()
    group = graphene.String()
    heatmap = GenericScalar()
    analysis = GenericScalar()

    def resolve_group(self, info, *args, **kwargs):
        return Group.get_user_group(self.group).value.display

    def resolve_heatmap(self, info, *args, **kwargs):
        import datetime
        import time
        from submission.models import Submission
        from user.models import User
        now = datetime.datetime.now()
        start_date = now - datetime.timedelta(days=366)
        s = Submission.objects.filter(user=self,
                                      submit_time__date__gt=start_date)
        s = s.annotate(date=Cast(TruncDate('submit_time'), CharField()))
        s = s.order_by('date')
        s = s.values('date')
        s = s.annotate(count=Count('submission_id'))
        return list(s)

    def resolve_analysis(self, info, *args, **kwargs):
        from submission.models import Submission
        from submission.judge_result import Judge_result
        s = Submission.objects.filter(user=self)
        privilege = info.context.user.has_perm('problem.view_all')
        if not privilege:
            s = Submission.objects.filter(problem__visible=True)
        solved = set()
        tried = set()
        trans = dict()
        for each in s:
            pk = each.problem.pk
            tried.add(pk)
            if pk not in trans:
                trans[pk] = each.problem.slug
            if Judge_result.get_judge_result(
                    each.judge_status) is Judge_result.AC:
                solved.add(pk)
        return sorted([(each, 'yes' if each in solved else 'no', trans[each])
                       for each in tried],
                      key=lambda x: x[0])
Example #9
0
class RevisionType(AuthNode, DjangoObjectType):
    """GraphQL representation of a Revision.
    """
    permission_classes = (WorkspaceTeamMembersOnly, )
    scope_to_workspace = True

    metadata = GenericScalar()
    parent_resource = graphene.Field(RelatedResourceType)
    related_resource = graphene.Field(RelatedResourceType)

    class Meta:
        model = models.Revision
        filter_fields = []
        interfaces = (relay.Node, )
        connection_class = connections.DefaultConnection
        exclude_fields = []

    def resolve_related_resource(instance, info):
        """Return the resource related to this Revision.
        """
        return info.context.loaders.related_revision_resources.load(
            instance.revision_id)

    def resolve_parent_resource(instance, info):
        """Return the resource related to this Revision.
        """
        if not instance.parent_resource_revision_id:
            return None
        return info.context.loaders.related_revision_resources.load(
            instance.parent_resource_revision_id)
Example #10
0
class Voyage(ObjectType):
    class Meta:
        interfaces = (Node, )

    id = ID(required=True)
    created = DateTime()
    modified = DateTime()

    name = String()

    media = Field('Media')

    owner = Field('User')
    members = List('User')

    comment_counts = GenericScalar()

    def resolve_comment_counts(root, info):
        # Initialize a dictionary with 0 comment count per chapter
        base_dict = dict.fromkeys(root.chapters, 0)

        counts = (db.session.query(Comment.chapter, func.count(
            Comment.id)).filter(Comment.voyage == root).group_by(
                Comment.chapter)).all()

        base_dict.update(dict(counts))
        return base_dict
Example #11
0
class VerifyMixin:
    payload = GenericScalar(required=True)

    @classmethod
    @ensure_token
    def verify(cls, root, info, token, **kwargs):
        return cls(payload=get_payload(token, info.context))
Example #12
0
class DeleteConsole(graphene.Mutation):
    """Delete a console."""

    response = GenericScalar()

    class Arguments:
        console_id = graphene.Int()

    async def mutate(parent, info, console_id):
        """Delete a console record with provided ID."""
        # Excute deletion query
        async with database.transaction():
            query = (console.delete().where(
                console.c.id == console_id).returning(console.c.id))
            try:
                record_deleted = await database.execute(query)
            except Exception as e:
                result = {"ok": False, "error": e}
            else:
                if not record_deleted:
                    result = {
                        "ok": False,
                        "error": "Problems deleting a console record",
                    }
                else:
                    result = {"ok": True}
            return DeleteConsole(response=result)
    class Query(graphene.ObjectType):
        test = GenericScalar(**{
            jwt_settings.JWT_ARGUMENT_NAME: graphene.String(),
        })

        def resolve_test(self, info, **kwargs):
            return info.context.user
Example #14
0
class GuidePageSection(graphene.ObjectType):
    value = GenericScalar()
    pages = graphene.List(GuidePageSectionPageBlock)
    heading = graphene.String()

    def resolve_heading(self, info):
        # We're doing our own translations in our model here
        # so let's make sure the API still works as expected
        if django.utils.translation.get_language() == 'en':
            return self.value['section_heading_en']
        elif django.utils.translation.get_language() == 'es':
            # if there is not a spanish translation available, return english
            if self.value['section_heading_es'] == '':
                return self.value['section_heading_en']
            return self.value['section_heading_es']
        elif django.utils.translation.get_language() == 'ar':
            return self.value['section_heading_ar']
        elif django.utils.translation.get_language() == 'vi':
            return self.value['section_heading_vi']

    def resolve_pages(self, info):
        repr_pages = []
        for page_id in self.value['pages']:
            repr_pages.append(GuidePageSectionPageBlock(value=page_id))

        return repr_pages
Example #15
0
class Log(DjangoObjectType):
    class Meta:
        model = models.Log
        exclude_fields = ('user_id', 'log_set', 'deleted')

    kind = Kind()
    entities = GenericScalar()
Example #16
0
class Clean(graphene.Mutation):
    class Meta:
        description = sstrip('''
            Clean a workflow from the run directory.
        ''')
        resolver = partial(mutator, command='clean')

    class Arguments:
        workflows = graphene.List(WorkflowID, required=True)
        rm = graphene.String(default_value='',
                             description=sstrip('''
                Only clean the specified subdirectories or files in
                the run directory, rather than the whole run.

                A colon separated list that accepts globs,
                e.g. ``.service/db:log:share:work/2020*``.
            '''))
        local_only = graphene.Boolean(default_value=False,
                                      description=sstrip('''
                Only clean on the local filesystem (not remote hosts).
            '''))
        remote_only = graphene.Boolean(default_value=False,
                                       description=sstrip('''
                Only clean on remote hosts (not the local filesystem).
            '''))

    result = GenericScalar()
class GeoJSON(graphene.ObjectType):
    type = graphene.String()
    coordinates = GenericScalar()

    class Meta:
        default_resolver = geojson_resolver
        name = 'CountriesGeoJSON'
Example #18
0
class Postmeta(NodeMixin, DjangoObjectType):
    meta_value_obj = GenericScalar()

    class Meta:
        model = models.Postmeta
        filterset_class = filters.PostmetaFilter
        interfaces = (graphene.Node, )
Example #19
0
class GeometryObjectType(graphene.ObjectType):
    type = graphene.String()
    coordinates = GenericScalar()

    class Meta:
        default_resolver = resolver.geometry_resolver
        description = """
Example #20
0
class ProfileField(SecureObjectType, SQLAlchemyObjectType):
    class Meta:
        model = models.ProfileField
        interfaces = (Node, )
        only_fields = ('id', )

    agent_profile = graphene.Field(lambda: AgentProfile)
    configurable_field = graphene.Field(lambda: ConfigurableFieldUnion, required=True)
    value_data = GenericScalar()

    def resolve_id(self, args, context, info):
        if self.id < 0:
            # this is a temporary object we created manually in resolve_profile_fields
            return self.id
        else:
            # this is a SQLAlchemy object
            # we can't use super here, so we just copy/paste resolve_id method from SQLAlchemyObjectType class
            from graphene.relay import is_node
            graphene_type = info.parent_type.graphene_type
            if is_node(graphene_type):
                return self.__mapper__.primary_key_from_instance(self)[0]
            return getattr(self, graphene_type._meta.id, None)

    def resolve_value_data(self, args, context, info):
        return getattr(self, 'value_data', {u'value': None})
class RefreshMutation(graphene.Mutation):
    token = graphene.String(required=True)
    payload = GenericScalar(required=True)
    refresh_token = graphene.String(required=True)

    class Arguments:
        refresh_token = graphene.String(required=True)

    def mutate(self, info, refresh_token):
        refresh_token = get_refresh_token(refresh_token)

        if refresh_token.revoked:
            raise JSONRefreshTokenExpired
        if refresh_token.is_expired():
            raise JSONRefreshTokenExpired

        refreshed_token = refresh_token.rotate()
        payload = jwt_payload(refresh_token.user,
                              refresh_token=refreshed_token.get_token())
        token = jwt_encode(payload)
        signals.refresh_finished.send(
            sender=RefreshToken,
            user=refresh_token.user,
            request=info.context,
        )
        return RefreshMutation(token=token,
                               payload=payload,
                               refresh_token=refreshed_token.get_token())
Example #22
0
class TransferGraphType(DjangoObjectType):
    date = graphene.String()
    total_item = graphene.Int()
    series = GenericScalar()

    class Meta:
        model = Transfer
Example #23
0
class ObtainPrivilegedJSONWebToken(graphene.Mutation):

    token = graphene.String()
    payload = GenericScalar(required=True)
    refresh_expires_in = graphene.Int(required=True)

    class Arguments:
        token = graphene.String(required=True)

    @classmethod
    def Field(cls, *args, **kwargs):
        cls._meta.arguments.update(
            {
                get_user_model().USERNAME_FIELD: graphene.String(required=True),
                "password": graphene.String(required=True),
            }
        )
        return super().Field(*args, **kwargs)

    @classmethod
    @graphql_jwt.decorators.staff_member_required
    @graphql_jwt.decorators.token_auth
    def mutate(cls, root, info, **kwargs):
        # print(root, info.context.token)
        return ObtainPrivilegedJSONWebToken()

    @classmethod
    def resolve(cls, root, info, **kwargs):
        cls()
Example #24
0
class Mutation(ObjectType):
    insert_patient = InsertPatient.Field()
    # insert_acceptance = InsertAcceptance.Field()
    add_acceptance = AddAcceptance.Field()

    # Insert Acceptance
    insert_acceptance = Field(Acceptance, req_data=GenericScalar())

    def resolve_insert_acceptance(self, info, req_data, **kwargs):
        print(req_data)
        # data = get_list()
        # sess = database.SessionLocal
        # sess.execute(PatientModel.__table__.insert(), data)
        # sess.commit()
        query = Acceptance.get_query(info)
        result = query.first()
        return result

    # Initialize Data
    init_pati_data = List(Patient)

    def resolve_init_pati_data(self, info, **kwargs):
        patient_query = Patient.get_query(info)
        result = patient_query.all()
        if len(result) == 0:
            data = get_list()
            sess = database.SessionLocal
            sess.execute(PatientModel.__table__.insert(), data)
            sess.commit()
            result = patient_query.all()
        return result

    init_depart_data = List(Department)

    def resolve_init_depart_data(self, info, **kwargs):
        depart_query = Department.get_query(info)
        result = depart_query.all()
        if len(result) == 0:
            ors = ORSystem(system_code="01")
            data = ors.get_info()
            sess = database.SessionLocal
            sess.execute(DepartmentModel.__table__.insert(), data)
            sess.commit()
            result = depart_query.all()
        return result

    init_phys_data = List(Physician)

    def resolve_init_phys_data(self, info, **kwargs):
        phys_query = Physician.get_query(info)
        result = phys_query.all()
        if len(result) == 0:
            ors = ORSystem(system_code="02")
            data = ors.get_info()
            sess = database.SessionLocal
            sess.execute(PhysicianModel.__table__.insert(), data)
            sess.commit()
            result = phys_query.all()
        return result
Example #25
0
class FieldData(graphene.AbstractType):
    __doc__ = docs.FieldData.__doc__

    configurable_field_id = graphene.ID(
        required=True, description=docs.FieldData.configurable_field_id)
    id = graphene.ID(required=True, description=docs.FieldData.id)
    value_data = GenericScalar(required=True,
                               description=docs.FieldData.value_data)
Example #26
0
class KbReference(content_types.Page):
    main = GenericScalar()
    topic = graphene.Field(lambda: KbTopic)

    def resolve_main(self, info):
        return self.main.stream_block.get_api_representation(self.main, info.context)

    def resolve_topic(self, info):
        return self.topic()
Example #27
0
class Offer(DjangoObjectType):
    class Meta:
        model = models.Offer

    main = GenericScalar()

    def resolve_main(self, info):
        return self.main.stream_block.get_api_representation(
            self.main, info.context)
Example #28
0
def model_connection(model):
    connection = CustomConnection.create_type(
        model.__name__ + "Connection", node=SQLAlchemyObjectTypes().get(model))
    return CustomConnectionField(
        connection,
        filters=GenericScalar(),
        limit=graphene.types.Int(),
        offset=graphene.types.Int(),
    )
Example #29
0
class AccountLocation(graphene.ObjectType):
    properties = GenericScalar()
    geometry = graphene.Field(GeometryObjectType)

    def resolve_properties(self, info):
        return self.get('properties', {})

    def resolve_geometry(self, info):
        return self.get('geometry', {})
Example #30
0
class PersonalType(DjangoObjectType):
    info = GenericScalar()
    persona_str = graphene.String()

    class Meta:
        model = Personal

    def resolve_persona_str(self: Personal, info):
        return self.persona.__str__()