Flask 点击前端按钮时如何调用带参数的Python视图函数?
问题原因及修复方案
第一步:修复后端视图代码
你现有后端存在两个核心问题:
- 路由规则没有配置和视图函数参数对应的路径占位符,Flask无法将请求路径中的参数传递给视图函数
- 视图函数不能直接返回布尔值
True,必须返回合法的Flask响应对象(比如重定向回原页面)
修改后的后端代码如下:
# 路由中添加两个路径参数占位符,和视图函数参数对应 @views.route('/send_notification/<string:user>/<string:type>', methods = ['GET','POST']) @login_required def send_notification(user, type): receiver = User.query.filter_by(username = user).first() # 可以加个判断,避免接收方不存在时报错 if not receiver: flash("目标用户不存在", category="error") return redirect(request.referrer) if type == 'family-invitation': family = Family.query.filter_by(id = current_user.family_id).first() description = f"{current_user.username} invites you to their family!" new_notification = Notification( sender = current_user.username, sender_prof_img = family.prof_img, user_id = receiver.id, description = description ) db.session.add(new_notification) db.session.commit() flash("Invitation to family has been sent!", category="success") # 返回重定向到之前的页面,而不是布尔值 return redirect(request.referrer)
注:如果还没有导入对应依赖,需要在文件顶部加from flask import request, redirect
第二步:修复前端按钮代码
你之前的Jinja url_for语法错误,参数需要作为关键字参数传入url_for,而不是写在函数名的括号字符串里,同时要注意引号的嵌套转义:
<button onclick="window.location.href = '{{ url_for('views.send_notification', user=profileUser.username, type='family-invitation') }}';" > Invite to family </button>
可选优化建议
当前用GET请求发送通知容易被爬虫或者浏览器预加载误触发,建议改成POST表单提交的方式更安全:
<form action="{{ url_for('views.send_notification', user=profileUser.username, type='family-invitation') }}" method="POST"> <button type="submit">Invite to family</button> </form>
内容的提问来源于stack exchange,提问作者FlafyKing
相关产品推荐
相关产品推荐

