-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
324 lines (257 loc) · 10.2 KB
/
main.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
import os
import smtplib
from datetime import date
from flask import Flask, render_template, request, url_for, redirect, flash, send_from_directory, abort
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin, login_user, LoginManager, login_required, current_user, logout_user
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import relationship
from flask_ckeditor import CKEditor
from flask_gravatar import Gravatar
from flask_mail import Message, Mail
from functools import wraps
from forms import CreatePostForm, RegisterForm, LoginForm, CommentForm
# load_dotenv(override=True)
MY_EMAIL = os.environ.get("MY_EMAIL")
MY_PASSWORD = os.environ.get("MY_PASSWORD")
ADMINS = [MY_EMAIL]
app = Flask(__name__)
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY')
app.config.update(dict(
DEBUG=True,
MAIL_SERVER='smtp.gmail.com',
MAIL_PORT=587,
MAIL_USE_TLS=True,
MAIL_USE_SSL=False,
MAIL_USERNAME=MY_EMAIL,
MAIL_PASSWORD=MY_PASSWORD,
))
mail = Mail(app)
ckeditor = CKEditor(app)
Bootstrap(app)
gravatar = Gravatar(app,
size=100,
rating='g',
default='retro',
force_default=False,
force_lower=False,
use_ssl=False,
base_url=None)
# CONNECT TO DB
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get("DATABASE_URL") # 'sqlite:///blog.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
login_manager = LoginManager()
login_manager.init_app(app)
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
# CONFIGURE TABLE
class User(UserMixin, db.Model):
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(100), unique=True)
password = db.Column(db.String(100))
name = db.Column(db.String(100))
# This will act like a list of BlogPost objects attached to each User.
# The "author" refers to the author property in the BlogPost class.
posts = relationship("BlogPost", back_populates="author")
comments = relationship("Comment", back_populates="comment_author")
class BlogPost(db.Model):
__tablename__ = "blog_posts"
id = db.Column(db.Integer, primary_key=True)
# Create Foreign Key, "users.id" the users refers to the tablename of User.
author_id = db.Column(db.Integer, db.ForeignKey("users.id"))
# Create reference to the User object, the "posts" refers to the posts property in the User class.
author = relationship("User", back_populates="posts")
title = db.Column(db.String(250), unique=True, nullable=False)
subtitle = db.Column(db.String(250), nullable=False)
date = db.Column(db.String(250), nullable=False)
body = db.Column(db.Text, nullable=False)
img_url = db.Column(db.String(250), nullable=False)
comments = relationship("Comment", back_populates="parent_post")
class Comment(db.Model):
__tablename__ = "comments"
id = db.Column(db.Integer, primary_key=True)
post_id = db.Column(db.Integer, db.ForeignKey("blog_posts.id"))
# `users.id` The `users` refers to the table name of the Users class.
# `comments` refers to the `comments` properties in the User and BlogPost classes.
author_id = db.Column(db.Integer, db.ForeignKey("users.id"))
parent_post = relationship("BlogPost", back_populates="comments")
comment_author = relationship("User", back_populates="comments")
text = db.Column(db.Text, nullable=False)
# Create all the tables in the database
db.create_all()
# Create admin-only decorator
def admin_only(f):
@wraps(f)
def decorated_function(*args, **kwargs):
# If id is not 1 then return abort with 403 error
if current_user.id != 1:
return abort(403)
# Otherwise continue with the route function
return f(*args, **kwargs)
return decorated_function
# Everytime you call render_template(), you pass the current_user over to the template.
# current_user.is_authenticated will be True if they are logged in/authenticated after registering.
# You can check for this is header.html
# RENDER HOME PAGE USING DB
@app.route('/')
def get_all_posts():
posts = BlogPost.query.all()
return render_template("index.html", all_posts=posts, current_user=current_user)
# Register new users into the User database
@app.route("/register", methods=["GET", "POST"])
def register():
form = RegisterForm()
if form.validate_on_submit():
# If user's email already exists
if User.query.filter_by(email=form.email.data).first():
# Send flash message
flash("You've already signed up with that email, log in instead!")
# Redirect to /login route
return redirect(url_for("login"))
hash_and_salted_password = generate_password_hash(
form.password.data,
method="pbkdf2:sha256",
salt_length=8
)
new_user = User(
email=form.email.data,
name=form.name.data,
password=hash_and_salted_password,
)
db.session.add(new_user)
db.session.commit()
# This line will authenticae the user with Flask-Login
login_user(new_user)
return redirect(url_for("get_all_posts"))
return render_template("register.html", form=form, current_user=current_user)
@app.route("/login", methods=["GET", "POST"])
def login():
form = LoginForm()
if form.validate_on_submit():
email = form.email.data
password = form.password.data
user = User.query.filter_by(email=email).first()
# Email doesn't exist
if not user:
flash("That email does not exist, please try again.")
return redirect(url_for("login"))
# Password incorrect
elif not check_password_hash(user.password, password):
flash("Password incorrect, please try again.")
return redirect(url_for("login"))
else:
login_user(user)
return redirect(url_for("get_all_posts"))
return render_template("login.html", form=form, current_user=current_user)
# RENDER POST USING DB
@app.route("/post/<int:post_id>", methods=["GET", "POST"])
def show_post(post_id):
form = CommentForm()
requested_post = BlogPost.query.get(post_id)
if form.validate_on_submit():
if not current_user.is_authenticated:
flash('You need to login or register to comment.')
return redirect(url_for("login"))
new_comment = Comment(
text=form.comment_text.data,
comment_author=current_user,
parent_post=requested_post
)
db.session.add(new_comment)
db.session.commit()
return render_template("post.html", post=requested_post, form=form, current_user=current_user)
# EDIT POST
@app.route("/edit-post/<int:post_id>", methods=["GET", "POST"])
@login_required
def edit_post(post_id):
post = BlogPost.query.get(post_id)
edit_form = CreatePostForm(
title=post.title,
subtitle=post.subtitle,
img_url=post.img_url,
author=current_user,
body=post.body
)
if edit_form.validate_on_submit():
post.title = edit_form.title.data
post.subtitle = edit_form.subtitle.data
post.img_url = edit_form.img_url.data
post.author = current_user
post.body = edit_form.body.data
db.session.commit()
return redirect(url_for("show_post", post_id=post.id))
return render_template("make-post.html", form=edit_form, is_edit=True, current_user=current_user)
@app.route("/new-post", methods=["GET", "POST"])
@admin_only
def add_new_post():
form = CreatePostForm()
if form.validate_on_submit():
new_post = BlogPost(
title=form.title.data,
subtitle=form.subtitle.data,
body=form.body.data,
img_url=form.img_url.data,
author=current_user,
date=date.today().strftime("%B %d, %Y")
)
db.session.add(new_post)
db.session.commit()
return redirect(url_for("get_all_posts"))
return render_template("make-post.html", form=form, current_user=current_user)
@app.route("/delete/<int:post_id>")
@admin_only
def delete_post(post_id):
post_to_delete = BlogPost.query.get(post_id)
db.session.delete(post_to_delete)
db.session.commit()
return redirect(url_for("get_all_posts"))
@app.route("/delete_comment/<int:post_id>/<int:comment_id>")
@admin_only
def delete_comment(post_id, comment_id):
comment_to_delete = Comment.query.get(comment_id)
db.session.delete(comment_to_delete)
db.session.commit()
form = CommentForm()
requested_post = BlogPost.query.get(post_id)
return render_template("post.html", post=requested_post, form=form, current_user=current_user)
@app.route("/resources")
@admin_only
def collabera_training_notes():
return render_template("linux-git-sql.html")
@app.route("/logout")
def logout():
logout_user()
return redirect(url_for("get_all_posts"))
@app.route("/about")
def about():
return render_template("about.html", current_user=current_user)
@app.route("/contact", methods=["GET", "POST"])
@login_required
def contact():
if request.method == "POST":
data = request.form
name = data["name"]
email_ = data["email"]
phone = data["phone"]
message = data["message"]
send_email(name, email_, phone, message)
flash('Successfully sent your message.')
return redirect(url_for('get_all_posts'))
return render_template("contact.html", current_user=current_user)
def send_email(name, eml, phone, message):
msg = Message("New Message", sender=ADMINS[0], recipients=ADMINS)
msg.body = f"Name: {name}\nEmail: {eml}\nPhone: {phone}\nMessage: {message}"
# msg.html = '<b>HTML</b> body'
with app.app_context():
mail.send(msg)
# with smtplib.SMTP("smtp.gmail.com", port=587) as connection:
# connection.starttls()
# connection.login(MY_EMAIL, MY_PASSWORD)
# connection.sendmail(MY_EMAIL, "[email protected]", email_message)
if __name__ == "__main__":
app.run()
# app.run(host='127.0.0.1', port=5000, debug=True)