-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
95 lines (74 loc) · 2.79 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
from flask import Flask, render_template, request, redirect
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
import os
from dotenv import load_dotenv
load_dotenv()
app = Flask(__name__)
DATABASE_TYPE = os.environ.get('DB_TYPE')
USERNAME = os.environ.get('DB_USER')
PASSWORD = os.environ.get('DB_PASSWORD')
HOSTNAME = os.environ.get('DB_HOST')
PORT = int(os.environ.get('DB_PORT'))
DATABASE_NAME = os.environ.get('DB_NAME')
app.config['SQLALCHEMY_DATABASE_URI'] = f'{DATABASE_TYPE}://{USERNAME}:{PASSWORD}@{HOSTNAME}:{PORT}/{DATABASE_NAME}'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
class BlogPost(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
content = db.Column(db.Text, nullable=False)
author = db.Column(db.String(20), nullable=False, default="N/A")
date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
def __repr__(self):
return "Blog post " + str(self.id)
db.init_app(app)
with app.app_context():
db.create_all()
@app.route("/")
def index():
return render_template("index.html")
@app.route("/posts", methods=["GET", "POST"])
def posts():
if request.method == "POST":
post_title = request.form["title"]
post_content = request.form["content"]
post_author = request.form["author"]
new_post = BlogPost(title=post_title, content=post_content, author=post_author)
db.session.add(new_post)
db.session.commit()
return redirect("/posts")
else:
all_posts = BlogPost.query.order_by(BlogPost.date_posted).all()
return render_template("posts.html", posts=all_posts)
@app.route("/posts/delete/<id>")
def delete(id):
post = BlogPost.query.get_or_404(id)
db.session.delete(post)
db.session.commit()
return redirect("/posts")
@app.route("/posts/edit/<int:id>", methods=["GET", "POST"])
def edit(id):
post = BlogPost.query.get_or_404(id)
if request.method == "POST":
post.title = request.form["title"]
post.author = request.form["author"]
post.content = request.form["content"]
db.session.commit()
return redirect("/posts")
else:
return render_template("edit.html", post=post)
@app.route("/posts/new", methods=["GET", "POST"])
def new_post():
if request.method == "POST":
post.title = request.form["title"]
post.author = request.form["author"]
post.content = request.form["content"]
new_post = BlogPost(title=post_title, content=post_content, author=post_author)
db.session.add(new_post)
db.session.commit()
return redirect("/posts")
else:
return render_template("new_post.html")
if __name__ == "__main__":
app.run(host="0.0.0.0", port=80)