首页 > 解决方案 > Flask - 如何使用按钮中的参数调用python函数?

问题描述

我正在我的网站上开发一个通知系统。我决定在数据库中为他们制作一个模型。我还在 views.py 中创建了一个函数,该函数接受接收通知的用户的参数和通知的类型。这是代码:

@views.route('/send_notification',methods = ['GET','POST'])
@login_required
def send_notification(user, type):

    reciever = User.query.filter_by(username = user).first()

    if type == 'family-invitation':
        family = Family.query.filter_by(id = current_user.family_id).first()
        description = "invites you to their family!"
        new_notification = Notification(sender = current_user.username, sender_prof_img = family.prof_img, user_id = reciever.id, description = description)
        db.session.add(new_notification)
        db.session.commit()
        flash("Invitation to family has been sent!", category="success")

    return True

现在我希望能够在有人邀请他们时向用户发送通知。当有人按下按钮时,我正在考虑调用 python 函数,但我不知道如何编码。

我想出了这样的东西,但它不起作用:

<button
      onclick="window.location.href = '{{ url_for('views.send_notification(profileUser.username, 'family-invitation')') }}';"
    >
      Invite to family
    </button>

标签: pythonhtmlflaskflask-sqlalchemy

解决方案


Flask Jinja 模板中的 url_for() 不能这样工作。它形成了特定资源的 URL,这意味着您不能将 Python 代码作为参数传递。我首先想到的选项是使用 URL 参数将数据传递给您的路由函数。

@views.route('/send_notification/<user>/<type>',methods = ['GET','POST'])
@login_required
def send_notification(user, type):

    reciever = User.query.filter_by(username = user).first()

    if type == 'family-invitation':
        family = Family.query.filter_by(id = current_user.family_id).first()
        description = "invites you to their family!"
        new_notification = Notification(sender = current_user.username,                     
    sender_prof_img = family.prof_img, user_id = reciever.id, description = description)
    db.session.add(new_notification)
    db.session.commit()
    flash("Invitation to family has been sent!", category="success")

return True

这样您的 HTML 将如下所示:

<button
  onclick="btnOnClick(profileUser.username, 'family-invitation');"
    >
  Invite to family
</button>
<script>
    function btnOnClick(username, notificationType) {
    window.location = `/send_notification/${username}/${notificationType}`;
}
</script>

推荐阅读