【问题标题】:Change state and redirect改变状态和重定向
【发布时间】:2020-09-15 14:30:46
【问题描述】:

我的网站顶部有一个通知列表。

  1. 每个通知都可以是“已读”或“未读”。
  2. 每个通知都是一个可点击的锚元素,将用户带到与此通知相关的帖子。

目前我使用GET请求来处理用户的点击:

@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')

我对使用 GET 请求 /read 来更改通知状态有一种不好的感觉。另一方面,我不想使用 POST(或 PATCH),因为它需要我使用 &lt;form&gt;(语义错误)或 JavaScript(可能会导致用户体验滞后)。

还有更好的选择吗?

堆栈是 vanilla JavaScript 和 Flask (Python 3.8)。

【问题讨论】:

    标签: javascript html http web flask


    【解决方案1】:

    您实际上可以使用POST 方法通过code=307 进行重定向。欲了解更多信息,you can read this

    return redirect(notification.action_url or '/exercises', code=307)
    

    【讨论】:

    • 感谢您的宝贵时间,但问题是如何将请求发送到/read
    • 您想在/read 中接收 POST 请求?你可以做@webapp.route('/read', methods=["POST"])
    • 我想使用POST(或PATCH),因为它是正确的 REST 选择。另一方面,我希望链接可以点击并立即转移到 action_url 位置。我不能只发送 POST 请求而不使用 JS(或表单,这在语义上是错误的)
    • 只使用 ajax 不会导致“延迟体验”
    • 但我需要更改状态+重定向到其他页面。我需要等到更改状态请求返回,然后才能进行重定向。
    猜你喜欢
    • 2016-12-20
    • 1970-01-01
    • 2021-03-04
    • 2018-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多