如何保存json文件中的更改

时间:2016-12-12 22:59:50

标签: python json io

我有实现删除方法的问题。删除*方法应删除所有注释。示例: Note.objects.filter(board ='正在进行中')。delete() - 应该删除所有笔记和#34;正在进行的#34;。对我来说最大的问题是保存json文件中的更改。 问题是:当我用删除方法删除笔记时,如何保持json文件中的更改?

   def delete(self):
   all_notes = [note for note in Note.objects.all()] # try to delete note with index 1
   for note in all_notes:
        if note.id == 1:
           all_notes.pop(0)
   for note in all_notes:
       print note
       note.save()

这是代码:

# coding: utf-8
from __future__ import unicode_literals
from shutil import copyfile
import json
import os

DATABASE = 'notes_data/notes.json'
BOARDS = ['to do', 'in progress', 'done']


class NotesManagerMixin(object):

    def count(self):
        return len(self.notes)

    def filter(self, *args, **kwargs):
        result = self.notes
        for key, value in kwargs.iteritems():
            result = [
                note for note in result
                if getattr(note, key, None) == value or 
                note.message.startswith(value) or 
                note.message.endswith(value)
            ]
        return NotesQueryset(result)

    def get(self, *args, **kwargs):
        notes = self.filter(**kwargs)
        if notes.count() == 0:
            raise IndexError('Note doesn\'t exist')
        elif notes.count() == 1:
            return notes[0]
        else:
            raise IndexError('Returned more then one entry')

    def first(self):
        return self.notes[0]

    def last(self):
        return self.notes[-1]


class NotesQueryset(NotesManagerMixin):

    def __init__(self, notes):
        self.notes = [note for note in notes]

    def update(self, *args, **kwargs):
        notes = self.notes
        for note in notes:
            if 'board' in kwargs:
                note.board = kwargs['board']
                note.save()
            if 'message' in kwargs:
                note.message == kwargs['message']
                note.save()



    def delete(self):
        all_notes = [note for note in Note.objects.all()] # try to delete note with index 1
        for note in all_notes:
            if note.id == 1:
                all_notes.pop(0)
        for note in all_notes:
            print note
            note.save()



    def __getitem__(self, idx):
        return self.notes[idx]

    def __str__(self):
        return str(self.notes)

    def __repr__(self):
        return self.__str__()


class NotesManager(NotesManagerMixin):

    def __init__(self):
        self.notes = []

    def __iter__(self):
        return self.next()

    def __generate_id(self):
        """
            Funkcja pomocnicza do pobrania pewnej wolnej wartości indexu.
        """
        try:
            return max(note.id for note in self.notes) + 1
        except ValueError:
            return 1

    def all(self):
        return NotesQueryset(self.notes)

    def add(self, idx, board, message):
        self.notes.append(Note(idx=idx, board=board, message=message))

    def create(self, board, message):
        note = Note(
            idx=self.__generate_id(),
            board=board,
            message=message
        )
        note.clean()

        self.notes.append(note)
        note.save()

        return note

    def next(self):
        for note in self.notes:
            yield note

    def to_dict(self):
        return [note.to_dict() for note in self.notes]


class Note(object):
    objects = NotesManager()

    def __init__(self, idx, board, message):
        self.id = idx
        self.board = board
        self.message = message

    def __str__(self):
        return 'ID: {}, Board: {}, Message: {}'.format(
            self.id,
            self.board,
            self.message
        )

    def __repr__(self):
        return self.__str__()

    def clean(self):
        if not self.message:
            raise ValueError('Message is required')

        if self.board not in BOARDS:
            raise ValueError('Board "{}" doesn\'t exists'.format(self.board))

        if type(self.id) != int:
            raise ValueError('Note id "{}" is invalid'.format(self.id))

    def save(self):
        for key, note in enumerate(self.objects):
            if note.id == self.id:
                self.objects.notes[key] = self
                break

        with open(DATABASE, 'w') as database_file:
            json.dump(self.objects.to_dict(), database_file, indent=4)

        return True

    def delete(self):
        # delete just one note
        pass

    def to_dict(self):
        return {
            'id': self.id,
            'message': self.message,
            'board': self.board
        }


def load_initial_data():

    with open(DATABASE, 'r') as database_file:
        json_data = json.load(database_file, encoding='utf-8')

    for item in json_data:
        Note.objects.add(
            idx=item['id'],
            board=item['board'],
            message=item['message'],
        )


load_initial_data()

1 个答案:

答案 0 :(得分:0)

通常,修改文件的方法是用修改后的数据覆盖整个文件。因此,一旦修改了内存数据,您的save方法就应该已经按照您想要的那样做了。

这里的问题是delete没有修改正在保存的Note.objects数据,它正在修改由列表推导[note for note in Note.objects.all()]创建的临时数组。因此,当您致电save时,您会再次保存原始数据。