class User(ObjectType): id = ID(required=True) external_id = ID(required=True) email = String(required=True) """Deprecated""" name = String(required=True) first_name = String(required=True) last_name = String(required=True) picture_url = String(required=False) companies = List(NonNull(Company), resolver=companies_by_principal) def resolve_name(root, info): return "{} {}".format(root["first_name"], root["last_name"])
class Team(ObjectType): id = Int(required=True) webSite = String() contactEmail = String() since = DateTime(required=True) riders = List(NonNull(lambda: Rider), required=True) def resolve_rides(team, info): db_cursor.execute( """ SELECT rider.id, firstName, lastName, email, birthday FROM rider INNER JOIN teamMember tm ON rider.id = tm.cyclistId WHERE tm.cyclistId = %(team_pk)s """, {"team_pk": team['team_id']}) return [Rider(**row_data) for row_data in db_cursor.fetchall()]
class Query(ObjectType): goodbye = String() posts = List(NonNull(Post)) def resolve_posts(root, info): return [ Post(id=1, title='title1', text='text1', files=[FileNode(id=1)]), Post(id=2, title='title2', text='text2', files=[FileNode(id=2), FileNode(id=3)]), Post(id=3, title='title3', text='text3'), ] def resolve_goodbye(root, info): return 'See ya!'
class Query(object): """ We don't want to have any root queries here """ invest_bucket = Field(GInvestmentBucket, args={'id_value': Argument(NonNull(ID))}) @staticmethod def resolve_invest_bucket(_self, info, id_value, **_args): """ The viewer represents the current logged in user """ if not info.context.user.is_authenticated(): return None return InvestmentBucket.accessible_buckets( info.context.user.profile).get(id=from_global_id(id_value)[1])
def type(self): from .types import DjangoObjectType _type = super(ConnectionField, self).type non_null = False if isinstance(_type, NonNull): _type = _type.of_type non_null = True assert issubclass( _type, DjangoObjectType ), "DjangoConnectionField only accepts DjangoObjectType types" assert _type._meta.connection, "The type {} doesn't have a connection".format( _type.__name__) connection_type = _type._meta.connection if non_null: return NonNull(connection_type) return connection_type
class Supply(ObjectType): id = ID(required=True) is_active = Boolean(required=True) name = String(required=True) description = String(required=False) skills = List(NonNull(Skill), required=True) quantity = Int(required=True) hourly_salary = Float(required=False) company = Field(lambda: Company, required=True, resolver=company_by_id) def resolve_skills(root, info): if root.skills is None: return [] return g.skill_loader.load_many(root.skills)
class Query(ObjectType): user_by_email: Field = Field( UserType, required=False, email=String(required=True), ) users: NonNull = NonNull(List(UserType, required=False), offset=Int(required=False)) async def resolve_user_by_email(self, info: ResolveInfo, **kwargs) -> typing.Union[None, UserType]: userData: typing.Union[None, UserType] = None result: typing.Union[typing.Mapping, None] = None email: str = kwargs.get('email', '').strip() if bool(email): # fetch one user based on the provided email: result = await fetch_one_record_filter_by_one_field( table=UserTable, filterField='email', filterValue=email) if not result is None: userData = dict(result) # remove password before sending to next operation userData.pop('hashed_password') return userData async def resolve_users( self, info: ResolveInfo, **kwargs) -> typing.Union[List, typing.List[UserType]]: users: list = [] offset: int = kwargs.get('offset', 0) fetchResult: typing.Union[ None, typing.List[typing.Mapping]] = await fetch_multiple_records( table=UserTable, offset=offset) if not fetchResult is None: for result in fetchResult: userData: typing.Mapping[str, typing.Any] = dict(result) # remove 'hashed_password' field first: userData.pop('hashed_password') users.append(userData) return users
class Query(ObjectType): goodbye = String() posts = List(NonNull(Post)) def resolve_posts(root, info): return [ Post(id=1, title='title1', text=FunnyText(id=1), files=[FileNode(id=1)]), Post(id=2, title='title2', text=FunnyText(id=2), files=[FileNode(id=2), FileNode(id=3)]), Post(id=3, title='title3', text=FunnyText(id=3)), Post( id=4, title='title4', text=FunnyText(id=4), author=User(primaryEmail="*****@*****.**") ), ] def resolve_goodbye(root, info): return 'See ya!'
class TagType(ObjectType): name = String(required=True, name=String()) articles = List(NonNull(ArticleType)) @staticmethod def resolve_name(parent, info, **kwargs): return parent.name # Remember to pass email into to fetch a certain user's articles @staticmethod def resolve_articles(parent, info, **kwargs): # Todo: Allowing query for a certain article with certain url article_urls = UserArticle.objects.filter( email=kwargs['email'], tag_name=parent.name ).first().urls return [ArticleType(url=article_url) for article_url in article_urls]
def __init__(self, ndb_key_prop, graphql_type_name, *args, **kwargs): self.__ndb_key_prop = ndb_key_prop self.__graphql_type_name = graphql_type_name is_repeated = ndb_key_prop._repeated is_required = ndb_key_prop._required _type = String if is_repeated: _type = List(_type) if is_required: _type = NonNull(_type) kwargs['args'] = { 'ndb': Argument(Boolean, False, description="Return an NDB id (key.id()) instead of a GraphQL global id") } super(NdbKeyStringField, self).__init__(_type, *args, **kwargs)
class Query(AbstractType): """ We don't want to have any root queries here """ invest_bucket = Field(GInvestmentBucket, args={'id': Argument(NonNull(ID))}) @staticmethod def resolve_invest_bucket(_self, args, context, _info): """ The viewer represents the current logged in user """ if not context.user.is_authenticated(): return None return InvestmentBucket.objects.filter( Q(public=True) | Q(owner=context.user.profile)).get( id=from_global_id(args['id'])[1])
class LoginUser(Mutation): success = NonNull(Boolean) account = Field(UserType) token = String() message = String() class Arguments: username = NonNull(String) password = NonNull(String) @staticmethod def mutate(root, info, username, password): user = authenticate(username=username, password=password) if not user: return LoginUser(success=False, message="Invalid Credentials") login(info.context, user) token, _ = Token.objects.get_or_create(user=user) return LoginUser(success=True, account=user, token=token)
class Settings(ObjectType): default_subdomains = Field(NonNull(List(NonNull(String)))) ipv4 = Field(NonNull(List(NonNull(String)))) ipv6 = Field(NonNull(List(NonNull(String)))) domains = Field(NonNull(List(NonNull(Domain)))) async def resolve_default_subdomains(self, info: ResolveInfo): if info.context.get('current_user'): return Config()['settings']['default_subdomains'] async def resolve_ipv4(self, info: ResolveInfo): if info.context.get('current_user'): return Config()['settings']['ipv4'] async def resolve_ipv6(self, info: ResolveInfo): if info.context.get('current_user'): return Config()['settings']['ipv6'] async def resolve_domains(self, info: ResolveInfo): if info.context.get('current_user'): return create_domain_list(Config())
class CompoundType(ObjectType): CID = NonNull(String) MolecularFormula = String() MolecularWeight = Float() CanonicalSMILES = String() IsomericSMILES = String() InChI = String() InChIKey = String() IUPACName = String() XLogP = Float() ExactMass = Float() MonoisotopicMass = Float() TPSA = Float() Complexity = Int() Charge = Int() HBondDonorCount = Int() HBondAcceptorCount = Int() RotatableBondCount = Int() HeavyAtomCount = Int() IsotopeAtomCount = Int() AtomStereoCount = Int() DefinedAtomStereoCount = Int() UndefinedAtomStereoCount = Int() BondStereoCount = Int() DefinedBondStereoCount = Int() UndefinedBondStereoCount = Int() CovalentUnitCount = Int() Volume3D = Float() XStericQuadrupole3D = Float() YStericQuadrupole3D = Float() ZStericQuadrupole3D = Float() FeatureCount3D = Int() FeatureAcceptorCount3D = Int() FeatureDonorCount3D = Int() FeatureAnionCount3D = Int() FeatureCationCount3D = Int() FeatureRingCount3D = Int() FeatureHydrophobeCount3D = Int() ConformerModelRMSD3D = Int() EffectiveRotorCount3D = Float() ConformerCount3D = Float() Fingerprint2D = String()
class ToggleFollowUser(ObjectMutation): ok = Boolean(required=True) errors = NonNull(List(String, required=False)) class Arguments: toUserId = Int(required=True) async def mutate(self, info: ResolveInfo, **kwargs): ok: bool = False errors: typing.List[str] = [] existingFollowingRecord: typing.Union[None, typing.Mapping] user: BaseUser = info.context['request'].user # check user authenticated or not: if user.is_authenticated: # get toUserId: toUserId: typing.Union[int, None] = kwargs.get('toUserId', None) if toUserId and isinstance(toUserId, int): # checking if this following relation ship does exist or not: if toUserId != user.id: query: Select = select([UserFollowingTable]).where( and_(UserFollowingTable.c.from_user_id == user.id, UserFollowingTable.c.to_user_id == toUserId)) existingFollowingRecord = await fetch_one_record_with_query( query=query) ok = True else: errors.append('You cannot follow yourself.') else: errors.append('Invalid id of user.') else: errors.append('You have to log in to follow people.') if ok and len(errors) == 0: # add background task background: BackgroundTasks = info.context['background'] background.add_task(update_user_following, toUserId, user.id, existingFollowingRecord) return ToggleFollowUser(ok=ok, errors=errors)
class Dns(ObjectType): generate = Field(NonNull(Result)) def strip(self, text): return '\n'.join([x.lstrip() for x in text.split('\n')]) async def resolve_generate(self, info: ResolveInfo): if info.context.get('current_user'): # Check environment result = check_docker_container() if result: return result result = check_root() if result: return result # Generate zone file zone_file = ZoneFile() for domain, template_output in zone_file.generate_zones(): path = join(abspath(sep), 'etc', 'bind', domain + '.zone') try: with open(path, 'w') as f: f.write(self.strip(template_output)) except IOError: return Result('cannot write to ', extra=path) path = join(abspath(sep), 'etc', 'bind', 'named.conf.local') # Generate named.conf try: with open(path, 'w') as f: template_output = ( NamedConfLocal().generate_named_conf_local()) f.write(self.strip(template_output)) except IOError: return Result('cannot write to ', extra=path) # Restart bind run([join(abspath(sep), 'etc', 'init.d', 'bind9'), 'restart']) return Result() else: return Result('not logged in')
class Dataset(ObjectType): id = NonNull(ID) title = String(description="The title of the dataset") clusters = List(Cluster, description="The clusters the algorithms were trained on") def __init__(self, dataset, **args): super().__init__(**args) self._dataset = dataset @staticmethod def resolve_title(root, info): return root._dataset['title'] @staticmethod def resolve_clusters(root, info): return [ Cluster(name=cluster['name']) for cluster in root._dataset['clusters'] ]
def __init__(self, _type, page_size=graphql_api_settings.DEFAULT_PAGE_SIZE, page_size_query_param=None, max_page_size=graphql_api_settings.MAX_PAGE_SIZE, ordering="", ordering_param='order', *args, **kwargs): kwargs.setdefault('args', {}) # Client can control the page using this query parameter. self.page_query_param = 'page' # The default page size. Defaults to `None`. self.page_size = page_size # Client can control the page size using this query parameter. # Default is 'None'. Set to eg 'page_size' to enable usage. self.page_size_query_param = page_size_query_param # Set to an integer to limit the maximum page size the client may request. # Only relevant if 'page_size_query_param' has also been set. self.max_page_size = max_page_size self.ordering = ordering self.ordering_param = ordering_param self.page_size_query_description = 'Number of results to return per page. Actual \'page_size\': {}'.format( self.page_size) kwargs[self.page_query_param] = Int(default_value=1, description='A page number within the result paginated set. Default: 1') kwargs[self.ordering_param] = String(default_value='', description='A string or coma separate strings values that indicating the ' 'default ordering when obtaining lists of objects.') if self.page_size_query_param: if not page_size: kwargs[self.page_size_query_param] = NonNull(Int, description=self.page_size_query_description) else: kwargs[self.page_size_query_param] = Int(description=self.page_size_query_description) super(PagePaginationField, self).__init__(List(_type), *args, **kwargs)
class CountedConnection(Connection): """ copied from https://github.com/graphql-python/graphene-sqlalchemy/issues/153#issuecomment-501949939 """ class Meta: # Being abstract is important because we can't reference the # node type here without creating a circular reference. Also, it # makes reuse easy. # # The node type will be populated later with # `CountedConnection.create_class()` in `Foo`'s # `__init_subclass_with_meta__()`. abstract = True total_count = NonNull(Int) def resolve_total_count(self, info, **kwargs): return self.length
class ChangePasswordMutation(Mutation): class Arguments: old_password = NonNull(String) new_password = NonNull(String) committed = NonNull(Boolean) @classmethod @login_required def mutate(cls, root, info, old_password, new_password, *args, **kwargs): # get current user user = info.context.user # reset if old password valid committed = False if user.check_password(old_password): user.set_password(new_password) user.save() committed = True return ChangePasswordMutation(committed=committed)
class Query(graphene.ObjectType): chats = graphene.List(NonNull(Chat), required=True) chat = graphene.Field(Chat, chat_id=graphene.ID(name='id', required=True)) player = graphene.Field(Player, player_id=graphene.ID(name='id', required=True)) my_profile = graphene.Field(TelegramProfile) @staticmethod def resolve_my_profile(root, info): return get_telegram_profile(info.context) @staticmethod def resolve_chats(root, info): return archive.Chat.objects.filter(parent=None).all() @staticmethod def resolve_chat(root, info, chat_id: str): return archive.Chat.objects.filter(id=chat_id).first() @staticmethod def resolve_player(root, info, player_id: str): return game.Player.objects.filter(id=player_id).first()
def type(self): _type = super(ConnectionField, self).type non_null = False if isinstance(_type, NonNull): _type = _type.of_type non_null = True assert issubclass( _type, ModelObjectType ), "DjangoConnectionField only accepts ModelObjectType types" assert _type._meta.connection, "The type {} doesn't have a connection".format( _type.__name__) if (_type._meta.filter_fields or _type._meta.filterset_class ) and type(self).__name__ == 'RelayConnectionField': warnings.warn( "Using fiterns in a RelayConnectionField(%s). Consider to use a RelayFilterConnectionField instead." % _type._meta.name, ) connection_type = _type._meta.connection if non_null: return NonNull(connection_type) return connection_type
class StockType(ObjectType): name = String(required=True) symbol = String(required=True, symbol=String()) # Index in Cassandra price = Int() articles = List(NonNull(ArticleType), start=Int(default_value=1)) # start for pagination @staticmethod def resolve_name(parent, info, **kwargs): return kwargs['name'] @staticmethod def resolve_symbol(parent, info, **kwargs): return kwargs['symbol'] @staticmethod def resolve_price(parent, info, **kwargs): prices = fetch_stock_current_data(kwargs['symbol']) list_prices = list(prices.items()) price = list_prices[0][1]['4. close'] return price @staticmethod def resolve_articles(parent, info, **kwargs): # Todo: Try different search term & use NLP to pick out the best time_range = 'date:r:' if kwargs.get('start_date', None): time_range += str(kwargs['start_date']) time_range += ':' + kwargs['end_date'] articles = fetch_url_metadata(kwargs['name'] + ' market news', start=kwargs['start'], sort=time_range) return [ArticleType(article=article) for article in articles]
class Query(ObjectType): categories = NonNull( List(CategoryType, required=False) ) async def resolve_categories(self, info: ResolveInfo, **kwargs): allCategories: typing.List[typing.Mapping[str, typing.Any]] = [] """ returns all categories and their subs """ query: Select = select([ CategoryTable ]) print(query) result = await database.fetch_all(query=query) for row in result: print(dict(row)) # for d in fetchResult: # print(dict(d)) return allCategories
class Query(ObjectType): posts = Field(List(NonNull(Post)), post_filter=Argument(PostFilterInput, required=True)) def resolve_posts(parent, info, post_filter: PostFilterInput): if post_filter.uuid is None: return [ Post( uuid=p.id, weight=p.content.weight, size=p.content.size, ) for p in repository.list() ] else: p = repository.get(UUID(post_filter.uuid)) if not p: return [] return [ Post( uuid=p.id, weight=p.content.weight, size=p.content.size, ) ]
class Demand(ObjectType): id = ID(required=True) is_active = Boolean(required=True) name = String(required=True) description = String(required=False) skills = List(NonNull(Skill), required=True) quantity = Int(required=True) max_hourly_salary = Float(required=False) company = Field(lambda: Company, required=True, resolver=company_by_id) # we only have this for now def resolve_description(root, info): if root.description_ext is None: return None return root.description_ext def resolve_skills(root, info): if root.skills is None: return [] return g.skill_loader.load_many(root.skills)
class GProfile(DjangoObjectType): """ GraphQL representation of a Profile """ stock_find = List(GStock, args={ 'text': Argument(NonNull(String)), 'first': Argument(Int) }) invest_suggestions = DjangoFilterConnectionField(GInvestmentBucket, ) class Meta(object): """ Meta Model for Profile """ model = Profile only_fields = ('id', 'trading_accounts', 'stock_find') interfaces = (relay.Node, ) @staticmethod def resolve_stock_find(_self, args, _context, _info): """ Finds a stock given a case insensitive name """ query = Stock.objects.filter(name__icontains=args['text']) if 'first' in args: query = query[:args['first']] return query @staticmethod def resolve_invest_suggestions(_data, _args, context, _info): """ Finds all the investment suggestions available to the user """ return InvestmentBucket.objects.filter( Q(owner=context.user.profile) | Q(public=True))
class TalkType(ObjectType): class Meta: name = "Talk" id = NonNull(ID) title = NonNull(String) speakers = NonNull(List(NonNull(SpeakerType))) is_open_discussion = NonNull(Boolean) is_mine = NonNull(Boolean) @staticmethod def resolve_speakers(parent: Talk, info): return [parent.owner, *parent.other_speakers.all()] @staticmethod def resolve_is_open_discussion(parent: Talk, info): return parent.open_discussion @staticmethod def resolve_is_mine(parent: Talk, info): return parent.owner == info.context.user
class Document(MongoengineObjectType): class Meta: connection_field_class = DocumentConnectionField model = DocumentModel interfaces = (Node,) filter_fields = { "title": ["icontains"], # "privacy_settings": ["users_access"], } author = NonNull("graph.types.user.User") is_author = NonNull(Boolean) @jwt_optional def resolve_is_author(root, info): return current_user is not None and current_user == root.author access_permission = NonNull(AccessEnum) @jwt_optional def resolve_access_permission(root, info): privacy: PrivacySettings = root.privacy_settings if current_user.pk == root.author.pk: return EDIT if privacy.visibility == PRIVATE: return NONE elif privacy.visibility == USERS: for user_access in privacy.users_access: if user_access.user.pk == current_user.pk: return user_access.access_type return NONE else: return privacy.public_access_type contents = NonNull(List(NonNull(DocumentSection))) privacy_settings = NonNull(PrivacySettings)
def convert_field_to_boolean(field, registry=None): return NonNull(Boolean, description=field.help_text)