是否可以限制用户每天可以使用 Django 邮递员发送的消息数量?

Is it possible to limit the number of messages a user can send a day with Django postman?

我已经使用 Django Postman 几周了,为了限制每个用户发送的消息数量,我一直在想 限制数量的最佳方法是什么用户一天、一周可以发送的消息数量……使用 Django-postman

为了找到 how 的答案,我也已经浏览了数周的专门文档,但我认为目前这不是一个用例,而且我真的不知道如何管理它。

当然,我不是在寻找一个完美的答案,但我想避免编写迷宫般的代码,所以也许只是一些关于它的想法可以帮助我看清这个问题。

非常感谢您对该主题的帮助!

作为一个简单的想法,在数据库中插入新的味精应该有一个条件来限制它们的数量(前一个味精的计数不 > 最大) 另一种方法:您将在 (selet * form table where userid=sesion and count(usermsg)< max )

时显示 msg jsut 的输入

回答我自己的问题。

经过大量研究和数小时不成功的测试,我找到了这样做的方法(虽然这没有集成在 django-postman 应用程序本身中)。其实这对很多人来说可能听起来很基础,但没关系,我仍然会分享我的解决方案,它依赖于 decorators.

起初我尝试创建自己的 ReplyView,但是让它与 django postman 一起工作非常痛苦:我没有成功,所以如果有人知道如何做到这一点,我将不胜感激阅读 him/her/apache.

此外,请注意,我已尽一切努力避免编辑 Django Postman 代码(因为我的修改会被任何 Django Postman 更新破坏)。


1。创建您的自定义 decorator

在您的 decorators.py 文件中(如果没有则必须创建),您必须创建 decorator 您将用于装饰默认 Postman ReplyView .我假设您将一个 profile 模型与用户相关联,因为您的个人资料将记住一天发送的消息数量,以及一个 canSendMessage 方法将检查是否允许连接的用户发送新消息(returns True 如果达到用户配额)。

from django.contrib import messages
from django.shortcuts import redirect

def count_messages_sent():
    def decorator_fun(func):
        def wrapper_func(request, *args, **kwargs):

            user_profile = request.user.profile

            # we check if user is allowed to send a new message
            if not user_profile.canSendMessage(): 
                messages.error(request, "Messages limit reached")
                return redirect('postman:inbox')

            # if he is, we call expected view, and update number of messages sent
            called_func = func(request, *args, **kwargs)
            user_profile.nbr_messages_sent_today += 1
            user_profile.save()

            return called_func
        return wrapper_func
    return decorator_fun

2。使用您的自定义 decorator

正如我之前所说:

  • 我不想编辑原始邮递员代码,
  • 我不想创建自定义视图。

因此,我们将不得不装饰 Django Postman ReplyView!如何?通过您的应用 urls.py 文件:

from postman import views as postman_views
from yourApp.decorators import count_messages_sent

urlpatterns = [
    ... 
    url(r'^messages/reply/(?P<message_id>[\d]+)/$', count_messages_sent()(postman_views.ReplyView.as_view()), name='custom_reply'),
]

就是这样!它就像一个魅力。

如果您有任何改进的想法,请随时分享!