从内存读取更新数据

最近内存越来越大,信息,尽量存在内存中 ,可以加快速度,现在先写一个 大体 思路。很多细节。待更新。

先从网上,看下了sqlite 的使用 。很轻量的数据库。拿来做测试,也很方便查看。

思路 就是 :

从内存中拿,如果内存没有就从数据库中取。

每次更新数据库的时候 更新一下内存中的数。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sqlite3

cx = sqlite3.connect("E:/sqlite/test.db")
cu = cx.cursor()


def data_from_sql(sql_id):
    sql = "select * from catalog where id = %s" % sql_id
    # print sql
    cu.execute(sql)
    return cu.fetchall()[0]

def updata_sql(id, touple_update):
    sql = "update catalog set name='898989 'where id = 0"
    cu.execute(sql)
    cx.commit()

def mem_func(func_test):
    mem = {}
    def func(id, func_table_get, method='get', touple_update=None, func_table_update=None):
        if method == 'get':
            if id not in mem:
                mem[id] = func_table_get(id)
            print func_test.__name__
        elif method == 'update':
            func_table_update(id, touple_update)
            mem[id] = func_table_get(id)
        # return func_test(id, func_table_get, method='get', touple_update=None, func_table_update=None)
        return mem
    return func

@mem_func
def get_or_update(id, func_table, method='get', touple_update=None, func_table_update=None):
    pass



print get_or_update(0, data_from_sql, method='get', touple_update=None, func_table_update=None)
print get_or_update(1, data_from_sql)

print get_or_update(0, data_from_sql,'update', (1, 2), updata_sql)
print get_or_update(2, data_from_sql)
print get_or_update(0, data_from_sql)

posted on 2013-07-02 18:16  tiger4py  阅读(239)  评论(0)    收藏  举报

导航