尝试在加载此文件时实施缓存 [英] Trying to implement a cache on load of this file

查看:94
本文介绍了尝试在加载此文件时实施缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

缓存的初始大小为20个元素,一旦达到其限制,要添加任何新元素,它将删除最近访问最少的元素.在关闭时,它应该将缓存的数据存储回文件中.数据应根据缓存策略存储在缓存中.提供缓存CRUD的选项.测试数据集:学生记录.

The cache would have an initial size of 20 elements and upon reaching its limit, to add any new element it would remove the least recently accessed element. On shutdown it should store the cached data back to the file. The data should be stored in the cache according to a caching strategy. Provide options for cache CRUD. Testing Data set : records of student.

import json
from collections import OrderedDict
import time
import os

if os.path.exists("qwerty.json"):
    record = json.load(open("qwerty.json", "r"), object_pairs_hook=OrderedDict)
else:
    record = OrderedDict({})

fo = open("foo.txt", "wb")

x = list(record.items())[:20]; x2 = sorted(x, key=lambda k: k[1]['time'], reverse=True)
print(x2)

command = ""
while command != 'exit':
    command = input('Enter a command(options: create,read,save): ')
    if command == "create":
        name = input('Enter name of the Student:')
        p = input('Student ID: ')
        a = input('Class: ')
        n = input('Marks: ')
        time = time.time()

        record[name] = {'Student ID:': p, 'Class:': a, 'Marks': n, 'time': time }

    elif command == 'read':
        z = json.load(open("qwerty.json", "r"), object_pairs_hook=OrderedDict)
        print(z)

    elif command == 'save':
        json.dump(record, open('qwerty.json', "w"))

fo.close()

推荐答案

实际上,您可以结合使用jsoncollections.OrderedDict来维护单个文件的顺序.

You can actually maintain order with a single file, using a combination of json and collections.OrderedDict.

您的初始设置如下:

from collections import OrderedDict
phone_book = OrderedDict({})

创建时,将元素添加到有序dict中,然后将其转储为JSON.键的顺序被保留.在像上面一样声明phone_book之后,create的其余代码保持不变.请注意,在写入文件时,不会将其关闭,因此以后将无法读取其内容.应该将其替换为:

When creating, add elements into an ordered dict and then dump it as JSON. The order of keys is preserved. After you declared phone_book like above, the rest of the code for create remains the same. Note that when you write to the file, you don't close it, so you can't read the contents later. This should be replaced with something like:

import os

if os.path.exists("qwerty.json")
    phone_book = json.load(open("qwerty.json", "r"), object_pairs_hook=OrderedDict)
else:
    phone_book = OrderedDict({})

command = ""
while command != 'exit':
    command = input('Enter a command(options: create,read,save): ')
    if command == "create":
        ...

    elif command == 'read':
        ...

    elif command == 'save':
        json.dump(phone_book, open('qwerty.json', "w"))

要阅读,您必须进行一些更改:

For reading, you'll have to make some changes:

elif command == 'read':
    z = json.load(open("C:\\Users\\qwerty.txt", "r"), object_pairs_hook=OrderedDict)
    ...

这将按存储密钥的顺序加载字典.现在,您可以调用list(z.items())[-20:]以仅获取最后20个项目.另外,在读取特定键时,可以通过删除并重新创建它来更新其上次读取时间":

This loads the dict in the order the keys were stored. You can now call list(z.items())[-20:] to get only the last 20 items. Also, when reading a particular key, you update its "last-read-time" by deleting and recreating it:

import copy
key = ...
temp = copy.copy(z[key])
del z[key]
z[key] = temp

这将更新dict中key的位置.这应该足以让您自己实现其余的内容.

This will update the position of key in the dict. This should be enough for you to implement the rest yourself.

这篇关于尝试在加载此文件时实施缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆