使用Flask、Python、PostgreSQL构建应用时点击按钮列表不显示怎么办
问题原因
- Jinja2 模板变量渲染错误,且循环逻辑有误
当前代码把<ul>标签放在了for循环内部,会为每一个建筑生成单独的隐藏列表,同时building[0]没有加Jinja2的渲染标记,浏览器会直接把它当成普通文本展示,不会读取变量值。 - 按钮点击事件没有阻止默认行为
按钮用的是<a>标签,默认点击后会跳转到#,触发页面刷新,导致还没执行动画就刷新了页面。 - 数据库连接资源未释放
原代码只关闭了游标,没有关闭数据库连接,长时间运行会出现连接泄漏问题。 - 去重逻辑可以优化
用Python层面做去重效率远低于直接用SQL的DISTINCT关键字实现。
修复方案
后端Python代码修改
import flask import psycopg2 as pg app = flask.Flask(__name__) @app.route('/') def home(): return flask.render_template('interface.html') @app.route('/GetBuildingsLists', methods = ['GET','POST']) def GetBuildingsLists(): print('Connecting to the PostgreSQL database...') db = pg.connect( host="****", database="****", user ="****", password="*****") db_cursor = db.cursor() # 直接用SQL去重,效率更高 q = "SELECT DISTINCT building_id FROM table1" db_cursor.execute(q) buildings = db_cursor.fetchall() # 提前把元组转为字符串列表,模板层不需要再取下标 unique_buildings = [item[0] for item in buildings] db_cursor.close() # 新增关闭数据库连接的逻辑 db.close() return flask.render_template('interfaceLists.html', unique_buildings = unique_buildings) if __name__ == '__main__': app.run(debug=True)
interfaceLists.html模板修改
<html> <head> <title>Results</title> <style> .links-unordered { display: inline-block; position: relative; } .links-unordered { margin-top: 20px; min-height: 30px; } .links-unordered .toggle-button { text-decoration: none; padding: 12px 16px 12px 16px; transition: 0.2s; border: 1px solid black; } .links-unordered .toggle-button:hover, .links-unordered .toggle-button:active, .links-unordered .toggle-button:focus, .links-unordered .toggle-button:visited { text-decoration: none; color: black; } .links-unordered .toggle-button:hover { border-width: 2px; } .links-unordered ul { position: absolute; top: 10px; margin-top: 25px; padding-inline-start: 20px; list-style: none; } .links-unordered ul li { line-height: 25px; padding-left: 15px; } .links-unordered a { text-decoration: none; color: black; } </style> </head> <body> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="demo_script_src.js"></script> <div class="links-unordered"> <a class="toggle-button" href="#">Buildings</a> <!-- ul移到循环外部,只生成一个列表 --> <ul style="display:none;"> {% for building in unique_buildings %} <!-- 变量加{{ }}标记才能被Jinja渲染 --> <li><a href="#">{{ building }}</a></li> {% endfor %} </ul> </div> </body> </html>
JS点击逻辑修改
$(document).ready(function() { $(".toggle-button").click(function(e) { // 阻止a标签默认跳转刷新行为 e.preventDefault(); // 加stop()防止多次点击出现动画叠加问题 $(this).parent().find("ul").stop().slideToggle(); }); })
内容的提问来源于stack exchange,提问作者coder96
相关产品推荐
相关产品推荐

