Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from django.views.generic.base import TemplateView
- from .query import schema
- class GraphQLContextMixin(object):
- # GraphQL query
- query = ''
- # The schema to execute query
- schema = None
- # Variables to be passed to the query
- variables = {}
- def get_query(self):
- """
- Returns the GraphQL query to process.
- """
- return self.query
- def get_schema(self):
- return self.schema
- def get_context_data(self, **kwargs):
- """
- Executes the GraphQL query and set the context data to the response.
- """
- return kwargs
- def get_variables(self, request):
- """
- Returns a dict of variables passed to the GraphQL query.
- """
- return self.variables
- def get(self, request, *args, **kwargs):
- """
- Executes the GraphQL query and add result to the context data before rendering template.
- """
- if not self.get_query():
- return self.render_to_response(self.get_context_data())
- response = self.get_schema().execute(
- self.get_query(),
- args=self.get_variables(request))
- return self.render_to_response(
- self.get_context_data(errors=response.errors,
- data=response.data))
- class MutationView(GraphQLContextMixin):
- # Mutation query
- mutation = ''
- def post(self, request, *args, **kwargs):
- """
- Executes the mutation and render the template with resulting data in the context.
- """
- if not self.get_mutation():
- return self.render_to_response(self.get_context_data())
- response = self.get_schema().execute(
- self.get_mutation(),
- args=self.get_user_data(request))
- return self.render_to_response(
- self.get_context_data(errors=response.errors,
- data=response.data))
- def get_user_data(self, request):
- """
- Returns the user data passed as variables to the mutation query.
- """
- return request.POST
- def get_mutation(self):
- """
- Returns the mutation query.
- """
- return self.mutation
- class LoginView(MutationView, TemplateView):
- mutation = '''
- mutation Login($username: String, $password: String) {
- createJWT(username: $username, password: $password) {
- jwt
- }
- }
- '''
- template_name = 'accounts/login.html'
- schema = schema
- class ListAllOrganizations(GraphQLContextMixin, TemplateView):
- query = '''
- query GetAllOrganizations {
- allOrganizations {
- name
- }
- }
- '''
- template_name = 'organizations/list_all.html'
- schema = schema
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement