Friday, 23 November 2018

What is the proper way to process the user-trigger events in Django?

For example, I have a blog based on Django and I already have several functions for users: loginedit_profileshare.

But now I need to implement a mission system.

  1. User logins, reward 10 score per day
  2. User completes his profile, reward 20 score
  3. User shares my blogs, reward 30 score

I don't want to mix reward code with normal functions code. So I decide to use message queue. Pseudo code may look like:

@login_required
def edit_profile(request):
    user = request.user
    nickname = ...
    desc = ...
    user.save(...)
    action.send(sender='edit_profile', payload={'user_id': user.id})
    return Response(...)

And the reward can subscribe this action

@receiver('edit_profile')
def edit_profile_reward(payload):
    user_id = payload['user_id']
    user = User.objects.get(id=user_id)
    mission, created = Mission.objects.get_or_create(user=user, type='complete_profile')
    if created:
         user.score += 20
         user.save()

But I don't know if this is the right way. If so, what message queue should I use? django-channel / django-q or something else? If not, what is the best practice?



from What is the proper way to process the user-trigger events in Django?

No comments:

Post a Comment