python - 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>
解决方案
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>
推荐阅读
- c++ - Polymorphic value types and interfaces
- npm - Bootstrap 4如何覆盖用于定义其他默认变量的scss变量
- sql - 如何将当前月份值与过去 12 个月进行比较
- reactjs - Create-React-App 找不到我的图像文件夹
- android - 使用带有导航架构组件的底部菜单栏时如何从工具栏中删除后退按钮
- python - 拉取美国人口普查 API 时的 400 状态码
- javascript - 无法读取元素未定义的属性“onchange”
- scala - 在 SCALA 中连接映射时删除重复键
- android - Recyclerview 与 searchview 解除绑定问题
- xcode - 我可以从命令行安装 Xcode 吗?