0

I have a notification list at the top of my website.

  1. Each notification can be either "read" or "unread."
  2. Each notification is a clickable anchor element, taking the user to the post related to this notification.

Currently I use GET request to handle the user's click:

@webapp.route('/read')
@webapp.route('/read/<int:notification_id>')
@login_required
def read_notification(notification_id=None):
    if notification_id is None:
        return notifications.read(user=current_user)

    fetched_notifications = notifications.get(current_user)
    if notification is None:
        return fail(404, 'Invalid notification ID.')
    if notification.user.id != current_user.id:
        return fail(403, "You aren't allowed to access this page.")

    notifications.read(id_=notification_id)
    return redirect(notification.action_url or '/exercises')

I have a bad feeling about using a GET request to /read in order to change the state of the notification. On the other hand, I don't want to use POST (or PATCH), 'cause it will require me to use <form> (semantically wrong) or JavaScript (may create a laggy user experience).

Is there any better option?

The stack is vanilla JavaScript and Flask (Python 3.8).

Yam Mesicka
  • 6,243
  • 7
  • 45
  • 64

1 Answers1

1

You can actually redirect with the POST method by using code=307. For more information, you can read this

return redirect(notification.action_url or '/exercises', code=307)
Patch
  • 694
  • 1
  • 10
  • 29
  • Thank you for your time, but the question is about how to send the request to `/read`. – Yam Mesicka May 28 '20 at 10:55
  • You want to recive POST request in `/read`? you can do `@webapp.route('/read', methods=["POST"])` – Patch May 28 '20 at 10:57
  • I want to use `POST` (or `PATCH`) 'cause it's the right REST choice. On the other hand, I want the link to be clickable and to be immediately transferred to the action_url location. I can't just send POST request without using JS (or form, which is semantically wrong) – Yam Mesicka May 28 '20 at 11:00
  • Just use ajax it won't cause a "laggy experience" – Patch May 28 '20 at 11:02
  • But I need to change the state + redirect to other page. I will need to wait until the change-state request returns, and only then I will be able redirect. – Yam Mesicka May 28 '20 at 11:09
  • Use `Celery` if you want to work with background tasks an alternative is you can timeout the ajax request so it will send the request to change the state without redirecting and once it's completed you can redirect the user. Wait do you want to rediect without caring if the state changed? – Patch May 28 '20 at 11:10