Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
368 lines (289 loc) · 10.7 KB
/
Copy pathmain.py
File metadata and controls
368 lines (289 loc) · 10.7 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
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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
from datetime import date, datetime
from flask import (
Flask,
abort,
render_template,
redirect,
url_for,
flash,
request,
send_from_directory,
)
import bleach
from flask_bootstrap import Bootstrap5
from flask_login import (
UserMixin,
login_user,
LoginManager,
current_user,
logout_user,
login_required,
)
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import relationship, DeclarativeBase, Mapped, mapped_column
from sqlalchemy import Integer, String, Text
from functools import wraps
from werkzeug.security import generate_password_hash, check_password_hash
from forms import RegisterForm, LoginForm, CommentForm
from forms import CreatePostForm
import os
ALLOWED_HTML_TAGS = [
"p", "br", "strong", "em", "u", "s", "a", "ul", "ol", "li",
"h1", "h2", "h3", "blockquote", "pre", "code",
]
ALLOWED_HTML_ATTRS = {"a": ["href", "title", "target", "rel"]}
def sanitize_html(content):
if not content:
return ""
return bleach.clean(
content,
tags=ALLOWED_HTML_TAGS,
attributes=ALLOWED_HTML_ATTRS,
strip=True,
)
app = Flask(__name__)
app.config["SECRET_KEY"] = os.getenv("SECRET_KEY")
Bootstrap5(app)
# TODO: Configure Flask-Login
login_manager = LoginManager()
login_manager.init_app(app=app)
login_manager.login_view = "login"
class Base(DeclarativeBase):
pass
# Gravatar helper — generate URL from email
import hashlib
def gravatar_url(email, size=100, default='retro', rating='g'):
"""Generate a Gravatar URL for the given email address."""
safe_email = str(email or "").lower().strip().encode('utf-8')
email_hash = hashlib.md5(safe_email).hexdigest()
return f"https://www.gravatar.com/avatar/{email_hash}?s={size}&d={default}&r={rating}"
# CREATE DATABASE
# Fetch variables
app.config["SQLALCHEMY_DATABASE_URI"] = os.getenv("DB_URl")
app.config["SQLALCHEMY_ENGINE_OPTIONS"] = {
"pool_pre_ping": True,
"pool_recycle": 280
}
db = SQLAlchemy(model_class=Base)
db.init_app(app)
# CONFIGURE TABLES
class Users(db.Model, UserMixin):
__tablename__ = "users"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
name: Mapped[str] = mapped_column(String(50), nullable=False)
email: Mapped[str] = mapped_column(
String(250), nullable=False, unique=True)
password: Mapped[str] = mapped_column(String(300), nullable=False)
is_author: Mapped[int] = mapped_column(Integer, default=0)
is_admin: Mapped[int] = mapped_column(Integer, default=0)
# ralations
posts = db.relationship("BlogPosts", back_populates="author")
comments = db.relationship("Comments", back_populates="author")
class BlogPosts(db.Model):
__tablename__ = "blog_posts"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
title: Mapped[str] = mapped_column(
String(250), unique=True, nullable=False)
subtitle: Mapped[str] = mapped_column(String(250), nullable=False)
date: Mapped[str] = mapped_column(String(250), nullable=False)
body: Mapped[str] = mapped_column(Text, nullable=False)
author_id: Mapped[int] = mapped_column(Integer, db.ForeignKey("users.id"))
img_url: Mapped[str] = mapped_column(String(250), nullable=False)
views: Mapped[int] = mapped_column(Integer, default=0)
author = db.relationship("Users", back_populates="posts")
comments = db.relationship("Comments", back_populates="post")
class Comments(db.Model):
__tablename__ = "comments"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
text: Mapped[str] = mapped_column(String(300), nullable=False)
author_id: Mapped[int] = mapped_column(Integer, db.ForeignKey("users.id"))
post_id: Mapped[int] = mapped_column(
Integer, db.ForeignKey("blog_posts.id"))
# relation ship
post = db.relationship("BlogPosts", back_populates="comments")
author = db.relationship("Users", back_populates="comments")
# TODO: Create a User table for all your registered users.
def ensure_author():
author = db.session.execute(db.select(Users).limit(1)).scalar_one_or_none()
if author:
return author
author = Users(
name="Sayed Mohammad Hashimi",
email="admin@hashimi.blog",
password=generate_password_hash(
os.getenv("DEMO_ADMIN_PASSWORD", "ChangeMe123!"),
salt_length=8,
),
)
db.session.add(author)
db.session.commit()
return author
# with app.app_context():
# db.create_all()
@app.context_processor
def inject_globals():
return {"now_year": datetime.now().year, "gravatar": gravatar_url}
@app.route('/sitemap.xml')
def sitemap():
return send_from_directory('static', 'sitemap.xml')
@app.route('/favicon.ico')
def favicon():
return send_from_directory(os.path.join(app.root_path, 'static', 'assets'),
'favicon.ico', mimetype='image/vnd.microsoft.icon')
# TODO: Use Werkzeug to hash the user's password when creating a new user.
@app.teardown_appcontext
def cleanup(exception=None):
db.session.remove()
@app.route("/register", methods=["GET", "POST"])
def register():
form = RegisterForm()
if request.method == "POST":
if form.validate_on_submit():
with app.app_context():
user = Users.query.filter_by(email=form.email.data).first()
if not user:
user = Users(
email=form.email.data.lower(),
password=generate_password_hash(
f"{form.password.data}", salt_length=8
),
name=form.name.data,
)
db.session.add(user)
db.session.commit()
login_user(user)
return redirect(url_for("get_all_posts"))
else:
flash("This email has allready an acount")
return redirect(url_for("login"))
return render_template("register.html", form=form)
# TODO: Retrieve a user from the database based on their email.
@app.route("/login", methods=["GET", "POST"])
def login():
form = LoginForm()
if request.method == "POST":
if form.validate_on_submit():
user = db.session.execute(
db.select(Users).where(Users.email == form.email.data)
).scalar()
if user:
if check_password_hash(user.password, form.password.data):
login_user(user)
return redirect(url_for("get_all_posts"))
else:
flash("The email or password is incorrect!")
else:
flash("The email or password is incorrect!")
return render_template("login.html", form=form)
@app.route("/logout")
def logout():
logout_user()
return redirect(url_for("get_all_posts"))
@app.route("/")
def get_all_posts():
result = db.session.execute(
db.select(BlogPosts).order_by(BlogPosts.id.desc())
)
posts = result.scalars().all()
return render_template("index.html", all_posts=posts)
# TODO: Allow logged-in users to comment on posts
@app.route("/post/<int:post_id>", methods=["POST", "GET"])
def show_post(post_id):
make_comment = CommentForm()
all_comments = db.session.execute(
db.select(Comments).where(Comments.post_id == post_id)).scalars().all()
requested_post = db.get_or_404(BlogPosts, post_id)
requested_post.views = (requested_post.views or 0) + 1
db.session.commit()
return render_template("post.html", post=requested_post, comment_form=make_comment, all_comments=all_comments, gravatar=gravatar_url)
# TODO: Use a decorator so only an admin user can create a new post
def only_admin(func):
@wraps(func)
def wrapper(*args, **kwargs):
if not current_user.is_authenticated:
return redirect(url_for("login"))
if current_user.is_admin == 1:
return func(*args, **kwargs)
return abort(403)
return wrapper
def only_author(func):
@wraps(func)
def wrapper(*args, **kwargs):
if not current_user.is_authenticated:
return redirect(url_for("login"))
if current_user.is_author == 1:
return func(*args, **kwargs)
return abort(403)
return wrapper
@app.route("/new-post", methods=["GET", "POST"])
@only_author
def add_new_post():
form = CreatePostForm()
if form.validate_on_submit():
new_post = BlogPosts(
title=form.title.data,
subtitle=form.subtitle.data,
body=sanitize_html(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)
# TODO: Use a decorator so only an admin user can edit a post
@app.route("/edit-post/<int:post_id>", methods=["GET", "POST"])
@only_admin
def edit_post(post_id):
post = db.get_or_404(BlogPosts, post_id)
edit_form = CreatePostForm(
title=post.title,
subtitle=post.subtitle,
img_url=post.img_url,
author=post.author,
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 = sanitize_html(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)
# TODO: Use a decorator so only an admin user can delete a post
@app.route("/delete/<int:post_id>")
@only_admin
def delete_post(post_id):
post_to_delete = db.get_or_404(BlogPosts, post_id)
db.session.delete(post_to_delete)
db.session.commit()
return redirect(url_for("get_all_posts"))
@app.route('/comment', methods=['POST'])
@login_required
def save_comment():
post_id = request.args.get("p")
form = CommentForm()
if form.validate_on_submit():
db.session.add(
Comments(
text=sanitize_html(form.comment_text.data),
author_id=current_user.id,
post_id=post_id,
)
)
db.session.commit()
return redirect(url_for('show_post', post_id=post_id))
@app.route("/about")
def about():
return render_template("about.html")
@app.route("/contact")
def contact():
return render_template("contact.html")
@login_manager.user_loader
def load_user(id):
return Users.query.filter_by(id=int(id)).first()
if __name__ == "__main__":
app.run(port=5002)