-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathviews.py
More file actions
71 lines (57 loc) · 2.31 KB
/
Copy pathviews.py
File metadata and controls
71 lines (57 loc) · 2.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
from flask import Blueprint, render_template, request, flash, redirect, url_for
from .models import Note, User
from flask_login import login_required, current_user
from . import db
import json
views = Blueprint('views', __name__)
@views.route('/', methods=['GET', 'POST'])
@login_required
def home():
if request.method == 'POST':
note = request.form.get('note')#Gets the note from the HTML
if len(note) < 1:
flash('Note is too short!', category='error')
else:
new_note = Note(data=note, user_id=current_user.id) #providing the schema for the note
db.session.add(new_note) #adding the note to the database
db.session.commit()
flash('Note added!', category='success')
return redirect(url_for('views.home'))
# Search behavior: show all notes when q is empty, otherwise show filtered results
q = request.args.get('q', '').strip()
if q:
notes = Note.query.filter(
Note.user_id == current_user.id,
Note.data.ilike(f'%{q}%')
).order_by(Note.id.desc()).all()
else:
notes = Note.query.filter_by(user_id=current_user.id).order_by(Note.id.desc()).all()
return render_template("home.html", user=current_user, notes=notes, query=q)
@views.route('/delete-note', methods=['POST'])
def delete_note():
note = json.loads(request.data) # this function expects a JSON from the INDEX.js file
noteId = note['noteId']
note = Note.query.get(noteId)
if note:
if note.user_id == current_user.id:
db.session.delete(note)
db.session.commit()
return jsonify({})
@views.route('/search')
@login_required
def search():
q = request.args.get('q', '').strip()
if not q:
flash('Please enter a keyword to search.', category='info')
return redirect(url_for('views.home'))
# case-insensitive partial match for the current user's notes
results = Note.query.filter(
Note.user_id == current_user.id,
Note.data.ilike(f'%{q}%')
).order_by(Note.id.desc()).all()
return render_template("home.html", user=current_user, notes=results, query=q)
@views.route('/clear-search')
@login_required
def clear_search():
# Redirect to home with no query parameter, showing all notes
return redirect(url_for('views.home'))