def test_query_profile_fields(graphql_request, graphql_registry, text_field2, profile_field): from assembl.models.configurable_fields import TextFieldsTypesEnum res = schema.execute( graphql_registry['ProfileFields'], context_value=graphql_request, variable_values={"lang": u"en"}) assert res.errors is None assert len(res.data['profileFields']) == 2 tf_with_value = res.data['profileFields'][0] assert int(from_global_id(tf_with_value['id'])[1]) == profile_field.id assert tf_with_value['configurableField']['title'] == u'My text field' assert tf_with_value['configurableField']['fieldType'] == TextFieldsTypesEnum.TEXT.value assert tf_with_value['configurableField']['order'] == 1.0 assert tf_with_value['configurableField']['required'] is True assert tf_with_value['configurableField']['hidden'] is False assert tf_with_value['valueData'][u'value'] == u'*****@*****.**' generated_tf = res.data['profileFields'][1] assert int(from_global_id(generated_tf['id'])[1]) < 0 assert generated_tf['configurableField']['fieldType'] == TextFieldsTypesEnum.EMAIL.value assert generated_tf['configurableField']['title'] == u'My other custom text field' assert generated_tf['configurableField']['order'] == 2.0 assert generated_tf['configurableField']['required'] is False assert generated_tf['configurableField']['hidden'] is False assert generated_tf['valueData'][u'value'] is None
def mutate_and_get_payload(cls, input, info): score = input.get('score') show_id = input.get('show_id') user_profile_id = input.get('user_profile_id') show = models.Show.objects.get(id=from_global_id(show_id).id) user_profile = models.UserProfile.objects.get(id=from_global_id(user_profile_id).id) review, created = models.Review.objects.update_or_create( user=user_profile, show=show, defaults={'score': score} ) return ReviewShow(review=review, show=show, user_profile=user_profile)
def mutate(root, info, **args): errors = [] invoice = None fixed_price_item = args.get('fixed_price_item') try: check_for_existence((args.get('invoice_id'), Invoice), ) except Exception as e: errors.append(str(e)) return CreateFixedPriceItem(errors=errors, invoice=invoice) invoice_id = from_global_id(args.get('invoice_id'))[1] invoice = Invoice.objects.get(id=invoice_id) res = invoice.can_update() if not res.get('success'): errors.append(res.get('error')) return UpdateInvoiceInfoMutation(errors=errors, invoice=None) TimeEntry.objects.create(invoice=invoice, entry_type=3, staff_member=info.context.user, **fixed_price_item) if invoice.is_in_xero: invoice.send_to_xero() invoice.save() return CreateFixedPriceItem(invoice=invoice)
def mutate(root, info, **args): errors = [] invoice = None invoice_id = args.get('invoice_id') invoice_data = args.get('invoice_data') try: check_for_existence( (invoice_data.matter.client.id, Client), (invoice_data.matter.id, Matter), (invoice_data.matter.manager.id, User), (invoice_id, Invoice), ) except Exception as e: errors.append(str(e)) return UpdateInvoiceInfoMutation(errors=errors, invoice=None) invoice_id = from_global_id(invoice_id)[1] invoice = Invoice.objects.get(pk=invoice_id) res = invoice.can_update() if not res.get('success'): errors.append(res.get('error')) return UpdateInvoiceInfoMutation(errors=errors, invoice=None) invoice.update(**invoice_data) invoice.matter.update(**invoice_data.matter) if invoice.is_in_xero: invoice.send_to_xero() invoice.save() invoice.refresh_from_db() return UpdateInvoiceInfoMutation(errors=errors, invoice=invoice)
def mutate(self, info, client, name, description, complete=False, deadline="", labor=""): # Will need to pass null or nothing in for empty deadline on frontend user = info.context.user if user.is_anonymous: # verifies that user is logged in return CreateJob(ok=False, status="Must be logged in.") else: new_job = Job( # creates new client from input data client=Client.objects.get(pk=from_global_id(client)[1]), name=name, description=description, complete=complete, user=user, ) # verifies that required data is present then creates client if labor != "": new_job.labor = labor if deadline != "": new_job.deadline = deadline if complete is not False: new_job.complete = complete new_job.save() return CreateJob(job=new_job, ok=True, status="ok")
def resolve_all_posts(self, info, **kwargs): username = kwargs.get('username') u = User.objects.get(username=username) searchterm = kwargs.get('q') tags = kwargs.get('tags') id = kwargs.get('id') if id: rid = from_global_id(id)[1] return (FeedPost.objects.all().filter(pk=rid)) if tags: users_sources = FeedSource.objects.filter(user=u, tags=tags, show_on_frontpage=True) else: users_sources = FeedSource.objects.filter(user=u, show_on_frontpage=True) if searchterm: queryset = FeedPost.objects.filter( feed__feedsource__in=users_sources).filter( Q(title__icontains=searchterm) | Q(content__icontains=searchterm)).annotate( source_title=F('feed__feedsource__title')) else: queryset = FeedPost.objects.filter( feed__feedsource__in=users_sources).annotate( source_title=F('feed__feedsource__title')) return queryset
def post(self, request, *args, **kwargs): # sends job info to be populated into invoice form req = json.loads(request.body) job = Job.objects.get(pk=from_global_id(req["job"])[1]) user = User.objects.get(pk=job.user_id) client = Client.objects.filter(pk=job.client_id).get() job_parts = Part.objects.filter(job_id=job).values() total = 0 for part in job_parts: total = total + part["cost"] total = total + job.labor context = { "invoice_number": job.id, "today": datetime.date.today(), "customer": user, "parts": job_parts, "labor": job.labor, "client_name": " ".join([client.first_name, client.last_name]), "client": client, "order_id": job.id, "total": total, } pdf = render_to_pdf("invoice.html", context) if pdf: response = HttpResponse(pdf, content_type="application/pdf") filename = "Invoice_%s.pdf" % (job.id) content = "inline; filename='%s'" % (filename) response["Content-Disposition"] = content return response return HttpResponse("Not found")
def mutate(root, info, **args): errors = [] invoice = None recorded_time = args.get('recorded_time') invoice_id = args.get('invoice_id') try: check_for_existence( *[(time_entry_id, TimeEntry) for time_entry_id in recorded_time], (invoice_id, Invoice), ) except Exception as e: errors.append(str(e)) return UpdateInvoiceMutation(errors=errors, invoice=None) invoice_id = from_global_id(invoice_id)[1] invoice = Invoice.objects.get(pk=invoice_id) res = invoice.can_update() if not res.get('success'): errors.append(res.get('error')) return UpdateInvoiceInfoMutation(errors=errors, invoice=None) invoice.time_entries.set( [TimeEntry.objects.get(pk=pk) for pk in recorded_time]) if invoice.is_in_xero: invoice.send_to_xero() invoice.save() return UpdateInvoiceMutation(errors=errors, invoice=invoice)
def mutate(root, info, token=None, project_data=None, project_id=None): db_id = from_global_id(project_id) try: project = Project.objects.get(pk=db_id[1]) if (project.user == info.context.user): if project_data.name: project.name = project_data.name if project_data.content: project.content = project_data.content if project_data.contact: project.contact = project_data.contact if project_data.place: project.place = project_data.place if project_data.startat: project.start_at = dateutil.parser.parse( project_data.startat) if project_data.isPublic: project.is_public = project_data.isPublic if project_data.isOpen: project.is_open = project_data.isOpen if project_data.header: project.header = project_data.header project.thumbnail = project_data.header project.save() if project_data.tags: now_tags = project.tags.values_list('name', flat=True) new_tags = project_data.tags add_tags = list(set(new_tags) - set(now_tags)) if add_tags: for tag in add_tags: project.tags.add(Tag.objects.get(name=tag)) remove_tags = list(set(now_tags) - set(new_tags)) if remove_tags: for tag in remove_tags: project.tags.remove(Tag.objects.get(name=tag)) except: return None return UpdateProject(project=project)
def set_lookup_kwarg(self, global_id): try: _type, _id = from_global_id(global_id) except (TypeError, ValueError, UnicodeDecodeError, binascii.Error): raise ValidationError("Invalid id.") self._meta.lookup_kwarg = _id
def test_mutation_add_extracts(graphql_request, top_post_in_thread_phase): post_db_id = int(from_global_id(top_post_in_thread_phase)[1]) extract_body = u"manger des choux à la crème" xpathStart = u"//div[@id='message-body-local:Content/%s']/" % post_db_id xpathEnd = xpathStart offsetStart = 17 offsetEnd = 44 variable_values = { "extracts": [ { "postId": top_post_in_thread_phase, "body": extract_body, "xpathStart": xpathStart, "xpathEnd": xpathEnd, "offsetStart": offsetStart, "offsetEnd": offsetEnd, "lang": "fr" } ], "extractState": "SUBMITTED", "extractNature": "actionable_solution" } post = models.AssemblPost.get(post_db_id) db = post.db def get_extracts(): return db.query( models.Extract ).join( models.Content, models.Extract.content == post ).options(joinedload(models.Extract.text_fragment_identifiers)).all() assert len(get_extracts()) == 0 res = schema.execute(u""" mutation AddPostsExtract($extracts: [PostExtractEntryInput]!, $extractState: ExtractStates, $extractNature: ExtractNatures) { addPostsExtract(extracts: $extracts, extractState: $extractState, extractNature: $extractNature) { status } } """, context_value=graphql_request, variable_values=variable_values) assert json.loads(json.dumps(res.data)) == { u'addPostsExtract': { u'status': True } } assert len(get_extracts()) == 1 # add the same extract res = schema.execute(u""" mutation AddPostsExtract($extracts: [PostExtractEntryInput]!, $extractState: ExtractStates, $extractNature: ExtractNatures) { addPostsExtract(extracts: $extracts, extractState: $extractState, extractNature: $extractNature) { status } } """, context_value=graphql_request, variable_values=variable_values) # The extract must be ignored assert len(get_extracts()) == 1
def mutate_and_get_payload(cls, input, context, info): order_items = OrderItems.objects.get( pk=from_global_id(input.get('id'))[1]) if input.get('quantity'): order_items.quantity = input.get('quantity') order_items.save() return UpdateOrderItems(order_items=order_items)
def mutate_and_get_payload(cls, root, info, **input): # проверяет токен token = input.get('token', None) if token != '******************': return "Invalid token" try: book = Book.objects.get(id=from_global_id(input.get('id'))[1]) if input.get('title'): book.title = input.get('title') if input.get('description'): book.description = input.get('description') if input.get('image'): book.image = input.get('image') if input.get('age'): book.age = input.get('age') if input.get('year'): book.year = input.get('year') if input.get('original_title'): book.original_title = input.get('original_title') if input.get('author'): book.author = input.get('author') if input.get('genre'): book.genre = input.get('genre') if input.get('series_id'): book.series_id = input.get('series_id') if input.get('nr_series'): book.nr_series = input.get('nr_series') book.save() return UpdateBook(book=book) except Book.DoesNotExist: return "Not found this is book"
def mutate_and_get_payload(root, info, **input): productos = Productos.objects.get(pk=from_global_id(input.get('id'))[1]) productos.productos_name = input.get('productos_name') productos.productos_comercial = Comercial.objects.get(comercial_name=input.get('productos_comercial')) productos.productos_title = Title.objects.get(title_name=input.get('productos_title')) productos.save() return UpdateProductos(productos=productos)
def mutate(self, info, form_id, content): try: result = FormService.submit(int(from_global_id(form_id)[1]), content) except FormService.exceptions as e: raise MutationExecutionException(str(e)) return SubmitForm(success=True, **result)
def mutate(cls, root, info, **fields): id = fields.pop('id') obj_id = from_global_id(id)[1] obj = cls.model.objects.get(pk=obj_id) ret = obj.delete() return cls(ok=(ret[0] > 0))
def mutate_and_get_payload(cls, input, request, info): gid_type, gid = from_global_id(input.get('lifeNode')) node = LifeNode._meta.model.objects.get(document_id=gid) error = has_permission(cls, request, node, 'edit') if error: return error tag_title = input.get('title').strip(' \t\n\r') tag_slug = slugify(tag_title) try: tag = TagModel.objects.get(slug=tag_slug) except TagModel.DoesNotExist: tag = TagModel( title=tag_title, slug=tag_slug, ) tag.save(request=request) c = CharacteristicModel( tag=tag.document, lifeNode=node.document, value=input.get('value') ) c.save(request=request) return CharacteristicAdd( lifeNode=node, characteristic=Characteristic.Connection.Edge( node=c, cursor=offset_to_cursor(0)) )
def mutate(self, info, game_id, player_id, tile_id, position): """Mutation "resolver" - store and broadcast a message.""" print('makeMove', tile_id) game = get_object_or_404(Game, id=game_id) player = get_object_or_404(Player, id=player_id) tile = get_object_or_404(Tile, id=from_global_id(tile_id)[1]) board_position = BoardPosition.objects.create(game=game, x=position.x, y=position.y) tile.board_position = board_position tile.player = None tile.save() refill_hand(game, player) players = game.players.all() player_index = 0 for i, p in enumerate(players): if game.turn == p: player_index = i if player_index == len(players) - 1: player_index = 0 else: player_index += 1 game.turn = players[player_index] game.save() # Notify subscribers. GameSubscription.new_move(game) return MakeMove(ok=True)
def mutate_and_get_payload(cls, input, request, info): try: gid_type, gid = from_global_id(input.get('id')) except Error: gid = input.get('id') revision = Revision._meta.model.objects.get(id=gid) document = revision.document current_obj = document.get_object() document.revision_tip_id = revision.pk document.save(update_fields=['revision_tip_id']) current_obj.is_tip = None current_obj.save(update_fields=['is_tip'], request=request) obj = revision.get_object() obj.is_tip = True obj.is_deleted = None obj.save(update_fields=['is_tip', 'is_deleted'], request=request) return RevisionRevert( node=obj, )
def resolve_club_stats(self, info, club): try: club_tuple = from_global_id(club) if not club_tuple: raise Exception() if not isinstance(club_tuple, tuple): raise Exception() if club_tuple[0] != 'ClubType': raise Exception() except: raise Exception("Malformed club ID") try: club = Club.objects.get(id=club_tuple[1]) except Club.DoesNotExist: raise Exception("Requested club does not exist") fields_to_aggregate = [ to_snake_case(x.name.value) for x in info.field_asts[0].selection_set.selections if x.name.value and x.name.value not in ['club', 'date', '__typename'] ] sums = {x: Sum(x) for x in fields_to_aggregate} club_stats = list(club.club_stats.all().values('club').annotate(**sums))[0] club_stats['club'] = club return ClubStatsType(**club_stats)
def test_mutation_create_text_field(graphql_request, graphql_registry, test_session): from assembl.models.configurable_fields import TextField res = schema.execute( graphql_registry['createTextField'], context_value=graphql_request, variable_values={ "lang": u"en", "titleEntries": [ { "localeCode": "en", "value": u"My new field" } ], "order": 4.0, "required": False, "hidden": False }) assert res.errors is None assert 'createTextField' in res.data new_field = res.data['createTextField']['field'] assert new_field[u'required'] is False assert new_field[u'hidden'] is False assert new_field[u'order'] == 4.0 title_entries = new_field['titleEntries'] assert title_entries[0]['localeCode'] == u'en' assert title_entries[0]['value'] == u'My new field' saobj = TextField.get(from_global_id(new_field[u'id'])[1]) test_session.delete(saobj)
def mutate_and_get_payload(cls, root, info, **input): youth_profile = YouthProfile.objects.get( pk=from_global_id(input.get("id"))[1]) youth_profile = renew_youth_profile(youth_profile) youth_profile.set_approved(save=True) return RenewYouthProfileMutation(youth_profile=youth_profile)
def mutate_and_get_payload(cls, args, context, **kwargs): raw_id = kwargs.get('id', None) # TODO: trabajar con el id de graphene. director_id = kwargs.pop('director') producers = kwargs.pop('producer') print(producers) kw = {'model': Film, 'data': kwargs} if raw_id: kw['id'] = from_global_id(raw_id)[1] film = generic_model_mutation_process(commit=False, **kw) if director_id: film.director_id = director_id film.save() if producers: q = Q() for producer_name in producers: q |= Q(name__iexact=producer_name['name']) producer_instances = [ producer for producer in Producer.objects.filter(q) ] film.producer.set(producer_instances) return AddFilm(film=film)
def resolve_member_stats(self, info, member): try: member_tuple = from_global_id(member) if not member_tuple: raise Exception() if not isinstance(member_tuple, tuple): raise Exception() if member_tuple[0] != 'MemberType': raise Exception() except: raise Exception("Malformed member ID") try: member = Member.objects.get(id=member_tuple[1]) except Member.DoesNotExist: raise Exception("Requested member does not exist") fields_to_aggregate = [ to_snake_case(x.name.value) for x in info.field_asts[0].selection_set.selections if x.name.value and x.name.value not in ['member', 'date', '__typename'] ] sums = {x: Sum(x) for x in fields_to_aggregate} member_stats = list(member.member_stats.all().values('member').annotate(**sums))[0] member_stats['member'] = member return MemberStatsType(**member_stats)
def mutate(self, _, transaction_id, item, admin_email, auth_token): _, transaction_id = from_global_id(transaction_id) validate_authentication(admin_email, auth_token, admin=True) admin_accepting = Admin.query.filter_by(email=admin_email).first() # Find the item the user requests item = Item.query.filter_by(name=item).first() if not item: raise Exception("Item not found...") # Find the transaction associated with the user's checkout request transaction = Transaction.query.filter_by(id=transaction_id).first() if not transaction: raise Exception("No such transaction found...") # Update the transaction to track the item as checked out transaction.accepted = True transaction.admin_accepted = admin_email transaction.date_accepted = datetime.now() item.date_out = transaction.date_accepted transactions = Transaction.query.all() return CheckOutItem(transactions=transactions)
def mutate(cls, root, info, user_id, deadline): user_id = from_global_id(user_id)[1] user = User.objects.get(id=user_id) TimeEvent.objects.create(user=user, deadline=deadline) return CreateTimeEvent(ok=True)
def mutate_and_get_payload(cls, input, context, info): global_id = input.get("id") id = from_global_id(global_id)[1] todo = models.TodoModel.objects.get(pk=id) viewer = todo.user todo.delete() return RemoveTodo(viewer=viewer, todoId=global_id)
def input_to_dictionary(input_, column=None): """Method to convert Graphene inputs into dictionary. Args: input_: GraphQL "data" dictionary structure from mutation column: List database model column names that should be column Returns: dictionary: Dict of inputs """ # Initialize key variables dictionary = {} if bool(column) is False: column = {} # Process each key from the imput for key in input_: # Convert GraphQL global id to database id if key[-2:] == 'id': input_[key] = from_global_id(input_[key])[1] else: # Otherwise the key is related to the database. # We only use Unicode data in the tables, so we need to convert. column_type = column.get(key, DATA_STRING) if column_type == DATA_STRING: input_[key] = input_[key].encode() elif column_type == DATA_FLOAT: input_[key] = float(input_[key]) else: input_[key] = int(input_[key]) dictionary[key] = input_[key] return dictionary
def mutate(root, info, **args): errors = [] invoice = None invoice_data = args.get('invoice_data') try: check_for_existence( *[(time_entry.id, TimeEntry) for time_entry in invoice_data.recorded_time], (invoice_data.matter.id, Matter), ) except Exception as e: errors.append(str(e)) return CreateInvoiceMutation(errors=errors, invoice=None) matter_id = from_global_id(invoice_data.matter.id)[1] invoice = Invoice.objects.create( matter_id=matter_id, created_date=datetime.now(), payment_terms_id=1, billing_method=invoice_data.billing_method, ) for fixed_price_item in invoice_data.fixed_price_items: fixed_price_item = {**fixed_price_item} del fixed_price_item['id'] TimeEntry.objects.create(entry_type=FIXED_PRICE_ITEM, invoice=invoice, staff_member=info.context.user, **fixed_price_item) if len(invoice_data.recorded_time): for time in invoice_data.recorded_time: time_entry_id = from_global_id(time.id)[1] time_entry = TimeEntry.objects.get(pk=time_entry_id) time_entry.units_to_bill = time.units_to_bill time_entry.save() invoice.time_entries.add(time_entry) invoice.matter.update(**invoice_data.matter, exclude=['time_entries', 'budget']) invoice.matter.budget = invoice_data.matter.budget or 0 invoice.save() return CreateInvoiceMutation(errors=errors, invoice=invoice)
def get_node(global_id, *args): _type, _id = from_global_id(global_id) if _type == 'Faction': return getFaction(_id) elif _type == 'Ship': return getShip(_id) else: return None
def mutate(cls, instance, args, info): company_id = int(from_global_id(args.get('company_id')).id) company = Company.objects.get(id=company_id) created_job = company.jobs.create( title=args.get('title'), description=args.get('description'), ) return CreateJob(job=created_job, ok=True)
def get_node(global_id, _info): type_, id_ = from_global_id(global_id) if type_ == 'Faction': return getFaction(id_) elif type_ == 'Ship': return getShip(id_) else: return None
def mutate_and_get_payload(root, info, **input): company = Company.objects.get(pk=from_global_id(input.get('id'))[1]) company.company_name = input.get('company_name') company.cnpj = input.get('cnpj') validate_cnpj(company.cnpj) company.save() return UpdateCompany(employee=company)
def mutate(self, info, public_key_id): user = get_user_from_info(info) try: result = EncryptionKeyService.remove_key( user, int(from_global_id(public_key_id)[1])) except EncryptionKeyService.exceptions as e: raise MutationExecutionException(str(e)) return RemoveEncryptionKey(success=True)
def mutate(self, info, id, instock): id = from_global_id(id)[1] p = Product.objects.get(id=id) # p.inStock = p.instock = instock p.isActive = True p.save() return StockStatusProduct(success=True)
def mutate(self, info, id, name, sortD, longD, brand): prd = Product.objects.get(id=from_global_id(id)[1]) prd.brand = brand prd.name = name prd.shortDescription = sortD prd.description = longD prd.save() return UpdateProduct(success=True)
def mutate_and_get_payload(cls, input, context, info): global_id = input.get("id") id = from_global_id(global_id)[1] todo = models.TodoModel.objects.get(pk=id) todo.completed = not todo.completed todo.save() viewer = todo.user return ToggleTodoComplete(todo=todo, viewer=viewer)
def mutate(self, info, answerSheetId, score=0, number=0): answer = AnswerSheet.objects.get( id=from_global_id(answerSheetId)[1]).answer_set.all().filter( number=number)[0] answer.score = score answer.completed = True answer.save() return ScoringTasks(answer=answer)
def resolve_recommend_shows(self, user_ids=None, **kwargs): if user_ids: user_profile_ids = [from_global_id(g_id).id for g_id in user_ids] group = models.UserProfile.objects.filter(id__in=user_profile_ids) all_users = models.UserProfile.objects.all() # TODO: eventually query user's friends return get_show_recommendations_via_group(group, all_users) else: return models.Show.objects.all()
def input_to_dictionary(input): """Method to convert Graphene inputs into dictionary.""" dictionary = {} for key in input: # Convert GraphQL global id to database id if key[-2:] == 'id' and input[key] != 'unknown': input[key] = from_global_id(input[key])[1] dictionary[key] = input[key] return dictionary
def getNode(globalId, *args): resolvedGlobalId = from_global_id(globalId) _type, _id = resolvedGlobalId.type, resolvedGlobalId.id if _type == "Faction": return getFaction(_id) elif _type == "Ship": return getShip(_id) else: return None
def mutate_and_get_payload(cls, input, context, info): global_id = input.get("id") text = input.get("text") id = from_global_id(global_id)[1] todo = models.TodoModel.objects.get(pk=id) todo.text = text todo.save() viewer = todo.user return UpdateTodoText(todo=todo, viewer=viewer)
def mutate_and_get_payload(cls, input, request, info): gid_type, gid = from_global_id(input.get('id')) post = Post._meta.model.objects.get(document_id=gid) error = has_permission(cls, request, post, 'edit') if error: return error post = post_save(post, input, request) return PostEdit(post=post)
def mutate_and_get_payload(cls, input, request, info): gid_type, gid = from_global_id(input.get('id')) tag = Tag._meta.model.objects.get(document_id=gid) error = has_permission(cls, request, tag, 'edit') if error: return error tag = tag_save(tag, input, request) return TagEdit(tag=tag)
def mutate_and_get_payload(cls, input, request, info): gid_type, gid = from_global_id(input.get('id')) node = LifeNode._meta.model.objects.get(document_id=gid) error = has_permission(cls, request, node, 'edit') if error: return error node = node_save(node, input, request) return LifeNodeEdit(lifeNode=node)
def id_fetcher(self, global_id, info): from graphene.relay.utils import is_node schema = info.schema.graphene_schema resolved_global_id = from_global_id(global_id) _type, _id = resolved_global_id.type, resolved_global_id.id object_type = schema.get_type(_type) if not is_node(object_type) or (self.field_object_type and object_type != self.field_object_type): return return object_type.get_node(_id)
def mutate_and_get_payload(cls, input, request, info): gid_type, gid = from_global_id(input.get('id')) node = LifeNode._meta.model.objects.get(document_id=gid) error = has_permission(cls, request, node, 'delete') if error: return error node.delete(request=request) return LifeNodeDelete(lifeNodeDeletedID=input.get('id'))
def mutate_and_get_payload(cls, input, request, info): gid_type, gid = from_global_id(input.get('id')) tag = Tag._meta.model.objects.get(document_id=gid) error = has_permission(cls, request, tag, 'delete') if error: return error tag.delete(request=request) return TagDelete(tagDeletedID=input.get('id'))
def mutate_and_get_payload(cls, args, context, info): actors_ids = [from_global_id(actor['actor_id'])[1] for actor in args['actors']] date = arrow.get(args['air_date']).date(), data_to_sent = { 'title': args['title'], 'actors': actors_ids, 'air_date': date, 'rating': args['rating'], } response = requests.post(ALL_FILMS_ENDPOINT, data=data_to_sent) data_from_server = response.json() film = Film.create_from_data(data_from_server, data_from_server['id']) return CreateFilm(film=film)
def mutate_and_get_payload(cls, input, request, info): gid_type, gid = from_global_id(input.get('id')) vote = VoteModel.objects.get(document_id=gid, author=request.user.document) error = has_permission(cls, request, vote, 'delete') if error: return error parent_id = vote.parent_id vote.delete(request=request) voting = Voting.get_node(parent_id, request, info) return VoteDelete(voteDeletedID=input.get('id'), voting=voting)
def id_fetcher(self, global_id, context, info): from graphene.relay.utils import is_node schema = info.schema.graphene_schema try: _type, _id = from_global_id(global_id) except: return None object_type = schema.get_type(_type) if isinstance(self.field_object_type, six.string_types): field_object_type = schema.get_type(self.field_object_type) else: field_object_type = self.field_object_type if not is_node(object_type) or (self.field_object_type and object_type != field_object_type): return return object_type.get_node(_id, context, info)
def mutate_and_get_payload(cls, input, info): name = input.get('name') homeworld_id = input.get('homeworld_id') assert homeworld_id, 'homeworld_id must be not null' try: homeworld_id = int(homeworld_id) except ValueError: try: resolved = from_global_id(homeworld_id) resolved.type.lower == 'planet', 'The homeworld should be a Planet, but found {}'.format(resolved.type) homeworld_id = resolved.id except: raise Exception("Received wrong Planet id: {}".format(homeworld_id)) homeworld = Planet._meta.model.objects.get(id=homeworld_id) hero = Hero._meta.model(name=name, homeworld=homeworld) hero.save() return CreateHero(hero=hero, ok=bool(hero.id))
def _set_vote(input, request, info): gid_type, gid = from_global_id(input.get('parent')) parent = Document._meta.model.objects.get(pk=gid) try: vote = VoteModel.objects.get(parent=parent, author=request.user.document) except VoteModel.DoesNotExist: vote = VoteModel(parent=parent, author=request.user.document) vote.value = input.get('value') vote.save(request=request) voting = Voting.get_node(gid, request, info) return { 'vote': vote, 'voting': voting }
def mutate(cls, input, args, info): # be a hack user for now until I work out authentication user = User.objects.get_by_natural_key('graphene') id = args.get('id') if id is not None: # update an existing item rid = from_global_id(id)[1] catalog_item = CatalogItem.objects.get(pk=rid) for a,v in args.items(): if a == 'id': continue if hasattr(catalog_item, a): setattr(catalog_item, a, v) catalog_item.save() catalog_item.refresh_from_db() else: # make a new item catalog_item = CatalogItem(owner=user, **args) catalog_item.save() return NewCatalogItem(catalog_item=CatalogNode(catalog_item))
def _resolve_id(cls, node_id): # Resolve an opaque global id into an internal form resolved_id = graphql_node.from_global_id(node_id) assert resolved_id.type == cls.__name__ return resolved_id.id
def filter(self, qs, value): gids = [from_global_id(v)[1] for v in value] return super(GlobalIDMultipleChoiceFilter, self).filter(qs, gids)
def filter(self, qs, value): _type, _id = from_global_id(value) return super(GlobalIDFilter, self).filter(qs, _id)
def test_mutation_add_extract(graphql_request, tags, top_post_in_thread_phase): post_db_id = int(from_global_id(top_post_in_thread_phase)[1]) contentLocale = u'fr' message_title = u"Manger des choux à la crème" extract_body = u"manger des choux à la crème" extract_author_name = u'Mr. Administrator' xpathStart = u"//div[@id='message-body-local:Content/%s']/" % post_db_id xpathEnd = xpathStart offsetStart = 17 offsetEnd = 44 important = False tags = ['tag1'] variable_values = { "contentLocale": contentLocale, "postId": top_post_in_thread_phase, "body": extract_body, "important": important, "xpathStart": xpathStart, "xpathEnd": xpathEnd, "offsetStart": offsetStart, "offsetEnd": offsetEnd, "tags": tags } mutation = u""" mutation addPostExtract( $contentLocale: String! $postId: ID! $body: String! $important: Boolean $xpathStart: String! $xpathEnd: String! $offsetStart: Int! $offsetEnd: Int! $tags: [String] ) { addPostExtract( postId: $postId body: $body important: $important xpathStart: $xpathStart xpathEnd: $xpathEnd offsetStart: $offsetStart offsetEnd: $offsetEnd lang: $contentLocale tags: $tags ) { post { id parentId subjectEntries(lang: $contentLocale) { value localeCode } publicationState ... on Post { extracts { important body extractNature extractAction textFragmentIdentifiers { xpathStart xpathEnd offsetStart offsetEnd } creator { name } tags { value } } } } } } """ res = schema.execute(mutation, context_value=graphql_request, variable_values=variable_values) assert json.loads(json.dumps(res.data)) == { u'addPostExtract': { u'post': { u'extracts': [ { u'body': extract_body, u'creator': { u'name': extract_author_name }, u'textFragmentIdentifiers': [ { u'offsetStart': offsetStart, u'offsetEnd': offsetEnd, u'xpathEnd': xpathEnd, u'xpathStart': xpathStart } ], u'extractAction': None, u'extractNature': None, u'important': important, u'tags': [{u'value': u'tag1'}] } ], u'publicationState': u'PUBLISHED', u'subjectEntries': [ { u'value': message_title, u'localeCode': contentLocale } ], u'parentId': None, u'id': top_post_in_thread_phase } } } res = schema.execute(mutation, context_value=graphql_request, variable_values=variable_values) assert res.errors and res.errors[0].message == "Extract already exists!" models.AssemblPost.get(post_db_id).extracts[0].tags = []