python - 在 Bottle 生成的网页上添加和减去按钮

标签 python bottle

目前我有一个 bottle 应用程序,它从 sqlite 数据库中读取元素并将它们显示在表格中(使用啤酒,因为好吧......我喜欢啤酒)。我希望能够使用表格行中的加减按钮调整表格中的数字(金额)。这些按钮应该既更新数据库中的金额,又刷新页面上显示的金额。

这是 python/bottle 部分:

@app.route('/')
@app.route('/display')
    def display():
    conn = sqlite3.connect('beers.db')
    c = conn.cursor()
    c.execute("SELECT id, brewer, beer, amount FROM beer;")
    result = c.fetchall()
    c.close()

    output = template('make_table', rows=result)
    return output

这是当前模板,带有加减按钮。

<p>The available beers are:</p>
<table border="1">
%for row in rows:
    <tr>
    %for col in row:
        <td>{{col}}</td>
    %end
        <td><input type ="button" value="Add"></td>
        <td><input type ="button" value="Subtract"></td>
    </tr>
%end
</table>

感谢您的帮助!

最佳答案

使用 POST 方法添加一个 /display 路由。

在此,获取啤酒 ID 的值,以及用户是否单击了“添加”或“订阅”。

完成此操作后,您将获得啤酒 ID 和要执行的操作,您只需使用 DB 执行操作,然后重定向到 /display 页面。

这是 Bottle 应用代码:

@app.route('/display', method='POST')
def display_mod():
    #You get the value of each button : None if non clicked / Add or Sub if clicked
    add = request.POST.get('Add')
    sub = request.POST.get('Sub')
    # b_id is the ID of the beer the user's clicked on (either on add or sub)
    b_id = request.POST.get('beer_id')

    if add is not None:
        # do something
        redirect("/display")

    if sub is not None:
        # so something
        redirect("/display")

然后,更改您的模板以包含一个表单并更改提交按钮中的两个按钮。您还需要放置一个隐藏 输入,以便您可以将数据传递给应用。

<p>The available beers are:</p>
<table border="1">
%for row in rows:
    <tr>
    <!-- Here you grab the beer's ID that you'll use later -->
    %p_id = row[0] 
    %for col in row:
        <td>{{col}}</td>
    %end
        <form action="/display" method="POST">
            <!-- input type hidden, and value is the ID of the beer -->
            <input type = "hidden" name ="beer_id" value= "{{p_id}}">
            <td><input type ="submit" name="Add" value="Add"></td>
            <td><input type ="submit" name="Sub" value="Subtract"></td>
        </form>
    </tr>
%end
</table>

给你。希望对您有所帮助(如果有帮助,请不要害羞,请给我一杯啤酒!)

关于python - 在 Bottle 生成的网页上添加和减去按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30513805/

相关文章:

python - 使用 asyncio.gather 不会引发内部异常

python - 如何从 python 获取 C++ 结构?

javascript - 我们如何在不使用 Javascript 的情况下向 python Bottle 服务器发送 GET 请求?

python - Bottle 是否处理非并发请求?

python - 如何在 Matplotlib 中连接图形坐标?

python - 如何使用 matplotlib 在 Axis 上显示完整的散点标记?

java - POST 请求未发送

Python 瓶 + postgresql

Python:使用 Bottle 框架从浏览器检索当前 URL

python - 删除文本中除 "\n"和 "/"之外的所有特殊字符