Marks notifications as either read or unread depending of POST parameters.
    Takes ``action`` as POST data, it can either be ``read`` or ``unread``.

    :param request: HTTP Request context.

    :return: Response to mark_all action.
485138
def mark_all(request):
    
    action = request.POST.get('action', None)
    success = True

    if action == 'read':
        request.user.notifications.read_all()
        msg = _("Marked all notifications as read")
    elif action == 'unread':
        request.user.notifications.unread_all()
        msg = _("Marked all notifications as unread")
    else:
        msg = _("Invalid mark action")
        success = False

    ctx = {'msg': msg, 'success': success, 'action': action}

    return notification_redirect(request, ctx)
430108
def watch_request(titles, unwatch = false)
      titles = titles.is_a?(Array) ? titles : [titles]
      params = {
        action: 'watch',
        titles: titles.shift(get_limited(titles.length, 50, 500)).join('|'),
        token: get_token('watch')
      }
      success_key = 'watched'
      if unwatch
        params[:unwatch] = 1
        success_key = 'unwatched'
      end

      post(params)['watch'].inject({}) do |result, entry|
        title = entry['title']
        if entry.key?(success_key)
          result[title] = entry.key?('missing') ? nil : true
        else
          result[title] = false
        end

        result
      end
    end
1326082
def response_action(self, request, queryset):  # noqa
        
        # There can be multiple action forms on the page (at the top
        # and bottom of the change list, for example). Get the action
        # whose button was pushed.
        try:
            action_index = int(request.POST.get('index', 0))
        except ValueError:  # pragma: no cover
            action_index = 0

        # Construct the action form.
        data = request.POST.copy()
        data.pop(helpers.ACTION_CHECKBOX_NAME, None)
        data.pop("index", None)

        # Use the action whose button was pushed
        try:
            data.update({'action': data.getlist('action')[action_index]})
        except IndexError:  # pragma: no cover
            # If we didn't get an action from the chosen form that's invalid
            # POST data, so by deleting action it'll fail the validation check
            # below. So no need to do anything here
            pass

        action_form = self.action_form(data, auto_id=None)
        action_form.fields['action'].choices = self.get_action_choices(request)

        # If the form's valid we can handle the action.
        if action_form.is_valid():
            action = action_form.cleaned_data['action']
            func, name, description = self.get_actions(request)[action]

            # Get the list of selected PKs. If nothing's selected, we can't
            # perform an action on it, so bail.
            if action_form.cleaned_data['select_across']:
                selected = ALL
            else:
                selected = request.POST.getlist(helpers.ACTION_CHECKBOX_NAME)

            if not selected:
                return None

            revision_field = self.model._concurrencymeta.field

            if self.check_concurrent_action:
                self.delete_selected_confirmation_template = self.get_confirmation_template()

                # If select_across we have to avoid the use of concurrency
                if selected is not ALL:
                    filters = []
                    for x in selected:
                        try:
                            pk, version = x.split(",")
                        except ValueError:  # pragma: no cover
                            raise ImproperlyConfigured('`ConcurrencyActionMixin` error.'
                                                       'A tuple with `primary_key, version_number` '
                                                       'expected:  `%s` found' % x)
                        filters.append(Q(**{'pk': pk,
                                            revision_field.attname: version}))

                    queryset = queryset.filter(reduce(operator.or_, filters))
                    if len(selected) != queryset.count():
                        messages.error(request, 'One or more record were updated. '
                                                '(Probably by other user) '
                                                'The execution was aborted.')
                        return HttpResponseRedirect(".")
                else:
                    messages.warning(request, 'Selecting all records, you will avoid the concurrency check')

            response = func(self, request, queryset)

            # Actions may return an HttpResponse, which will be used as the
            # response from the POST. If not, we'll be a good little HTTP
            # citizen and redirect back to the changelist page.
            if isinstance(response, HttpResponse):
                return response
            else:
                return HttpResponseRedirect(".")
586830
public function readNotifications(Request $request)
    {
        if (!$request->isXmlHttpRequest()) {
            $this->app->abort(400);
        }

        try {
            $this->getEventsManager()->read(
                explode('_', (string) $request->request->get('notifications')),
                $this->getAuthenticatedUser()->getId()
            );

            return $this->app->json(['success' => true, 'message' => '']);
        } catch (\Exception $e) {
            return $this->app->json(['success' => false, 'message' => $e->getMessage()]);
        }
    }
1117741
def notifications_mark_read(input_params={}, always_retry=True, **kwargs):
    
    return DXHTTPRequest('/notifications/markRead', input_params, always_retry=always_retry, **kwargs)
554080
public void handleRequest(String request) {
        if (messageListener != null) {
            log.debug("Received Http request");
            messageListener.onInboundMessage(new RawMessage(request), null);
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Received Http request:" + NEWLINE + request);
            }
        }
    }
627762
def post(self, request, *args, **kwargs):
        
        return self.unlock(request, *args, **kwargs)
964876
def do_POST(self, request, response):
        # pylint: disable=C0103
        
        # Get the request JSON content
        data = jsonrpclib.loads(to_str(request.read_data()))

        # Convert from Jabsorb
        data = jabsorb.from_jabsorb(data)

        # Dispatch
        try:
            result = self._unmarshaled_dispatch(data, self._simple_dispatch)
        except NoMulticallResult:
            # No result (never happens, but who knows...)
            result = None

        if result is not None:
            # Convert result to Jabsorb
            if "result" in result:
                result["result"] = jabsorb.to_jabsorb(result["result"])

            # Store JSON
            result = jsonrpclib.jdumps(result)
        else:
            # It was a notification
            result = ""

        # Send the result
        response.send_content(200, result, "application/json-rpc")
87267
def mark_read(request, message_id, dispatch_id, hashed, redirect_to=None):
    
    if redirect_to is None:
        redirect_to = get_static_url('img/sitemessage/blank.png')

    return _generic_view(
        'handle_mark_read_request', sig_mark_read_failed,
        request, message_id, dispatch_id, hashed, redirect_to=redirect_to
    )
335491
def comet_view(self, request):
        
        request_id = self.id_for_request(request)
        if not request_id:
            request.write(HttpResponse(403).as_bytes())
            request.finish()
            return
        
        data = {
            'headers': request.headers,
            'arguments': request.arguments,
            'remote_ip': request.remote_ip,
            'request_id': request_id,
        }
        message_kind = 'comet-%s' % (request.method,)
        if request.method == 'POST':
            data['body'] = simplejson.loads(request.body)
            request.write(HttpResponse(201).as_bytes())
            request.finish()
        else:
            self.pending_requests[request_id].append(request)
        self.publish(Message(message_kind, datetime.now(), data))
843549
def process_request(self, request):
        
        # Initialize thread local storage
        threadlocal.actionslog = {
            'signal_duid': (self.__class__, time.time()),
            'remote_ip': request.META.get('REMOTE_ADDR'),
        }

        # In case of proxy, set 'original' address
        if request.META.get('HTTP_X_FORWARDED_FOR'):
            threadlocal.actionslog['remote_ip'] = request.META.get('HTTP_X_FORWARDED_FOR').split(',')[0]

        # Connect signal for automatic logging
        if hasattr(request, 'user') and hasattr(request.user, 'is_authenticated') and request.user.is_authenticated():
            set_user = curry(self.set_user, request.user)
            pre_save.connect(set_user, sender=LogAction, dispatch_uid=threadlocal.actionslog['signal_duid'], weak=False)
434684
def _doSendRequest(self, data, get_thread_id=False):
        """"""
        j = self._post(self.req_url.SEND, data, fix_request=True, as_json=True)

        # update JS token if received in response
        fb_dtsg = get_jsmods_require(j, 2)
        if fb_dtsg is not None:
            self._payload_default["fb_dtsg"] = fb_dtsg

        try:
            message_ids = [
                (action["message_id"], action["thread_fbid"])
                for action in j["payload"]["actions"]
                if "message_id" in action
            ]
            if len(message_ids) != 1:
                log.warning("Got multiple message ids' back: {}".format(message_ids))
            if get_thread_id:
                return message_ids[0]
            else:
                return message_ids[0][0]
        except (KeyError, IndexError, TypeError) as e:
            raise FBchatException(
                "Error when sending message: "
                "No message IDs could be found: {}".format(j)
            )
620713
def mark_all_as_read(self, recipient=None):
        
        # We want to filter out read ones, as later we will store
        # the time they were marked as read.
        qset = self.unread(True)
        if recipient:
            qset = qset.filter(recipient=recipient)

        return qset.update(unread=False)
1250392
def mark_notifications_as_read(self, last_read_at=datetime.datetime.utcnow()):
        
        assert isinstance(last_read_at, datetime.datetime)
        put_parameters = {
            "last_read_at": last_read_at.strftime('%Y-%m-%dT%H:%M:%SZ')
        }

        headers, data = self._requester.requestJsonAndCheck(
            "PUT",
            "/notifications",
            input=put_parameters
        )
1154741
def render_POST(self, request):
        
        try:
            d = self.getAndSubmitChanges(request)
        except Exception:
            d = defer.fail()

        def ok(_):
            request.setResponseCode(202)
            request.finish()

        def err(why):
            code = 500
            if why.check(ValueError):
                code = 400
                msg = unicode2bytes(why.getErrorMessage())
            else:
                log.err(why, "adding changes from web hook")
                msg = b'Error processing changes.'
            request.setResponseCode(code, msg)
            request.write(msg)
            request.finish()

        d.addCallbacks(ok, err)

        return server.NOT_DONE_YET
868353
def write_request(request, notification)
      message = Kafka::Protocol::RequestMessage.new(
        api_key: request.api_key,
        api_version: request.respond_to?(:api_version) ? request.api_version : 0,
        correlation_id: @correlation_id,
        client_id: @client_id,
        request: request,
      )

      data = Kafka::Protocol::Encoder.encode_with(message)
      notification[:request_size] = data.bytesize

      @encoder.write_bytes(data)

      nil
    rescue Errno::ETIMEDOUT
      @logger.error "Timed out while writing request #{@correlation_id}"
      raise
    end
995983
def send_request(request)
      api_name = Protocol.api_name(request.api_key)

      # Default notification payload.
      notification = {
        broker_host: @host,
        api: api_name,
        request_size: 0,
        response_size: 0,
      }

      raise IdleConnection if idle?

      @logger.push_tags(api_name)
      @instrumenter.instrument("request.connection", notification) do
        open unless open?

        @correlation_id += 1

        @logger.debug "Sending #{api_name} API request #{@correlation_id} to #{to_s}"

        write_request(request, notification)

        response_class = request.response_class
        response = wait_for_response(response_class, notification) unless response_class.nil?

        @last_request = Time.now

        response
      end
    rescue SystemCallError, EOFError, IOError => e
      close

      raise ConnectionError, "Connection error #{e.class}: #{e}"
    ensure
      @logger.pop_tags
    end