【问题标题】:Flask - how to call python function with parameters in button?Flask - 如何使用按钮中的参数调用python函数?
【发布时间】:2021-11-03 20:35:55
【问题描述】:

我正在我的网站上开发一个通知系统。我决定在数据库中为他们制作一个模型。我还在 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>

【问题讨论】:

    标签: python html flask flask-sqlalchemy


    【解决方案1】:

    js文件

    function myfunction(){
       fetch("/send_notification", {
          method:"GET"
    })
    
    }
    
    

    html

    <button onclick="myfunction()">click me to send notification</button>
    

    【讨论】:

      【解决方案2】:
      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>
      

      【讨论】:

        猜你喜欢
        • 2015-09-03
        • 1970-01-01
        • 2017-07-24
        • 2021-09-20
        • 2017-03-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多