缓存Python脚本返回的mysql查询
我有一个python“2.6.4”脚本:缓存Python脚本返回的mysql查询,python,mysql,performance,caching,Python,Mysql,Performance,Caching,我有一个python“2.6.4”脚本: #!/usr/bin/python import MySQLdb import csv import pprint db = MySQLdb.connect(host="localhost", # The Host user="username", # username passwd="password", # password
#!/usr/bin/python
import MySQLdb
import csv
import pprint
db = MySQLdb.connect(host="localhost", # The Host
user="username", # username
passwd="password", # password
db="dbname") # name of the data base
cursor = db.cursor()
cursor.execute("SELECT name, id, city, storeid FROM Products;")
StudentsData = cursor.fetchall()
pprint.pprint(StudentsData)
此查询返回数百万行,执行需要3分钟,每天运行20次,everyuser需要等待3分钟才能获取输出
我在考虑缓存它,但我不知道如何在python中进行缓存,
这是一个好主意吗?如果是的话,我如何使用obove代码来实现呢
在Python 3中,如果有更好的方法,请帮助我?,对于一个非常简单的例子,您可以查看functools.lru\u缓存:
对于更复杂的缓存,烧杯可能是一种选择:是否缓存完全取决于您。过时的数据会成为问题吗 我能想到的最简单的缓存方案是使用Python的类似以下内容: 导入MySQLdb 导入csv 导入pprint 导入时间 最大缓存时间=60*20分钟 CACHE\u FILENAME='results.CACHE' 使用openCACHE_文件名,“r”作为缓存: cached=pickle.loadcache iftime.time>cached['timestamp']+最大缓存时间: 缓存太旧,请运行查询 db=MySQLdb.connecthost=localhost,主机 user=用户名,用户名 passwd=密码,密码 db=dbname数据库的名称 cursor=db.cursor cursor.execute从产品中选择名称、id、城市、门店id; StudentsData=cursor.fetchall 更新缓存文件 数据={'results':学生数据,'timestamp':time.time} 使用openCACHE_文件名,“w”作为缓存: pickle.dumpdata,缓存 其他: 缓存的数据足够新鲜,请使用它 StudentsData=cached['results'] pprint.pprint学生数据 您需要手动初始化results.cache文件一次 编辑 with语法是一个上下文管理器,在Python 2.5中引入
with open(CACHE_FILENAME, 'r') as cache:
cached = pickle.load(cache)
可以重写为
cached = open(CACHE_FILENAME, 'r')
cached = pickle.load(cache)
cached.close()
编辑2
在chat中进行了长时间的讨论后,以下内容起到了作用:
import MySQLdb
import csv
import pprint
import time
import pickle
MAX_CACHE_AGE = 60*20 # 20 Minutes
CACHE_FILENAME = 'results.cache'
regen = False
try:
with open(CACHE_FILENAME, 'r') as cache:
cached = pickle.load(cache)
if(time.time() > cached['timestamp'] + MAX_CACHE_AGE):
print("Cache too old: regenerating cache")
regen = True
else:
print("Cached data is fresh enough: loading results from cache")
except IOError:
print("Error opening %s: regenerating cache" % CACHE_FILENAME)
regen = True
if(regen):
# Cache too old, run query
db = MySQLdb.connect(host="localhost", # The Host
user="username", # username
passwd="password", # password
db="dbname") # name of the data base
cursor = db.cursor()
cursor.execute("SELECT name, id, city, storeid FROM Products;")
StudentsData = cursor.fetchall()
cursor.close()
# Update cache file
data = {'results': StudentsData, 'timestamp':time.time()}
with open(CACHE_FILENAME, 'w') as cache:
pickle.dump(data, cache)
else:
# Cached data is fresh enough, use that
StudentsData = cached['results']
print StudentsData
是否缓存完全由您决定。过时的数据会成为一个问题吗?非常感谢您提供了一个很好的示例!!我相信这正是我要寻找的,唯一的问题是我得到了这个错误,openCACHE_文件名为'r'作为缓存:^SyntaxError:无效语法我应该安装一些脚本才能工作吗?谢谢你错过了那里的as吗?我得到了有和没有as的错误。我试着移除它,看看这是否能解决问题。但是它没有。你使用的是什么版本的Python?支持上下文管理器之前的版本?我以另一种模式进行了编辑,以防您使用的是Python<2.5抱歉,我没有发布这篇文章2.6.4‘python2的任何替代品??