单击html按钮时如何调用python函数并传递参数?

时间:2019-03-09 12:12:42

标签: python flask

我显示了数据库中的数据

{% extends "layout.html" %}
{% block content %}
    <article class="media content-section">
            <div class="table-responsive">          
                <div class="table table-striped">
                    <table>
                        <thead>
                            <tr>
                                <th>Name</th>
                                <th>Phone Number</th>
                                <th> Send SMS </th>
                            </tr>
                        </thead>
                        {% for detail in details%}
                        <tbody>
                            <tr>
                                <th>{{ detail.username }}</th>
                                <th>{{ detail.phonenumber }}</th>
                                <th><button type="button" class="btn btn-success" onclick="'{{ url_for('sendsms', phonenumber = detail.phonenumber)}}'">Send Request</button></th>
                        </tr>
                    </tbody>
                {% endfor %}
            </table>
        </div>
    </article>
{% endblock content %}

在单击按钮时如何调用功能并通过电话号码?

当我按下该按钮时,sendms函数应该被调用并且电话号码应该传递给该函数。

我的路线是

def sendsms(phonenumber):
        account_sid = '************************'
        auth_token = '*************************'
        client = Client(account_sid, auth_token)

        message = client.messages.create(
                                  from_= current_user.username,
                                  body='i need immediately'
                                  to= phonenumber)

        print(message.sid)

1 个答案:

答案 0 :(得分:1)

当然,走吧。首先,让我们向HTML代码中添加表单元素。

{% for detail in details%}

#let's make a bunch of forms for every detail so you can send separate data for every request.

    <form action="{{ url_for('sendsms') }}" method="post">
        <tbody>
           <tr>
          <th><input type="text" name="username" value={{ detail.username }} required></th>
          <th><input type="text" name="phonenumber" value={{ detail.phonenumber }} required></th>
          <th><input type="submit" name="button" class="btn btn-success" value="Send Request"></a></th>
          </tr>
        </tbody>
    </form>
        {% endfor %}

然后,让我们的后端处理POST请求。

#Let's make sure that our route handles POST requests so add POST method to route:
@app.route('/sendsms', methods=['POST'])
def sendsms():
    account_sid = '************************'
    auth_token = '*************************'
    client = Client(account_sid, auth_token)

    #You can access values you sent in form using request.form data:
    phonenumber = request.form['phonenumber']
    username = request.form['username']

    message = client.messages.create(
                              from_= username,
                              body='i need immediately'
                              to= phonenumber)

    print(message.sid)

P.S。该代码可能应该工作,但是由于我无法检查它-至少会给您一个提示。祝你好运!