一开始 flask的cache type是 simple,然后在生产环境 可不能这么用吧,然后开始研究用memcached,然后一直出错。出错的原因是 libmemcached的版本和pylibmc的版本不对,然后,我结局了他就好了,这里就不标明如何搭建环境了,值得提醒的是,在pip 安装包的时候一定要指定好版本。
代码如下:
config.py
(pythonenv)[xluren@test Flask-Cache_for_memcached_06]$ cat config.py import os class Config(object): DEBUG=True CACHE_TYPE = 'memcached' SECRET_KEY = "d73b04b0e696b0945283defa3eee4538" BASE_DIR = os.path.abspath(os.path.dirname(__file__)) SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(BASE_DIR, 'app.db') CACHE_MEMCACHED_SERVERS=["10.210.71.145:11211"] class MysqlConfig(Config): SQLALCHEMY_DATABASE_URI = 'mysql://hello:[email protected]:3306/sqlalchemy' class MongoDBConfig(Config): MONGOALCHEMY_DATABASE="mydb" MONGOALCHEMY_SERVER="10.210.71.145" MONGOALCHEMY_PORT=8888 POST_PER_PAGE = 3
(pythonenv)[xluren@test Flask-Cache_for_memcached_06]$ cat run.py from flask import Flask import random # import the flask extension from flask.ext.cache import Cache app = Flask(__name__) #import config setting app.config.from_object("config.Config") # register the cache instance and binds it on to your app app.cache = Cache(app) @app.route("/") @app.cache.cached(timeout=500,key_prefix="hello") # cache this view for 30 seconds def cached_view(): a=random.randint(0,100) return str(a) if __name__ == "__main__": app.run(port=5000, debug=True, host='0.0.0.0')
cache 验证的代码:
<?php $mem = new Memcache; $mem->connect("127.0.0.1", 11211); #add $mem->set('key1', 'This is first value', 0, 60); $val = $mem->get('key1'); echo "Get key1 value: " . $val ."\n"; #modify $mem->replace('key1', 'This is replace value', 0, 60); $val = $mem->get('key1'); echo "Get key1 value: " . $val . "\n"; #insert array $arr = array('aaa', 'bbb', 'ccc', 'ddd'); $mem->set('key2', $arr, 0, 60); $val2 = $mem->get('key2'); echo "Get key2 value: "; print_r($val2); echo "\n"; #delete $mem->delete('key1'); $val = $mem->get('key1'); echo "Get key1 value: " . $val . "\n"; #add $mem->set('key1', 'This is k1 value', 0, 60); $val = $mem->get('key1'); echo "Get key1 value: " . $val ."\n"; #add $mem->set('key2', 'This is k2 value', 0, 60); $val = $mem->get('key2'); echo "Get key2 value: " . $val ."\n"; #add $mem->set('key3', 'This is k3 value', 0, 60); $val = $mem->get('key3'); echo "Get key3 value: " . $val ."\n"; $items=$mem->getExtendedStats("items"); $host="127.0.0.1"; $port=11211; $items=$items["$host:$port"]['items']; print "###############"; print_r($items); print "###############"; foreach($items as $key=>$values) { $number=$key; $str=$mem->getExtendedStats ("cachedump",$number,0); $line=$str["$host:$port"]; if( is_array($line) && count($line)>0) { foreach($line as $key=>$value) { echo $key.'=>'; print_r($mem->get($key)); echo "\r\n"; } } } $mem->flush(); $val2 = $mem->get('key2'); echo "Get key2 value: "; print_r($val2); echo "\n"; $mem->close(); ?>验证的时候,页面会有直观的体现,同时,通过代码访问memcached的,得到的效果更佳真实
太爽了。