如何在Flask+SQLite+Python环境下实现数据无刷新展示
问题:点击保存按钮后实现页面异步更新数据展示
我通过按钮触发llm.py中的test函数保存大语言模型(LLM)的输出,目前点击按钮能成功将数据存入数据库,但必须刷新页面才能在主页面看到新数据,希望实现无需刷新页面就能立即展示新数据。
现有代码情况
llm.py中的test函数
该函数负责解析LLM输出并写入SQLite数据库:
def test(output): data = json.loads(output) label = data['label'] explanation = data['explanation'] etymology = data['etymology'] example = data['example'] connection = sqlite3.connect('database.db') cur = connection.cursor() cur.execute("INSERT INTO emotions (label, explanation, etymology, example) VALUES (?, ?, ?, ?)",(label, explanation, etymology, example)) connection.commit() connection.close() print(data)
Flask主路由(app.py)
主页面路由从数据库读取数据并渲染模板:
@app.route('/') def index(): conn = get_db_connection() emotions = conn.execute('SELECT * FROM emotions ORDER BY id DESC').fetchall() conn.close() return render_template('index.tpl', gradioserver_url='http://127.0.0.1:7860', emotions=emotions)
页面模板(index.tpl)
页面嵌入Gradio界面,并渲染数据库中的情感数据:
<iframe src="{{ gradioserver_url }}" width="100%" height="400" frameborder="0" ></iframe> <h2>This is what others feel. And maybe you</h2> <div class="emotions-container"> {% for emotion in emotions %} <div class='emo'> <h2>{{ emotion['label'] }}</h2> <p>{{ emotion['example'] }}</p> <p>{{ emotion['explanation'] }}</p> <p>{{ emotion['etymology'] }}</p> </div> {% endfor %}
尝试过的方法及问题
我试着用AJAX实现异步更新,但对POST/GET逻辑不熟悉,写了以下代码:
var xhr = new XMLHttpRequest(); xhr.open('POST', 'http://127.0.0.1:5000/', true); xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8'); xhr.onload = function() { if (xhr.status === 200) { console.log(xhr.responseText); } }; xhr.send(JSON.stringify(data));
控制台提示“data未定义”,因为test函数里解析出的data变量和这段AJAX代码没有关联。另外,我注释掉xhr.send(JSON.stringify(data));后,点击Gradio的保存按钮(代码如下),控制台没有任何反应:
btn_save = gr.Button(value="Save Emotion") btn_save.click(test, inputs=[emo_out], outputs=emo_out)
内容的提问来源于stack exchange,提问作者S.H
相关产品推荐
相关产品推荐

