-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
79 lines (64 loc) · 2.36 KB
/
app.py
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
72
73
74
75
76
77
78
79
from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
app = Flask(__name__)
# Database
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///blogposts.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
# Model
class blogpost(db.Model):
id = db.Column(db.Integer, primary_key=True)
blog_title = db.Column(db.String(100), nullable=False)
blog_subtitle = db.Column(db.String(50))
blog_content = db.Column(db.Text, nullable=False)
date_created = db.Column(db.DateTime, default=datetime.utcnow)
with app.app_context():
db.create_all()
def __repr__(self):
return 'Blog post ' + str(self.id)
# Routes
@app.route('/')
def index():
all_blogs = blogpost.query.order_by(blogpost.date_created.desc()).all()
return render_template('index.html', blogs=all_blogs)
@app.route('/search', methods=['GET', 'POST'])
def search():
if request.method == 'POST':
search = request.form['search']
search = "%{}%".format(search)
results = blogpost.query.filter(blogpost.blog_title.like(search)).all()
return render_template('search.html', results=results)
return redirect(url_for('index'))
@app.route('/<int:id>')
def blog(id):
blog = blogpost.query.filter_by(id=id).one()
return render_template('blog.html', blog=blog)
@app.route('/add')
def add():
return render_template('add.html')
@app.route('/add_blog', methods=['POST'])
def add_blog():
if request.method == 'POST':
title = request.form['blog_title']
subtitle = request.form['blog_subtitle']
content = request.form['blog_content']
new_blog = blogpost(blog_title=title, blog_subtitle=subtitle, blog_content=content, date_created=datetime.now())
db.session.add(new_blog)
db.session.commit()
return redirect(url_for('index'))
@app.route('/admin')
def admin():
all_blogs = blogpost.query.order_by(blogpost.date_created.desc()).all()
return render_template('admin.html', blogs=all_blogs)
@app.route('/delete/<int:id>')
def delete(id):
blog = blogpost.query.filter_by(id=id).one()
db.session.delete(blog)
db.session.commit()
return redirect(url_for('admin'))
@app.route('/about')
def about():
return render_template('about.html')
if __name__ == '__main__':
app.run(debug=True)