gpt4 book ai didi

python - MySQL 数据未在 Web 应用程序中更新 - Python/Flask

转载 作者:行者123 更新时间:2023-11-29 07:32:25 25 4
gpt4 key购买 nike

我正在使用 MySQL 后端构建 Python/Flask 应用程序。许多 View 都有向路由提交数据的表单,然后路由通过 db.session.commit() 添加数据。 。我可以确认 MySQL 数据库每次提交都会更新,但是如果我随后多次刷新页面,数据每次都会更改(即最近添加的项目将消失,重新出现)。

我做了一些事情来尝试修复:

HTML header
我知道添加大量 header 并不是最好的选择,但我添加了这些 header 来对抗缓存:

<meta http-equiv="cache-control" content="max-age=0" />
<meta http-equiv="cache-control" content="private, proxy-revalidate, s-maxage=0, no-cache, no-store, must-revalidate" />
<meta http-equiv="expires" content="0" />
<meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
<meta http-equiv="pragma" content="no-cache" />

Flask header 我向 Flask 应用程序本身添加了 header :

response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate" # HTTP 1.1.
response.headers["Pragma"] = "no-cache" # HTTP 1.0.
response.headers["Expires"] = "0" # Proxies.

禁用 MySQL 缓存

SET SESSION query_cache_type=OFF;

Apache2 禁用缓存

<filesMatch "\.(html|htm|js|css)$">
FileETag None
<ifModule mod_headers.c>
Header unset ETag
Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
Header set Pragma "no-cache"
Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT"
</ifModule>
</filesMatch>

一些基于打探和事实的行为:

  • 每当我执行sudo service apache2 restart时,遵循它一切正常。其他一些帖子提到可能有启动的进程导致了这种情况?
  • 我使用 SQLAlchemy 作为我的 ORM,所以有一次我认为这可能是 SQLAlchemy 缓存信息,所以在我尝试的每次提交之后 db.session.close()这样每次查询时连接都是新鲜的。

有人可以帮我吗?像许多学习 Flask 的人一样,我是 Web 应用程序开发的初学者。

非常感谢!

编辑:

  • 当我通过执行 python <strong>init</strong>.py 来运行应用程序时,它工作得很好。
  • 快速刷新页面时,我收到间歇性 HTTP 500 错误。

编辑2:下面是我要发布到的路由示例,然后我将重定向到自身并向用户显示 GET 选项。我希望在提交数据后,后续查询应该包含它,但很多时候 Web 应用程序不会显示最近添加的数据。在多次刷新时,它有时会显示,有时会消失。很奇怪:

@app.route('/projects', methods=['GET','POST'])
@login_required
def projects():
user = return_current_user()
if request.method == 'POST':
if request.form['title'] and request.form['description']:
project = Projects(request.form['title'], request.form['description'])
if project.title != None and project.description != None:
user.projects.append(project)
db.session.commit()

return redirect('/projects')
elif request.method == 'GET':
if 'clear-page' in request.args:
return redirect('/projects')
elif 'query' in request.args:
projects = Projects.query.filter(Projects.title.like('%'+request.args['query']+'%')).order_by(Projects.timestamp.desc()).all()

else:
projects = Projects.query.order_by(Projects.timestamp.desc()).all()

return render_template('projects.html', title="Projects", user=user, projects=projects)

最佳答案

我实际上已经弄清楚了这一点 - 解决方法是在查询之前添加 db.session.commit() 。不确定这是否是“正确”的方法,但它对我的小型应用程序很有用!

关于python - MySQL 数据未在 Web 应用程序中更新 - Python/Flask,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32149305/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com