-★出爺;3 发表于 2015-8-31 09:52:28

简单示例python操作memcache

  
  项目需要python
  简单示例
  表结构


1 CREATE TABLE `slevin` (
2   `id` int(5) NOT NULL DEFAULT '0',
3   `name` char(10) DEFAULT NULL,
4   PRIMARY KEY (`id`)
5 ) ENGINE=InnoDB DEFAULT CHARSET=latin1  查看表的内容



1 mysql> select * from slevin;
2 +----+------+
3 | id | name |
4 +----+------+
5 |1 | o    |
6 |2 | h    |
7 |3 | c    |
8 |4 | d    |
9 |5 | e    |
10 |6 | f    |
11 |7 | a    |
12 |8 | b    |
13 |9 | c    |
14 | 10 | d    |
15 | 11 | e    |
16 | 12 | f    |
17 +----+------+
18 12 rows in set (0.00 sec)   以下是python操作memcache的脚本



1 importMySQLdb, memcache, hashlib
2 import MySQLdb.cursors
3 #建立一个简单hash算法函数
4 def hash(obj):
5   m=hashlib.md5()
6   m.update(obj)
7   key=m.hexdigest()
8   return key
9 #返回字典式的元组(cursorclass = MySQLdb.cursors.DictCursor)
10 conn = MySQLdb.connect (host = "192.168.1.254",user = "root",passwd = "000000",db = "test",cursorclass = MySQLdb.cursors.DictCursor)                           
11 mc = memcache.Client(['192.168.1.254:11211'],debug=0)
12 #cursor = conn.cursor ()
13 two=conn.cursor ()
14 two.execute ("select * from slevin")
15 row=two.fetchall()
16 #mc.flush_all()
17 if not mc.get(hash("slevin2")):
18   for i in row:
19         #用HASH(表名+id值)做为KEY,把一行的记录存储到一个key里面
20         tabname='slevin'
21         tabname=tabname+str(i.values())
22         mc.add(hash(tabname),i)
23         #print mc.get(hash(tabname))
24 else:
25   value=mc.get(hash("slevin2"))
26   for key in value.keys():
27         print "%s is %s" %(key,value)
28 mc.disconnect_all()
29 cursor.close ()
30 conn.close ()
页: [1]
查看完整版本: 简单示例python操作memcache