MySQL数据正在使用Google Cloud SQL和SQLAlchemy进行缓存 [英] MySQL data is caching with google cloud SQL and SQLAlchemy
问题描述
这是我关于stackoverflow的第一个问题,所以如果我做错了,请纠正我:).
This is my first question on stackoverflow, so please correct me if I do something wrong :).
我来自Google Cloud SQL托管数据库的数据正在使用Flask-SQLAlchemy进行缓存.当我添加新记录并尝试获取该记录时,它不存在.
My data from a database hosted at Google Cloud SQL is caching with Flask-SQLAlchemy. When I add a new record and try to get that record it doesn't exist.
我正在使用一个添加记录的脚本,并且我使用一个脚本来获取记录.
I am using a script that adds records and I use one to get records.
我首先使用SQLite进行了尝试,效果很好.但是使用Google Cloud SQL上的MySQL却没有.
I first tried it with SQLite, that worked perfectly. But with MySQL at Google Cloud SQL it doesn't.
每次我向数据库添加/更改某些内容时,我都会使用 db.session.commit()
Every time I add/change something to the database I use db.session.commit()
我将pymysql模块与此配合使用: pymysql.install_as_MySQLdb()
我的连接URI如下所示: mysql://...
I use the pymysql module with this: pymysql.install_as_MySQLdb()
And my connection URI looks like this: mysql://...
这就是我用来添加新记录的方式(我的脚本用于添加笑话):
This is what I use to add a new record (my script is for adding jokes):
new_joke = Jokes(joke, user["username"], user["id"], avatar_url, "0")
db.session.add(new_joke)
db.session.commit()
这就是我用来获取记录(随机)的方法:
And this is what I use to get a record (random):
jokes = Jokes.query.all()
randint = random.randint(0, len(jokes) - 1)
joke = jokes[randint]
推荐答案
我找到了答案!
通过在进行查询之前执行 db.session.commit()
,它将刷新其缓存.
By doing db.session.commit()
before making a query, it refreshes it's cache.
我的代码现在看起来像这样:
My code now looks like this:
db.session.commit()
jokes = Jokes.query.all()
randint = random.randint(0, len(jokes) - 1)
joke = jokes[randint]
这篇关于MySQL数据正在使用Google Cloud SQL和SQLAlchemy进行缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!