-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
312 lines (235 loc) · 9.64 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
from datetime import date
from flask import Flask, abort, render_template, redirect, url_for, flash, request
from flask_bootstrap import Bootstrap5
from flask_ckeditor import CKEditor
# from flask_gravatar import Gravatar
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, deferred
from sqlalchemy import Integer, String, Text, Column, select, ForeignKey
from functools import wraps
from werkzeug.security import generate_password_hash, check_password_hash
from os import environ
from dotenv import load_dotenv
# Import your forms from the forms.py
import forms
load_dotenv()
'''
Make sure the required packages are installed:
Open the Terminal in PyCharm (bottom left).
On Windows type:
python -m pip install -r requirements.txt
On MacOS type:
pip3 install -r requirements.txt
This will install the packages from the requirements.txt for this project.
'''
print(environ.get('FLASK_KEY'))
app = Flask(__name__)
app.config['SECRET_KEY'] = environ.get('FLASK_KEY')
ckeditor = CKEditor(app)
Bootstrap5(app)
# TODO: Configure Flask-Login
login_manager = LoginManager()
login_manager.init_app(app)
@login_manager.user_loader
def user_loader(usr_id):
return db.get_or_404(User, usr_id)
@login_manager.unauthorized_handler
def unauthorized_handler():
flash('Unauthorization first!', 'danger')
return redirect(url_for('login'))
@app.context_processor
def is_authorized():
ret = {'auth': True if current_user.is_authenticated else False}
if ret['auth']: ret['admin'] = True if current_user.id==1 else False
return ret
print(environ.get('DB_URI'))
# CREATE DATABASE
class Base(DeclarativeBase):
pass
app.config['SQLALCHEMY_DATABASE_URI'] = environ.get('DB_URI')
db = SQLAlchemy(model_class=Base)
db.init_app(app)
# TODO: Create a User table for all your registered users.
class User(db.Model, UserMixin):
__tablename__ = "Users"
id = Column("id", Integer, primary_key=True)
comments: Mapped[list['Comment']] = relationship(back_populates='user')
posts: Mapped[list['BlogPost']] = relationship(back_populates='user')
name = Column('name', String)
email = Column('email', String)
password = deferred(Column('password', String))
profile = Column('photo', String, nullable=True)
# CONFIGURE TABLES
class BlogPost(db.Model):
__tablename__ = "blog_posts"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
user_id: Mapped[int] = mapped_column(ForeignKey(User.id, ondelete='SET NULL'), nullable=True)
user: Mapped['User'] = relationship(back_populates='posts', foreign_keys=[user_id])
comments: Mapped[list['Comment']] = relationship(cascade='all, delete', passive_deletes=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: Mapped[str] = mapped_column(String(250), nullable=False)
img_url: Mapped[str] = mapped_column(String(250), nullable=False)
class Comment(db.Model):
__tablename__ = "Comment"
id: Mapped[int] = mapped_column('id', Integer, primary_key=True)
post_id: Mapped[int] = mapped_column(ForeignKey(BlogPost.id, ondelete='CASCADE'))
user_id: Mapped[int] = mapped_column(ForeignKey(User.id, ondelete='SET NULL'), nullable=True)
post: Mapped['BlogPost'] = relationship(back_populates="comments", foreign_keys=[post_id])
user: Mapped['User'] = relationship(back_populates='comments', foreign_keys=[user_id])
body: Mapped[int] = mapped_column('comment', String)
with app.app_context():
db.create_all()
# TODO: Use Werkzeug to hash the user's password when creating a new user.
@app.route('/register', methods=['post', 'get'])
def register():
reg_form = forms.RegisterForm()
if request.method == "POST":
reg_form.validate()
name = reg_form.name.data
email = reg_form.email.data
password = reg_form.passwrod.data
if db.session.execute(select(User).filter(User.email == email)).scalar_one_or_none():
flash("e-Mail already exited!", 'warning')
else:
db.session.add(User(
name = name,
email = email,
password = generate_password_hash(password=password, method='pbkdf2', salt_length=25)
))
db.session.commit()
flash("User registered successfully", 'success')
return redirect(url_for('login'))
return render_template("register.html", form=reg_form)
# TODO: Retrieve a user from the database based on their email.
@app.route('/login', methods=['post', 'get'])
def login():
login_form = forms.LoginForm()
if is_authorized()['auth']:
return redirect(url_for('home'))
if request.method == "POST":
login_form.validate()
email = login_form.email.data
password = login_form.password.data
print(email)
if user := db.session.execute(select(User).filter(User.email==email)).scalar_one_or_none():
print("we got user data")
if check_password_hash(user.password, password):
# login_user(user)
flash(f"Welcome {user.name}", 'success')
login_user(user)
return redirect(url_for('home'))
else:
flash("Wrong user credentials!", 'danger')
else:
flash(f"User did not exist!", "warning")
return render_template("login.html", form=login_form)
@app.route('/logout')
@login_required
def logout():
logout_user()
return redirect(url_for('home'))
@app.route('/')
def home():
print("home")
posts = db.session.execute(db.select(BlogPost).order_by(BlogPost.date)).scalars().all()
print("after data")
return render_template('index.html', posts=posts)
# TODO: Allow logged-in users to comment on posts
@app.route("/post/<int:post_id>", methods=['post', 'get'])
@login_required
def show_post(post_id):
comment_form = forms.CommentForm()
requested_post = db.get_or_404(BlogPost, post_id)
# comments = db.get
if request.method == 'POST':
db.session.add(Comment(
body = comment_form.comment.data,
post_id = post_id,
user_id = current_user.id
))
db.session.commit()
flash("Comment submitted successfuly.", 'success')
print(request.path)
return render_template("post.html", post=requested_post, form=comment_form)
# TODO: Use a decorator so only an admin user can create a new post
@app.route("/new-post", methods=["GET", "POST"])
def new_post():
if not is_authorized()['admin']:
flash("Access denied!", 'danger')
return redirect(url_for('home'))
form = forms.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.name,
date=date.today().strftime("%B %d, %Y"),
user_id=current_user.id
)
db.session.add(new_post)
db.session.commit()
flash("Post created successfuly!", 'success')
return redirect(url_for("home"))
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"])
def edit_post(post_id):
post = db.get_or_404(BlogPost, post_id)
edit_form = forms.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 = 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/comment/<int:id>/<int:pid>")
def delete_comment(id, pid):
if not is_authorized()['admin']:
flash('Access denied!', 'danger')
return redirect(url_for('home'))
print("deleting the comment")
db.session.delete(db.get_or_404(Comment, id))
print("lets commit")
db.session.commit()
flash("Comment deleted successfully.", 'success')
print("job done")
return redirect(url_for('show_post', post_id=pid))
@app.route("/delete/post/<int:post_id>")
@login_required
def delete_post(post_id):
print("in delte")
if not is_authorized()['admin']:
flash('Access denied!', 'danger')
return redirect(url_for('home'))
else:
to_delete = db.get_or_404(BlogPost, post_id)
db.session.delete(to_delete)
db.session.commit()
flash("Post deleted successfully.", 'success')
return redirect(url_for('home'))
@app.route("/about")
def about():
return render_template("about.html")
@app.route("/contact", methods=['post', 'get'])
def contact():
if request.method == "POST":
flash("Message sent successfuly!", 'success')
return render_template("contact.html")
if __name__ == "__main__":
app.run(debug=True, port=5008)