app.py 1.5 KB
Newer Older
6
62cacc1fcf7e861cf6c3b88a 已提交
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
from flask import Flask, render_template, request, redirect
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///notes.db'
db = SQLAlchemy(app)

class Note(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100))
    content = db.Column(db.Text)

@app.route('/')
def index():
    q = request.args.get('q') # 获取搜索条件
    if q:
        notes = Note.query.filter(Note.title.contains(q) | Note.content.contains(q))
    else:
        notes = Note.query.all()
    return render_template('index.html',q=q, notes=notes) 

@app.route('/add', methods=['GET', 'POST']) 
def add():
    if request.method == 'POST':
        title = request.form['title']
        content = request.form['content'] 
        note = Note(title=title, content=content)
        db.session.add(note)
        db.session.commit()
        return redirect('/')
    return render_template('add.html')

@app.route('/edit/<int:id>', methods=['GET', 'POST'])
def edit(id):
    note = Note.query.get(id)
    if request.method == 'POST':
        note.title = request.form['title']
        note.content = request.form['content'] 
        db.session.commit()
        return redirect('/')
    return render_template('edit.html', note=note)  

@app.route('/delete/<int:id>')
def delete(id):
    note = Note.query.get(id)
    db.session.delete(note)
    db.session.commit()
    return redirect('/')

if __name__ == '__main__':
    with app.app_context():
        db.create_all()
    app.run(port=5001,debug=True)