def edit(note_id): note = Note.query.filter_by(id=note_id).first() if isinstance(note, NoneType) or current_user.id != note.id_user: flash('This note does not exists !', 'warning') return redirect(url_for('index')) form = NoteForm(obj=note) if form.validate_on_submit(): edit_date = datetime.now() # update note in postgresql note.title = form.title.data note.content = form.content.data note.is_public = form.is_public.data note.edit_date = edit_date db.session.commit() # update note in redis redis_client.hmset( note_id, { 'title': form.title.data, 'content': form.content.data, 'is_public': str(form.is_public.data), 'edit_date': str(edit_date) }) # remove note id from list and re-add it at the start redis_client.lrem(f'{current_user.id}:notes_id', 0, str(note.id)) redis_client.lpush(f'{current_user.id}:notes_id', note.id) flash('Your note has been updated !', 'success') return redirect(url_for('index')) return render_template('note_form.html', title='Update a note', form=form)
def index(): notes = None if current_user.is_authenticated: if not redis_client.exists(f'{current_user.id}:notes_id'): notes = current_user.notes.order_by(Note.edit_date.desc()) if notes.count() != 0: for note in notes: note_dict = NoteConverter.note_to_dict(note) redis_client.lpush(f'{current_user.id}:notes_id', note_dict['id']) redis_client.hmset(note_dict['id'], note_dict) flash('Your notes where loaded from postgresql !', 'info') else: notes = None else: notes = [] count = 0 while count < redis_client.llen(f'{current_user.id}:notes_id'): note_id = redis_client.lindex(f'{current_user.id}:notes_id', count) notes.append( NoteConverter.dict_to_note(redis_client.hgetall(note_id))) count += 1 flash('Your notes where loaded from redis !', 'info') return render_template("index.html", title='Your notes', notes=notes)
def new(): form = NoteForm() if form.validate_on_submit(): note = Note(title=form.title.data, content=form.content.data, creation_date=datetime.now(), edit_date=datetime.now(), author=current_user, is_public=form.is_public.data, uuid=uuid.uuid4()) # insert into postgresql db.session.add(note) db.session.flush() # get id of inserted note db.session.refresh(note) db.session.commit() # insert into redis redis_client.lpush('notes_id', note.id) redis_client.hmset(note.id, NoteConverter.note_to_dict(note)) flash('Your note has been created !', 'success') return redirect(url_for('index')) return render_template('note_form.html', title='New note', form=form)