【问题标题】:Is it possible to limit the number of messages a user can send a day with Django postman?是否可以限制用户每天可以使用 Django postman 发送的消息数量?
【发布时间】:2018-01-21 18:54:31
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: python django django-apps


    【解决方案1】:

    回答我自己的问题。

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

    起初我尝试创建自己的ReplyView,但让它与 django postman 一起工作很痛苦:我没有成功,所以如果有人知道怎么做,我会很感激阅读他/她/阿帕奇。

    另外,请注意我所做的一切都是为了不编辑 Django postman 代码(因为我的修改会被任何 Django Postman 更新破坏)。


    1。创建您的自定义decorator

    在您的decorators.py 文件中(如果没有,则必须创建该文件),您必须创建decorator 用于装饰默认邮递员ReplyView。我将假设您将 profile 模型与用户关联,因为您的个人资料将记住每天发送的消息数量,而 canSendMessage 方法将检查是否允许连接的用户发送新消息(返回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'),
    ]
    

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

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

    【讨论】:

      【解决方案2】:

      作为一个简单的想法,在数据库中插入新的 msg 应该有一个限制它们的数量的条件(前一个 msg 的计数不是 > max ) 另一种方法:当 (selet * form table where userid=sesion and count(usermsg) 时,您将显示 msg jsut 的输入

      【讨论】:

      • 我想我不会那样得到我想要的,但我仍然同意你手动控制发送消息数量的想法。实际上我将尝试覆盖postman views,我还将在我的用户profile 模型中创建新属性,这就是我要计算的地方。如果可行,我会在这里发布我所做的!
      猜你喜欢
      • 2021-10-06
      • 1970-01-01
      • 1970-01-01
      • 2019-12-20
      • 2018-12-16
      • 1970-01-01
      • 2014-07-14
      • 2019-07-21
      • 1970-01-01
      相关资源
      最近更新 更多