【发布时间】:2015-08-21 21:11:39
【问题描述】:
我正在使用 MySQL 后端构建 Python/Flask 应用程序。许多视图都有向路由提交数据的表单,然后路由通过db.session.commit() 添加数据。我可以确认 MySQL db 每次提交都会更新,但是如果我随后多次刷新页面,数据每次都会更改(即最近添加的项目会消失,然后重新出现)。
我做了几件事来尝试修复:
HTML 标头
我知道添加大量标头并希望获得最好的结果并不是最好的,但我添加了这些标头以对抗缓存:
<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 应用程序本身添加了标题:
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)
【问题讨论】:
标签: python mysql flask sqlalchemy apache2