Django:从存储中删除重复的消息 [英] Django: Remove duplicate messages from storage

查看:76
本文介绍了Django:从存储中删除重复的消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 messages 将Flash消息添加到模板(正如您期望的那样).

I'm using messages to add flash messages to the template (just as you'd expect).

我遇到的问题是,如果您双击指向生成消息的页面的链接,则该消息会出现两次.

The problem I have is that if you double click a link to a page that generates a message then the message appears twice.

我正在使用该消息告诉用户我已经将他们从他们期望的位置重定向了.他们不需要两次相同的消息.

I am using the message to tell the user I have redirected them from where they were expecting to go. They don;t need the same message twice.

我理解这里的逻辑,但是想知道如何删除重复的消息.

I understand the logic here but am wondering how I can remove duplicated messages.

  • 点击网址
  • 生成的消息,保存在存储中
  • 再次点击网址页面呈现之前
  • 生成第二条消息,保存在存储中
  • 响应添加存储中的所有消息
  • 通过两条消息发送邮件

最终,我希望这是一个中间件,这样它就可以掩盖所有请求.

Ultimately I would like this to be a middleware so it can cover off all requests.

推荐答案

使用自定义的MESSAGE_STORAGE,遇到相同的问题并找到另一个解决方案:

Ran into the same problem and found another solution, using a custom MESSAGE_STORAGE:

from django.contrib.messages.storage.session import SessionStorage
from django.contrib.messages.storage.base import Message


class DedupMessageMixin(object):
    def __iter__(self):
        msgset = [tuple(m.__dict__.items())
                  for m in super(DedupMessageMixin, self).__iter__()]
        return iter([Message(**dict(m)) for m in set(msgset)])


class SessionDedupStorage(DedupMessageMixin, SessionStorage):
    pass


# in settings
MESSAGE_STORAGE = 'some.where.SessionDedupStorage'

这对于将代码直接与消息一起播放(例如在视图中)的代码也能很好地工作.由于它是mixin,因此您可以轻松地将其重新用于其他消息存储.

This will work fine with code that would also play with messages directly, say in a view for example. Since it's a mixin, you can easily reuse it for other message storages.

这里是一种避免完全存储重复项的替代方法:

Here is an alternative to avoid storing duplicates at all:

from django.contrib.messages.storage.session import SessionStorage
from itertools import chain


class DedupMessageMixin(object):
    def add(self, level, message, extra_tags):
        messages = chain(self._loaded_messages, self._queued_messages)
        for m in messages:
            if m.message == message:
                return
        return super(DedupMessageMixin, self).add(level, message, extra_tags)

这篇关于Django:从存储中删除重复的消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆