-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
420 lines (338 loc) · 14.4 KB
/
main.py
File metadata and controls
420 lines (338 loc) · 14.4 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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
from flask import Flask, render_template,flash,request,url_for,redirect
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import MetaData
from flask_migrate import Migrate
from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin, login_user, login_required, LoginManager, logout_user, current_user
from flask_ckeditor import CKEditor
from werkzeug.utils import secure_filename
import os
import uuid as uuid
from forms import *
from flask import jsonify
current_dir = os.path.abspath(os.path.dirname(__file__))
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///'+ os.path.join(current_dir,"BlogApp.db")
app.config['SECRET_KEY'] = 'this key is super dooper se bhi Uper VaLa SecRET'
UPLOAD_FOLDER = os.path.join(current_dir,"static/images")
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
ckeditor = CKEditor(app)
####################################################### METADATA #####################################################################
metadata = MetaData(
naming_convention={
"ix": 'ix_%(column_0_label)s',
"uq": "uq_%(table_name)s_%(column_0_name)s",
"ck": "ck_%(table_name)s_%(constraint_name)s",
"fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
"pk": "pk_%(table_name)s"
}
)
db = SQLAlchemy(metadata=metadata)
db.init_app(app)
app.app_context().push()
migrate = Migrate(app , db)
#Login Manager Stuff
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
@login_manager.user_loader
def load_user(user_id):
return Users.query.get(int(user_id))
#JSON thing
@app.route('/date')
def date():
datet = datetime.utcnow()
return {"Date": datet}
#Posts Model
class Posts(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(1000),nullable=False)
content = db.Column(db.Text,nullable=False)
#author = db.Column(db.String(255))
date_posted = db.Column(db.DateTime,default = datetime.utcnow())
slug = db.Column(db.String(255))
hidden = db.Column(db.Boolean, default=False)
poster_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete = "CASCADE"), nullable=False)
comments = db.relationship('Comment', backref ='post', passive_deletes = True)
likes = db.relationship('Likes', backref ='post', passive_deletes = True)
def like(self, user):
if not self.is_liked_by(user):
like = Likes(user=user, post=self)
db.session.add(like)
db.session.commit()
def unlike(self, user):
like = Likes.query.filter_by(user=user, post=self).first()
if like:
db.session.delete(like)
db.session.commit()
def is_liked_by(self, user):
return Likes.query.filter_by(user=user, post=self).count() > 0
#Test Model (Can be used as users model with few changes)
#Now it is Users model
class Users(db.Model,UserMixin):
id = db.Column(db.Integer, primary_key = True)
username = db.Column(db.String(32),nullable=False,unique=True)
name = db.Column(db.String(75),nullable=False)
email = db.Column(db.String(150),nullable=False,unique=True)
fav_color = db.Column(db.String(50))
user_bio = db.Column(db.Text(50000), nullable=True)
profile_pic = db.Column(db.String(), nullable = True)
password_hash = db.Column(db.String(128),nullable=False)
datetime_created = db.Column(db.DateTime, default=datetime.utcnow)
posts = db.relationship('Posts', backref ='poster', cascade = 'all,delete-orphan')
comments = db.relationship('Comment', backref ='poster', passive_deletes = True)
likes = db.relationship('Likes', backref='poster', passive_deletes = True)
@property
def password(self):
raise AttributeError('password is not in a readable format')
@password.setter
def password(self,password):
self.password_hash = generate_password_hash(password)
def verify_password(self,password):
return check_password_hash(self.password_hash, password)
def __repr__(self):
return '<Name %r>' % self.name
class Comment(db.Model):
id = db.Column(db.Integer, primary_key=True)
content = db.Column(db.String(500),nullable=False)
date_posted = db.Column(db.DateTime,default = datetime.utcnow())
poster_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete = "CASCADE"), nullable=False)
post_id = db.Column(db.Integer, db.ForeignKey('posts.id', ondelete = "CASCADE"), nullable=False)
class Likes(db.Model):
id = db.Column(db.Integer, primary_key=True)
date_liked = db.Column(db.DateTime, default=datetime.utcnow())
post_id = db.Column(db.Integer, db.ForeignKey('posts.id', ondelete = "CASCADE"), nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete = "CASCADE"), nullable=False)
def __repr__(self):
return f"Like('{self.date_liked}')"
#Login route
@app.route('/login',methods=['GET','POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
user = Users.query.filter_by(username = form.username.data).first()
if user:
if(check_password_hash(user.password_hash, form.password.data)):
login_user(user)
flash("Login Succesfull!!")
return redirect(url_for('dashboard'))
else:
flash("Wrong Password... Try again!!")
else:
flash("User does not exists!!")
return render_template('login.html',form = form)
#dashboard route
@app.route('/dashboard',methods = ['GET','POST'])
@login_required
def dashboard():
return render_template('dashboard.html')
#logout route
@app.route('/logout', methods = ['GET','POST'])
@login_required
def logout():
logout_user()
flash("Logged out succesfully!")
return redirect(url_for('login'))
@app.route('/posts')
def posts():
posts = Posts.query.order_by(Posts.date_posted and Posts.hidden == False)
return render_template('posts.html',posts = posts)
@app.route('/posts/<int:id>', methods = ['GET','POST'])
def post(id):
post = Posts.query.get_or_404(id)
form = CommentForm()
if form.validate_on_submit() and current_user.is_authenticated:
try:
comment = Comment(content = form.content.data , poster = current_user, post_id = post.id)
db.session.add(comment)
db.session.commit()
flash('Comment added successfully','success')
return redirect(url_for('post',id = id))
except:
flash('Error occured while adding comment','danger')
db.session.rollback()
comments = Comment.query.filter_by(post_id = id).order_by(Comment.date_posted.desc())
likes = len(post.likes)
return render_template('post.html',post = post, comments = comments, form = form, id = post.id, likes = likes)
@app.route('/posts/<int:id>/like',methods=['POST'])
@login_required
def like_post(id):
post = Posts.query.filter_by(id = id)
like = Likes.query.filter_by(user_id = current_user.id, post_id = id).first()
if not post:
flash('Post does not exist', 'danger')
elif like:
db.session.delete(like)
db.session.commit()
else:
like = Likes(user_id = current_user.id, post_id = id)
db.session.add(like)
db.session.commit()
return redirect(url_for('post', id=id))
@app.route('/add_post', methods=['POST','GET'])
@login_required
def add_post():
form = PostForm()
if form.validate_on_submit():
poster = current_user.id
post = Posts(title = form.title.data, content = form.content.data, poster_id = poster, slug = form.slug.data)
db.session.add(post)
db.session.commit()
flash("Post added successfully!!")
return redirect(url_for('add_post'))
return render_template('add_post.html',form=form)
@app.route('/post/edit/<int:id>', methods=['POST','GET'])
@login_required
def edit_post(id):
post = Posts.query.get_or_404(id)
form = PostForm()
if form.validate_on_submit():
post.title = form.title.data
post.slug = form.slug.data
post.content = form.content.data
db.session.add(post)
db.session.commit()
flash("Post updated successfully")
return redirect(url_for('post',id=post.id))
if current_user.id == post.poster_id:
form.title.data = post.title
form.slug.data = post.slug
form.content.data = post.content
return render_template('edit_post.html',form=form)
else:
flash("You aren't authorized to update this post!!")
posts = Posts.query.order_by(Posts.date_posted and Posts.hidden == False)
return render_template('posts.html',posts = posts)
@app.route('/post/delete/<int:id>')
@login_required
def delete_post(id):
post_to_delete = Posts.query.get_or_404(id)
id = current_user.id
if id == post_to_delete.poster_id:
try:
db.session.delete(post_to_delete)
db.session.commit()
flash("Post deleted successfully")
posts = Posts.query.order_by(Posts.date_posted and Posts.hidden == False)
return render_template('posts.html',posts = posts)
except:
flash("Oops something went wrong...")
posts = Posts.query.order_by(Posts.date_posted and Posts.hidden == False)
return render_template('posts.html',posts = posts)
else:
flash("You aren't authorized to delete this post!!!!")
posts = Posts.query.order_by(Posts.date_posted and Posts.hidden == False)
return render_template('posts.html',posts = posts)
@app.route('/post/<int:post_id>/comment/<int:comment_id>/delete', methods=['POST', 'DELETE'])
@login_required
def delete_comment(post_id, comment_id):
comment = Comment.query.get_or_404(comment_id)
if comment.poster != current_user:
flash('You are not authorized to delete this comment')
db.session.delete(comment)
db.session.commit()
flash('Comment deleted successfully', 'success')
return redirect(url_for('post', id=post_id))
@app.route('/Users/Add',methods=['POST','GET'])
def add():
name = None
form = UserForm()
if form.validate_on_submit():
user = Users.query.filter_by(email = form.email.data).first()
if user is None:
hashed_pass = generate_password_hash(form.password_hash.data,"sha256")
user = Users(username = form.username.data, name = form.name.data, email = form.email.data, fav_color = form.fav_color.data, user_bio = form.user_bio.data, password_hash = hashed_pass)
db.session.add(user)
db.session.commit()
name = form.name.data
flash("User added successfully!!")
return redirect(url_for('add'))
our_users = Users.query.order_by( Users.datetime_created)
return render_template('add_user.html',name=name,form=form,our_users=our_users)
@app.route('/delete/<int:id>')
@login_required
def delete(id):
user_to_delete = Users.query.get_or_404(id)
name = None
form = UserForm()
if id == current_user.id:
try:
db.session.delete(user_to_delete)
db.session.commit()
flash("User deleted successfully!!")
our_users = Users.query.order_by( Users.datetime_created)
logout_user()
return render_template('add_user.html',name=name,form=form,our_users=our_users)
except:
flash("Oops!.. There was an error deleting the user")
our_users = Users.query.order_by( Users.datetime_created)
return render_template('add_user.html',name=name,form=form,our_users=our_users)
else:
flash("You are not allowed to delete this user")
return redirect(url_for('dashboard'))
@app.route('/Update/<int:id>',methods=['POST','GET'])
@login_required
def update(id):
form = UserForm()
name_to_update = Users.query.get_or_404(id)
if request.method == 'POST':
name_to_update.username = form.username.data
name_to_update.name = form.name.data
name_to_update.email = form.email.data
name_to_update.fav_color = form.fav_color.data
name_to_update.user_bio = form.user_bio.data
if request.files['profile_pic']:
name_to_update.profile_pic = request.files['profile_pic']
pic_filename = secure_filename(name_to_update.profile_pic.filename)
pic_name = str(uuid.uuid1())+'$_'+ pic_filename
name_to_update.profile_pic = pic_name
saver = request.files['profile_pic']
saver.save(os.path.join(app.config['UPLOAD_FOLDER'], pic_name))
try:
db.session.commit()
flash("User updated successfully")
return render_template('update.html',form = form,name_to_update=name_to_update,id = id)
except:
flash("Oops Something went wrong... Try again!")
return render_template('update.html',form = form,name_to_update=name_to_update)
else:
db.session.commit()
flash("User updated successfully")
return render_template('update.html',form = form,name_to_update=name_to_update,id = id)
else:
return render_template('update.html',form = form,name_to_update=name_to_update,id = id)
@app.route('/namepage', methods=['GET','POST'])
def namepage():
name = None
form = test()
if form.validate_on_submit():
name = form.name.data
form.name.data = ''
flash("Name submitted successfully")
return render_template('name.html', name= name, form= form)
@app.context_processor
def base():
form = SearchForm()
return dict(form=form)
@app.route('/search', methods=['POST'])
def search():
form = SearchForm()
posts = Posts.query
if form.validate_on_submit():
post.searched = form.searched.data
posts = posts.filter(Posts.content.like('%' + post.searched + '%'))
posts = posts.order_by(Posts.title).all()
return render_template('search.html',form= form , searched = post.searched, posts = posts)
@app.route('/admin')
@login_required
def admin():
id = current_user.id
if id == 1:
return render_template('admin.html')
else:
flash("Sorry you must be admin to access this page!!!")
return redirect(url_for('dashboard'))
if __name__ == '__main__':
db.create_all()
app.run(debug=True)