def item_file(request, slug): item = cache.get(Item.get_cache_key(slug), None) if not item: item = get_object_or_404(Item, slug=slug) if item.cacheable: cache.set(Item.get_cache_key(slug), item, app_settings.GALLERY_CACHE_TIMEOUT) try: return HttpResponse(item.file, mimetype=item.mimetype) except: item = get_object_or_404(Item, slug=slug) return HttpResponse(item.file, mimetype=item.mimetype)
def adicionar_item(self, request, item, quantidade, pk=0): error, messages = False, [] if request.user.is_authenticated: cliente = get_object_or_404(Cliente, user=request.user) if pk and cliente.carrinho.pk != pk: raise PermissionDenied( 'O cliente não tem permissão para alterar esse carrinho') carrinho = cliente.carrinho else: carrinho = Carrinho.objects.get( pk=pk) if pk else Carrinho.objects.create() produto = get_object_or_404(Produto, pk=item) carrinho, error, messages = carrinho.adicionar_item( produto, quantidade, error, messages) return carrinho, error, messages
def remove(self, request, pk, content_pk): """ --- method_path: /groups/{id}/remove/{content_pk}/ method_action: DELETE desc: Remover o conteúdo do grupo. input: - name: content_pk desc: Id do conteúdo type: integer required: True location: path """ group = self.get_object() content = get_object_or_404(Content, pk=content_pk) group.group_contents.filter(order__gte=content.order + 1).update(order=F('order') - 1) Log.objects.create(user=request.user, action='delete', content_object=content) content.delete() serializer = self.get_serializer(group) return Response(serializer.data)
def add(self, request, pk): """ --- method_path: /groups/{id}/add/ method_action: POST desc: Adicionar conteúdo no grupo. input: - name: media desc: Id da mídia. type: integer required: True location: form - name: duration desc: Duração da exibição type: str required: True location: form """ group = self.get_object() media_pk, duration = get_fields(request.data, ['media', 'duration']) media = get_object_or_404(Media, pk=media_pk) content = Content.objects.create( media=media, duration=dateparse.parse_duration(duration), group=group, order=group.group_contents.count() + 1) Log.objects.create(user=request.user, action='create', content_object=content) serializer = ContentSerializer(content) return Response(serializer.data)
def add(self, request, pk): """ --- method_path: /tvs/{id}/add/ method_action: POST desc: Adicionar grupo na tv. input: - name: group desc: Id do grupo. type: integer required: True location: form """ tv = self.get_object() group_pk, *_ = get_fields(request.data, ['group']) group = get_object_or_404(Group, pk=group_pk) tv.group = group tv.save() serializer = self.get_serializer(tv) Log.objects.create(user=request.user, action='update', content_object=tv) return Response(serializer.data)
def resolve_table_last_commit_timestamp(self, info, datastore_id, schema_name, table_name, **kwargs): """Retrieve the last time a table was modified. """ get_kwargs = { 'name__iexact': table_name, 'schema__datastore_id': shortcuts.from_global_id(datastore_id, True), 'schema__name__iexact': schema_name, 'workspace': info.context.workspace, } table = shortcuts.get_object_or_404(models.Table, **get_kwargs) if not permissions.request_can_view_datastore(info, table.datastore): raise errors.PermissionDenied() ca_id = "table.last_commit.%s" % table.id value = cache.get(ca_id) if value is not None: return value value = ( inspector.get_engine(table.datastore) .get_last_commit_time_for_table(schema_name, table_name) ) cache.set(ca_id, value, (15 * 60)) return value
def solicitar(self, request): """ --- method_path: /clientes/solicitar/ method_action: POST desc: Solicitar alteração de senha. input: - name: email desc: Email do usuário. type: str required: True location: form """ to_email, *_ = get_fields(request.data, ['email']) user = get_object_or_404(User, email=to_email) mail_subject = 'Solicitação para alteração de senha.' message = render_to_string('website/pass_reset.html', { 'user': user, 'domain': settings.FRONT_END_HOST, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() return Response({'message': 'A solicitação será enviada para o seu email.'})
def down(self, request, pk): """ --- method_path: /groups/{id}/down/ method_action: PATCH desc: Diminuir a ordem do conteúdo input: - name: content desc: Id do conteúdo type: integer required: True location: form """ group = self.get_object() content_pk, *_ = get_fields(request.data, ['content']) content = get_object_or_404(Content, pk=content_pk) if content.order < group.group_contents.count(): group.group_contents.filter(order=content.order + 1).update(order=content.order) content.order += 1 content.save() Log.objects.create(user=request.user, action='update', content_object=content) serializer = self.get_serializer(group) return Response(serializer.data)
def resolve_datastore_by_slug(self, info, slug): """Retrieve a single datastore by slug. """ get_kwargs = { 'workspace': info.context.workspace, 'slug__iexact': slug, } return shortcuts.get_object_or_404(models.Datastore, **get_kwargs)
def perform_mutation(cls, context, connection): """If none, we should disable it. """ active_sso = None if connection: active_sso = get_object_or_404(models.SSOConnection, pk=connection) context.workspace.active_sso = active_sso context.workspace.save()
def resolve_sso_connection_by_primary_key(self, info, pk): """Find SSO connection by primary key. """ get_kwargs = { 'workspace': info.context.workspace, 'pk': pk, } return shortcuts.get_object_or_404(SSOConnection, **get_kwargs)
def resolve_datastore(self, info, id): """Retrieve a single datastore by ID. """ get_kwargs = { 'workspace': info.context.workspace, 'pk': shortcuts.from_global_id(id, True), } return shortcuts.get_object_or_404(models.Datastore, **get_kwargs)
def resolve_workspace_group(self, info, id): """Retrieve a group by the ID. Scoped to the current workspace. """ _type, pk = shortcuts.from_global_id(id) get_kwargs = { 'workspace_id': info.context.workspace.pk, 'pk': pk, } return shortcuts.get_object_or_404(Group, **get_kwargs)
def resolve_custom_field(self, info, id, *args, **kwargs): """Retrieve a specific custom field instance. """ _type, pk = shortcuts.from_global_id(id) get_kwargs = { 'workspace': info.context.workspace, 'pk': pk, } return shortcuts.get_object_or_404(CustomField, **get_kwargs)
def resolve_sso_connection(self, info, id): """Retrieve a single sso connection by ID. """ _type, pk = shortcuts.from_global_id(id) get_kwargs = { 'workspace': info.context.workspace, 'pk': pk, } return shortcuts.get_object_or_404(SSOConnection, **get_kwargs)
def resolve_workspace_user(self, info, id): """Retrieve a team member by the ID. Scoped to the current workspace. """ _type, pk = shortcuts.from_global_id(id) get_kwargs = { 'workspace_id': info.context.workspace.pk, 'user__id': pk, } return shortcuts.get_object_or_404(Membership, **get_kwargs)
def enderecos(self, request): try: if request.user.is_authenticated: cliente = get_object_or_404(Cliente, user=request.user) endereco_pk = request.data.get('endereco', None) if endereco_pk: endereco = get_object_or_404(Endereco, pk=endereco_pk) endereco = Endereco.objects.get(pk=endereco_pk) cliente.enderecos.add(endereco) cliente.save() serializer = self.serializer_class(cliente) return Response(serializer.data) else: data = {'detail': 'O campo endereço é obrigatório'} return Response(data, status=status.HTTP_400_BAD_REQUEST) else: raise NotAuthenticated except models.ObjectDoesNotExist: raise Http404
def resolve_workspace_group_users(self, info, group_id): """Retrieve the users of the provided group. Scoped to the current workspace. """ _type, pk = shortcuts.from_global_id(group_id) get_kwargs = { 'workspace_id': info.context.workspace.pk, 'pk': pk, } return shortcuts.get_object_or_404( Group, **get_kwargs).user_set.order_by('fname')
def resolve_table_definition(self, info, datastore_id, schema_name, table_name, **kwargs): """Retrieve detailed table definition. """ get_kwargs = { 'name__iexact': table_name, 'schema__datastore_id': shortcuts.from_global_id(datastore_id, True), 'schema__name__iexact': schema_name, 'workspace': info.context.workspace, } return shortcuts.get_object_or_404(models.Table, **get_kwargs)
def item_detail(self, request, pk, produto_id): error, messages = False, [] carrinho = self.get_object() produto = get_object_or_404(Produto, pk=produto_id) item = get_object_or_404(ItemCarrinho, carrinho=carrinho, produto=produto) if method == 'DELETE': item.delete() if method == 'PATCH': quantidade, error, messages = produto.validar_qtd( quantidade, error, messages) item.quantidade = quantidade item.save() serializer = CarrinhoSerializer(carrinho) data = serializer.data data['messages'] = messages data['error'] = error return Response(data)
def resolve_run(self, info, id, *args, **kwargs): """Retrieve a specific run by the global ID. """ _type, pk = shortcuts.from_global_id(id) get_kwargs = { 'workspace': info.context.workspace, 'pk': pk, } return shortcuts.get_object_or_404(models.Run, **get_kwargs)
def reset(self, request): uidb64, token, password = get_fields( request.data, ['uid', 'token', 'password']) try: uid = force_text(urlsafe_base64_decode(uidb64)) user = get_object_or_404(User, pk=uid) except(TypeError, ValueError, OverflowError): user = None if user is not None and account_activation_token.check_token(user, token): user.set_password(password) user.save() return Response({'message': 'Senha alterada com sucesso'}) return Response({'message': 'Token ou uid inválido'}, status=status.HTTP_400_BAD_REQUEST)
def resolve_run_history(self, info, datastore_id, *args, **kwargs): """Retrieve the last 30 active runs. """ get_kwargs = { 'workspace': info.context.workspace, 'pk': shortcuts.from_global_id(datastore_id, True), } datastore = shortcuts.get_object_or_404(models.Datastore, **get_kwargs) if not definition_permissions.request_can_view_datastore(info, datastore): raise errors.PermissionDenied() return datastore.run_history.filter(started_at__isnull=False).order_by('-started_at').prefetch_related('errors')
def resolve_schema_names_by_datastore(self, info, datastore_id, *args, **kwargs): """Retrieve a list of schema names for the provided datastore. """ get_kwargs = { 'workspace': info.context.workspace, 'pk': shortcuts.from_global_id(datastore_id, True), } datastore = shortcuts.get_object_or_404(models.Datastore, **get_kwargs) if not permissions.request_can_view_datastore(info, datastore): raise errors.PermissionDenied() return sorted(datastore.schemas.values_list('name', flat=True))
def resolve_table_names_by_schema(self, info, datastore_id, schema_name, **kwargs): """Retrieve a list of table names for the provided schema. """ get_kwargs = { 'name__iexact': schema_name, 'datastore_id': shortcuts.from_global_id(datastore_id, True), 'workspace': info.context.workspace, } schema = shortcuts.get_object_or_404(models.Schema, **get_kwargs) if not permissions.request_can_view_datastore(info, schema.datastore): raise errors.PermissionDenied() return sorted(schema.tables.values_list('name', flat=True))
def resolve_run_revisions(self, info, run_id, *args, **kwargs): """Retrieve revisions for the provided object. """ _type, pk = shortcuts.from_global_id(run_id) get_kwargs = { 'workspace': info.context.workspace, 'pk': pk, } resource = shortcuts.get_object_or_404(models.Run, **get_kwargs) revisions = resource.revisions\ .filter(applied_on__isnull=False)\ .exclude(metadata__field__isnull=False, metadata__field='object_id')\ .order_by('created_at') return revisions
def mutate(self, info, uid, token, password): errors = None user = shortcuts.get_object_or_404(models.User, pk=uid) try: ResetPasswordConfirm.perform_mutation(user, token, password) except PasswordResetTokenExpired: errors = [ ErrorType(resource='User', field='password_reset_token', code='invalid') ] except exceptions.ValidationError: errors = [ ErrorType(resource='User', field='password', code='invalid') ] return ResetPasswordConfirm(ok=(errors is None), errors=errors)
def edit_note(request, note_id): """Edit a note. This creates a new revision and bump the head to this new one""" # get the old note old_note = get_object_or_404(Note, note_id) if request.method == "POST": # get the new one from the form form = NoteForm(data=request.POST) if form.is_valid(): new_note = form.save(commit=False) new_note.save_as_revision_of(old_note) return redirect("notes:list") else: form = NoteForm(initial=old_note) return render("edit_note.html", { "form": form, }, request)
def entry(request, slug): ret = cache.get(Entry.get_cache_key(slug), None) if not ret: entry = get_object_or_404(Entry, slug=slug) tpl = entry.template or 'gae_blog/entry.html' ret = render_to_response( tpl, locals(), context_instance=RequestContext(request), ) ret = ret._get_content() if entry.cacheable: cache.set(Entry.get_cache_key(slug), ret, app_settings.BLOG_CACHE_TIMEOUT) return HttpResponse(ret)
def wiki(request, slug): ret = cache.get(Wiki.get_cache_key(slug), None) if not ret: wiki = get_object_or_404(Wiki, slug=slug) tpl = wiki.template or 'gae_wiki/wiki.html' ret = render_to_response( tpl, locals(), context_instance=RequestContext(request), ) ret = ret._get_content() if wiki.cacheable: cache.set(Wiki.get_cache_key(slug), ret, app_settings.WIKI_CACHE_TIMEOUT) return HttpResponse(ret)
def resolve_datastore_assets(self, info, slug, search=None, *args, **kwargs): """Retrieve the assets for this datastore. """ get_kwargs = { 'workspace': info.context.workspace, 'slug__iexact': slug, } datastore = shortcuts.get_object_or_404(models.Datastore, **get_kwargs) if not permissions.request_can_view_datastore(info, datastore): raise errors.PermissionDenied() queryset = models.Table.search_objects.execute( search=search, schema__datastore_id=datastore.id, deleted_at__isnull=True, ) return queryset.order_by('schema__name', 'name')
def show_note(request, note_id): # get the note. note = get_object_or_404(Note, note_id) return render("show_note.html", { 'note': note, }, request)
def entry_by_old_id(request, old_id): entry = get_object_or_404(Entry, old_id=int(old_id)) return HttpResponseRedirect(entry.get_absolute_url())
def item_info(request, slug): item = get_object_or_404(Item, slug=slug) return locals()