import graphene from backend.graphql.query import Query as backend_query from backend.graphql.mutation import Mutation as backend_mutation from backend.model.translation_collection import translation_types class Query(backend_query, graphene.ObjectType): pass class Mutation(backend_mutation, graphene.ObjectType): pass schema = graphene.Schema(query=Query, mutation=Mutation, types=translation_types)
def test_should_query_dataloader_fields(): from promise import Promise from promise.dataloader import DataLoader def article_batch_load_fn(keys): queryset = Article.objects.filter(reporter_id__in=keys) return Promise.resolve( [[article for article in queryset if article.reporter_id == id] for id in keys]) article_loader = DataLoader(article_batch_load_fn) class ArticleType(DjangoObjectType): class Meta: model = Article interfaces = (Node, ) class ReporterType(DjangoObjectType): class Meta: model = Reporter interfaces = (Node, ) use_connection = True articles = DjangoConnectionField(ArticleType) def resolve_articles(self, info, **args): return article_loader.load(self.id) class Query(graphene.ObjectType): all_reporters = DjangoConnectionField(ReporterType) r = Reporter.objects.create(first_name='John', last_name='Doe', email='*****@*****.**', a_choice=1) Article.objects.create(headline='Article Node 1', pub_date=datetime.date.today(), pub_date_time=datetime.datetime.now(), reporter=r, editor=r, lang='es') Article.objects.create(headline='Article Node 2', pub_date=datetime.date.today(), pub_date_time=datetime.datetime.now(), reporter=r, editor=r, lang='en') schema = graphene.Schema(query=Query) query = ''' query ReporterPromiseConnectionQuery { allReporters(first: 1) { edges { node { id articles(first: 2) { edges { node { headline } } } } } } } ''' expected = { 'allReporters': { 'edges': [{ 'node': { 'id': 'UmVwb3J0ZXJUeXBlOjE=', 'articles': { 'edges': [{ 'node': { 'headline': 'Article Node 1', } }, { 'node': { 'headline': 'Article Node 2' } }] } } }] } } result = schema.execute(query) assert not result.errors assert result.data == expected
username = kwargs.get('username') user = query.filter(UserModel.email == email).first() user.username = username db_session.commit() ok = True return changeUsername(user=user, ok=ok) class Query(graphene.ObjectType): node = relay.Node.Field() user = SQLAlchemyConnectionField(Users) findUser = graphene.Field(lambda: Users, username=graphene.String()) # find_user = graphene.String(description='A f**k...') all_users = SQLAlchemyConnectionField(Users) def resolve_findUser(self, info, **kwargs): query = Users.get_query(info) username = kwargs.get('username') # you can also use and_ with filter() eg: filter(and_(param1, param2)).first() return query.filter(UserModel.username == username).first() class MyMutations(graphene.ObjectType): create_user = createUser.Field() change_username = changeUsername.Field() schema = graphene.Schema(query=Query, mutation=MyMutations, types=[Users])
users = graphene.List(UserType) problems = graphene.List(ProblemType) comments = graphene.List(CommentType) # problems = graphene.List() def resolve_users(self, context): query = UserType.get_query(context) return query.all() def resolve_problems(self, content): query = ProblemType.get_query(content) return query.all() def resolve_comments(self, context): query = CommentType.get_query(context) return query.all() class Mutation(graphene.ObjectType): create_user = CreateUser.Field() create_comment = CreateComment.Field() create_problem = CreateProblem.Field() get_user_token = GetUserToken.Field() schema = graphene.Schema(query=Query, mutation=Mutation, types=[UserType, ProblemType, CommentType])
def test_should_node(): # reset_global_registry() # Node._meta.registry = get_global_registry() class ReporterNode(DjangoObjectType): class Meta: model = Reporter interfaces = (Node, ) @classmethod def get_node(cls, info, id): return Reporter(id=2, first_name='Cookie Monster') def resolve_articles(self, info, **args): return [Article(headline='Hi!')] class ArticleNode(DjangoObjectType): class Meta: model = Article interfaces = (Node, ) @classmethod def get_node(cls, info, id): return Article(id=1, headline='Article node', pub_date=datetime.date(2002, 3, 11)) class Query(graphene.ObjectType): node = Node.Field() reporter = graphene.Field(ReporterNode) article = graphene.Field(ArticleNode) def resolve_reporter(self, info): return Reporter(id=1, first_name='ABA', last_name='X') query = ''' query ReporterQuery { reporter { id, firstName, articles { edges { node { headline } } } lastName, email } myArticle: node(id:"QXJ0aWNsZU5vZGU6MQ==") { id ... on ReporterNode { firstName } ... on ArticleNode { headline pubDate } } } ''' expected = { 'reporter': { 'id': 'UmVwb3J0ZXJOb2RlOjE=', 'firstName': 'ABA', 'lastName': 'X', 'email': '', 'articles': { 'edges': [{ 'node': { 'headline': 'Hi!' } }] }, }, 'myArticle': { 'id': 'QXJ0aWNsZU5vZGU6MQ==', 'headline': 'Article node', 'pubDate': '2002-03-11', } } schema = graphene.Schema(query=Query) result = schema.execute(query) assert not result.errors assert result.data == expected
class HelloWorldHandler(RequestHandler): def get(self, request): return Response(HTTPStatus.OK, 'hello world') def post(self, request): return Response(HTTPStatus.METHOD_NOT_ALLOWED) class Hello(graphene.ObjectType): hello = graphene.String(arg=graphene.String(default_value="world")) def resolve_hello(self, info, arg): return "Hello " + arg hello_schema = graphene.Schema(query=Hello) class HelloGraphQL(RequestHandler): def get(self, request): return Response(HTTPStatus.METHOD_NOT_ALLOWED) def post(self, request): if not request.json: return Response(HTTPStatus.BAD_REQUEST) res = hello_schema.execute(request.json['query']) return mkJSONResp(res) class User(graphene.ObjectType): id = graphene.Int() username = graphene.String() def __init__(self, id, username):
# TODO: Step 3 create this file import graphene from demo.api.graphql.endpoints.dummy_query import DummyQuery from demo.api.graphql.endpoints.dummy_mutation import DummyMutations class Queries(DummyQuery): pass class Mutations(DummyMutations): pass schema = graphene.Schema(query=Queries, mutation=Mutations)
from .article.queries import ArticleQuery from .article.mutations import ArticleMutation from .theme.queries import ThemeQuery from .theme.mutations import ThemeMutation from .feedback.queries import FeedbackQuery from .feedback.mutations import FeedbackMutation class QueryRoot(UserQuery, MoodQuery, HabitQuery, ActivityQuery, ArticleQuery, ThemeQuery, FeedbackQuery, graphene.ObjectType): pass class MutationRoot(UserMutation, MoodMutation, HabitMutation, ActivityMutation, ArticleMutation, ThemeMutation, FeedbackMutation, graphene.ObjectType): pass class AuthQueryRoot(AuthQuery, graphene.ObjectType): pass class AuthMutationRoot(AuthMutation, graphene.ObjectType): pass main_schema = graphene.Schema(query=QueryRoot, mutation=MutationRoot) auth_schema = graphene.Schema(query=AuthQueryRoot, mutation=AuthMutationRoot)
class Department(SQLAlchemyObjectType): class Meta: model = DepartmentModel interfaces = (relay.Node, ) class Employee(SQLAlchemyObjectType): class Meta: model = EmployeeModel interfaces = (relay.Node, ) class Role(SQLAlchemyObjectType): class Meta: model = RoleModel interfaces = (relay.Node, ) class Query(graphene.ObjectType): node = relay.Node.Field() # Allow only single column sorting all_employees = SQLAlchemyConnectionField(Employee, sort=Employee.sort_argument()) # Allows sorting over multiple columns, by default over the primary key all_roles = SQLAlchemyConnectionField(Role) # Disable sorting over this field all_departments = SQLAlchemyConnectionField(Department, sort=None) schema = graphene.Schema(query=Query, types=[Department, Employee, Role])
# Create your views here. from graphene import ObjectType from graphene_django.tests.schema import Query from graphene_django.views import GraphQLView from rest_framework.permissions import IsAuthenticated from rest_framework.views import APIView from rest_framework_simplejwt.authentication import JWTAuthentication import graphene from apis.queries.product import ProductQuery class AppTitleType(ObjectType): name = graphene.String() class RootQuery(ObjectType, ProductQuery): pass class APIGqlView(APIView, GraphQLView): authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticated] @classmethod def as_view(cls, **initkwargs): return super().as_view(**initkwargs) schema = graphene.Schema(query=RootQuery)
raise ValueError("please provide argument \"semester\"") return get_targets(semester=semester, partner_code=partner_code) def resolve_partner_allocations(self, info, semester=None, partner_code=None): if semester is None: raise ValueError("please provide argument \"semester\"") return get_partners(semester=semester, partner=partner_code) def resolve_user(self, info): return g.user def resolve_salt_astronomers(self, info): return get_salt_astronomers() def resolve_tac_members(self, info, partner_code=None): return get_tac_members(partner_code) def resolve_salt_users(self, info): return get_salt_users() def resolve_statistics(self, info, semester, partner=None): return get_statistics(partner, semester) schema = graphene.Schema(query=Query, mutation=Mutations, types=[HRS, RSS, BVIT, SCAM])
class NewsList(ObjectType): news = List(News, required=True, filter_by_date=Boolean(default_value=False)) @staticmethod def resolve_news(parent, info, filter_by_date): if filter_by_date: return sorted(news_source, key=lambda x: x.publish_date) resolver = get_news_list_resolver(parent, info, filter_by_date) return news_source news_source = [ News( author=NewsAuthor(name='Victor', author_id=1), content=NewsContent(title='First', text='WOW!'), publish_date=date.today(), ), News(author=NewsAuthor(name='Eugene', author_id=2), content=NewsContent(title='Second', text='WOW 222!'), publish_date=date.today() - timedelta(days=1)), ] router = APIRouter() router.add_route("/graphql", GraphQLApp(schema=graphene.Schema(query=NewsList)))
import graphene from books.schema import Query as BookQuery class Query(BookQuery, graphene.ObjectType): pass SCHEMA = graphene.Schema(query=Query)
import graphene from graphql.execution.executors.asyncio import AsyncioExecutor from starlette.applications import Starlette from starlette.graphql import GraphQLApp from starlette.middleware.cors import CORSMiddleware from blenheim.schema.schema import Query, Mutations from blenheim.schema.settings.settings import SettingsMutations app = Starlette() app.add_middleware(CORSMiddleware, allow_origins=['*'], allow_headers=['*'], allow_methods=["POST"]) # noinspection PyTypeChecker app.add_route( '/', GraphQLApp(schema=graphene.Schema(query=Query, mutation=Mutations), executor_class=AsyncioExecutor))
class Query(graphene.ObjectType): class Meta: description = 'Example query for TornadoQL' hello = graphene.String() def resolve_hello(self, info): return 'Hello from TornadoQL!' class Mutation(graphene.ObjectType): class Meta: description = 'Example mutation for TornadoQL' post = PostMutation.Field() class Subscription(graphene.ObjectType): class Meta: description = 'Example subscription for TornadoQL' onPost = graphene.Field(Message) def resolve_onPost(root, info): return Storage.stream schema = graphene.Schema(query=Query, mutation=Mutation, subscription=Subscription)
import graphene import cookbook.ingredients.schema class Query(cookbook.ingredients.schema.Query, graphene.ObjectType): # This class will inherit from multiple Queries # as we begin to add more apps to our project pass schema = graphene.Schema(query=Query, mutation=cookbook.ingredients.schema.Mutations)
def main(): schema = graphene.Schema(query=Query) result = schema.execute('{ hello }') print(result.data['hello'])
class LoginQuery(object): login = graphene.Field(UserType) logout = graphene.Field(UserType) def create_token(self, login_obj): password_obj = {'password': login_obj.password} key = dt.now().strftime('%Y-%M-%dT%H:%M:%SZ') token = jwt.encode( password_obj, key, algorithm=settings.DEFAULT_ALGORITHM) TokenUser.objects.create(user=user, token=token) def resolve_login(self, info): login_obj = info.context.login_obj user = User.objects.get(email=login_obj.email) if not user: return None else: try: validate_password(login_obj.password, user=user) except ValidationError: return None self.create_token(login_obj) return user schema = graphene.Schema(query=LoginQuery)
import responder import graphene class Query(graphene.ObjectType): hello = graphene.String(name=graphene.String(default_value="stranger")) def resolve_hello(self, info, name): return f"Hello {name}" api = responder.API() api.add_route("/graph", graphene.Schema(query=Query)) @api.route("/{greeting}") async def greet_world(req, resp, *, greeting): resp.text = f"{greeting}, world!" if __name__ == '__main__': api.run(address="0.0.0.0", port=5000)
category = categories[0] cache = {CACHE_ANCESTORS: CategoryAncestorsCache(category)} setattr(context, CONTEXT_CACHE_NAME, cache) return category return None def resolve_attributes(self, args, context, info): category_pk = args.get('category_pk') queryset = ProductAttribute.objects.prefetch_related('values') if category_pk: # Get attributes that are used with product classes # within the given category. tree = Category.objects.get(pk=category_pk).get_descendants( include_self=True) product_classes = set([ obj[0] for obj in Product.objects.filter( categories__in=tree).values_list('product_class_id') ]) queryset = queryset.filter( Q(products_class__in=product_classes) | Q(product_variants_class__in=product_classes)) return queryset.distinct() def resolve_root(self, args, context, info): # Re-expose the root query object. Workaround for the issue in Relay: # https://github.com/facebook/relay/issues/112 return Query() schema = graphene.Schema(Query)
import graphene import riskapi.schema from graphene_django.debug import DjangoDebug class Query( riskapi.schema.Query, graphene.ObjectType, ): debug = graphene.Field(DjangoDebug, name="_debug") class Mutation(riskapi.schema.Mutation, graphene.ObjectType): # This class will inherit from multiple Queries # as we begin to add more apps to our project debug = graphene.Field(DjangoDebug, name="_debug") schema = graphene.Schema( query=Query, mutation=Mutation, auto_camelcase=False, ) # schema = graphene.Schema(query=Query, auto_camelcase=False,)
class User(graphene.ObjectType): id = graphene.ID() username = graphene.String() last_login = graphene.DateTime() class Query(graphene.ObjectType): users = graphene.List(User, first=graphene.Int()) def resolve_users(self, info, first): return [ User(username='******', last_login=datetime.now()), User(username='******', last_login=datetime.now()), User(username='******', last_login=datetime.now()), ][:first] schema = graphene.Schema(query=Query, auto_camelcase=False) result = schema.execute(''' { users(first: 2) { username last_login } } ''') items = dict(result.data.items()) print(json.dumps(items, indent=4))
from graphene_django import DjangoObjectType import graphene from .models import PersonalNote class PersonalNoteType(DjangoObjectType): class Meta: model = PersonalNote interfaces = (graphene.relay.Node, ) class Query(graphene.ObjectType): notes = graphene.List(PersonalNoteType) def resolve_notes(self, info): """Decide what notes to return """ user = info.context.user if user.is_anonymous: return PersonalNote.objects.none() else: return PersonalNote.objects.filter(user=user) schema = graphene.Schema(query=Query)
# Third-party imports import graphene # Local application imports from .mutations import CreateBusinessMutation, UpdateBusinessMutation, DeleteBusinessMutation from .queries import BusinessQuery # class BusinessSerializerMutation(SerializerMutation): # class Meta: # serializer_class = BusinessSerializer # model_operations = ['create', 'update', 'delete'] # lookup_field = 'id' class BusinessMutation(graphene.ObjectType): create_business = CreateBusinessMutation.Field() update_business = UpdateBusinessMutation.Field() delete_business = DeleteBusinessMutation.Field() schema = graphene.Schema(query=BusinessQuery, mutation=BusinessMutation)
def test_should_query_node_multiple_filtering(): class ReporterType(DjangoObjectType): class Meta: model = Reporter interfaces = (Node, ) class ArticleType(DjangoObjectType): class Meta: model = Article interfaces = (Node, ) filter_fields = ('lang', 'headline') class Query(graphene.ObjectType): all_reporters = DjangoConnectionField(ReporterType) r = Reporter.objects.create(first_name='John', last_name='Doe', email='*****@*****.**', a_choice=1) Article.objects.create(headline='Article Node 1', pub_date=datetime.date.today(), pub_date_time=datetime.datetime.now(), reporter=r, editor=r, lang='es') Article.objects.create(headline='Article Node 2', pub_date=datetime.date.today(), pub_date_time=datetime.datetime.now(), reporter=r, editor=r, lang='es') Article.objects.create(headline='Article Node 3', pub_date=datetime.date.today(), pub_date_time=datetime.datetime.now(), reporter=r, editor=r, lang='en') schema = graphene.Schema(query=Query) query = ''' query NodeFilteringQuery { allReporters { edges { node { id articles(lang: "es", headline: "Article Node 1") { edges { node { id } } } } } } } ''' expected = { 'allReporters': { 'edges': [{ 'node': { 'id': 'UmVwb3J0ZXJUeXBlOjE=', 'articles': { 'edges': [{ 'node': { 'id': 'QXJ0aWNsZVR5cGU6MQ==' } }] } } }] } } result = schema.execute(query) assert not result.errors assert result.data == expected
# api/schema.py import graphene from server.api.graphql.queries import Query from server.api.graphql.mutations import Mutation from server.api.graphql.types import ( RankType, RankModeType, CommonCodeType, TodoInfoType ) # Schema 생성 schema = graphene.Schema( query=Query, mutation=Mutation, types=[ RankType, RankModeType, CommonCodeType, TodoInfoType ], auto_camelcase=False )
def test_proxy_model_fails(): """ This test asserts that if you try to query for a proxy model, that query will fail with: GraphQLError('Expected value of type "CNNReporterType" but got: CNNReporter.',) This is because a proxy model has the identical model definition to its superclass, and defines its behavior at runtime, rather than at the database level. Currently, filtering objects of the proxy models' type isn't supported. It would require a field on the model that would represent the type, and it doesn't seem like there is a clear way to enforce this pattern across all projects """ class CNNReporterType(DjangoObjectType): class Meta: model = CNNReporter interfaces = (Node, ) use_connection = True reporter_1 = Reporter.objects.create(first_name='John', last_name='Doe', email='*****@*****.**', a_choice=1) reporter_2 = CNNReporter.objects.create( first_name='Some', last_name='Guy', email='*****@*****.**', a_choice=1, reporter_type=2, # set this guy to be CNN ) class Query(graphene.ObjectType): all_reporters = DjangoConnectionField(CNNReporterType) schema = graphene.Schema(query=Query) query = ''' query ProxyModelQuery { allReporters { edges { node { id } } } } ''' expected = { 'allReporters': { 'edges': [{ 'node': { 'id': 'UmVwb3J0ZXJUeXBlOjE=', }, }, { 'node': { 'id': 'UmVwb3J0ZXJUeXBlOjI=', }, }] } } result = schema.execute(query) assert result.errors
import graphene from project.api.tickets.mutations import Mutation from project.api.tickets.queries import Query from project.api.tickets.types import TicketCloned, TicketFieldUpdated schema = graphene.Schema(query=Query, mutation=Mutation, types=[TicketFieldUpdated, TicketCloned])
def resolve_bus(self, info, **kwargs): filters = {k: i for (k, i) in kwargs.items() if i} return Bus.objects.filter(**filters).first() def resolve_busses(self, info, **kwargs): return Bus.objects.all() def resolve_routes(self, info, **kwargs): return Route.objects.all() def resolve_locations(self, info, **kwargs): return Location.objects.all() def resolve_stops(self, info, **kwargs): return Stop.objects.all() def resolve_transponders(self, info, **kwargs): return Transponder.objects.all() class Mutation(ObjectType): update_bus = BusMutation.Field() create_bus = CreateBus.Field() schema = graphene.Schema( query=Query, mutation=Mutation, )
"size": svg_maze.maze.size, "layer": svg_maze.maze.layers, "svg": svg_string, "seed": svg_maze.maze.seed, "fileName": svg_maze.file_name } return return_dict def resolve_get_maze(root, info, layerApprox=1, color=False, size=4, seed=""): if seed != "": maze = mz.Maze(0, 0, seed) else: maze = mz.Maze(layerApprox, size) maze_package = { "points": maze.points, "solution": maze.solution, "layers": maze.layers, "size": maze.size, "seed": maze.seed, "color": maze.color } return maze_package MazeSchema = graphene.Schema(query=MazeQuery)