-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp.py
More file actions
658 lines (552 loc) · 24.8 KB
/
app.py
File metadata and controls
658 lines (552 loc) · 24.8 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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
# app.py
import os
from flask import Flask, render_template, request, jsonify, Blueprint, session, redirect, url_for, send_from_directory
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash, check_password_hash
from werkzeug.utils import secure_filename
from datetime import datetime, timedelta
import secrets
import re
from functools import wraps
import jwt
from flask_mail import Mail, Message
from itsdangerous import URLSafeTimedSerializer
import logging
from logging.handlers import RotatingFileHandler
from PIL import Image, ImageDraw
import io
import base64
from dotenv import load_dotenv
load_dotenv()
app = Flask(__name__)
# Premium Configuration
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY', secrets.token_hex(32))
app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv('DATABASE_URL', 'sqlite:///premium_blog.db')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(days=30)
app.config['JWT_SECRET_KEY'] = secrets.token_hex(32)
# File Upload Configuration
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
app.config['UPLOAD_FOLDER'] = 'static/uploads'
app.config['ALLOWED_EXTENSIONS'] = {'png', 'jpg', 'jpeg', 'gif', 'webp'}
# Email Configuration
app.config['MAIL_SERVER'] = os.getenv('MAIL_SERVER', 'smtp.gmail.com')
app.config['MAIL_PORT'] = int(os.getenv('MAIL_PORT', 587))
app.config['MAIL_USE_TLS'] = os.getenv('MAIL_USE_TLS', 'True').lower() == 'true'
app.config['MAIL_USERNAME'] = os.getenv('MAIL_USERNAME', 'your-email@gmail.com')
app.config['MAIL_PASSWORD'] = os.getenv('MAIL_PASSWORD', 'your-app-password')
app.config['MAIL_DEFAULT_SENDER'] = os.getenv('MAIL_DEFAULT_SENDER', 'your-email@gmail.com')
db = SQLAlchemy(app)
mail = Mail(app)
serializer = URLSafeTimedSerializer(app.config['SECRET_KEY'])
# Create directories
for folder in ['avatars', 'posts', 'backgrounds']:
os.makedirs(os.path.join(app.config['UPLOAD_FOLDER'], folder), exist_ok=True)
# Setup logging
if not os.path.exists('logs'):
os.mkdir('logs')
file_handler = RotatingFileHandler('logs/blog.log', maxBytes=10240, backupCount=10)
file_handler.setFormatter(logging.Formatter(
'%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'
))
file_handler.setLevel(logging.INFO)
app.logger.addHandler(file_handler)
app.logger.setLevel(logging.INFO)
# ===== MODELS =====
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False, index=True)
email = db.Column(db.String(120), unique=True, nullable=False, index=True)
password_hash = db.Column(db.String(128), nullable=False)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
last_login = db.Column(db.DateTime, nullable=True)
is_active = db.Column(db.Boolean, default=True)
is_admin = db.Column(db.Boolean, default=False)
is_premium = db.Column(db.Boolean, default=False)
profile_picture = db.Column(db.String(200), default='default.png')
bio = db.Column(db.Text, nullable=True)
website = db.Column(db.String(200), nullable=True)
location = db.Column(db.String(100), nullable=True)
posts = db.relationship('Post', backref='author', lazy=True, cascade='all, delete-orphan')
comments = db.relationship('Comment', backref='author', lazy=True, cascade='all, delete-orphan')
likes = db.relationship('Like', backref='user', lazy=True, cascade='all, delete-orphan')
def set_password(self, password):
self.password_hash = generate_password_hash(password)
def check_password(self, password):
return check_password_hash(self.password_hash, password)
def get_avatar_url(self):
if self.profile_picture and self.profile_picture != 'default.png':
return url_for('uploaded_file', filename=f'avatars/{self.profile_picture}')
else:
return f"/api/avatar/{self.username}"
def to_dict(self):
return {
'id': self.id,
'username': self.username,
'email': self.email,
'created_at': self.created_at.isoformat(),
'last_login': self.last_login.isoformat() if self.last_login else None,
'profile_picture': self.get_avatar_url(),
'bio': self.bio,
'website': self.website,
'location': self.location,
'is_premium': self.is_premium,
'is_admin': self.is_admin,
'post_count': len(self.posts)
}
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(200), nullable=False, index=True)
content = db.Column(db.Text, nullable=False)
excerpt = db.Column(db.String(300), nullable=True)
slug = db.Column(db.String(210), unique=True, index=True, nullable=True)
created_at = db.Column(db.DateTime, default=datetime.utcnow, index=True)
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
is_published = db.Column(db.Boolean, default=True)
is_featured = db.Column(db.Boolean, default=False)
view_count = db.Column(db.Integer, default=0)
featured_image = db.Column(db.String(200), nullable=True)
tags = db.Column(db.String(500), nullable=True)
category = db.Column(db.String(100), default='General')
comments = db.relationship('Comment', backref='post', lazy=True, cascade='all, delete-orphan')
likes = db.relationship('Like', backref='post', lazy=True, cascade='all, delete-orphan')
def generate_slug(self):
if not self.title:
return None
base_slug = re.sub(r'[^\w\s-]', '', self.title).strip().lower()
base_slug = re.sub(r'[-\s]+', '-', base_slug)
slug = base_slug
counter = 1
while Post.query.filter_by(slug=slug).first():
slug = f"{base_slug}-{counter}"
counter += 1
return slug
def get_featured_image_url(self):
if self.featured_image:
return url_for('uploaded_file', filename=f'posts/{self.featured_image}')
return None
def to_dict(self):
return {
'id': self.id,
'title': self.title,
'content': self.content,
'excerpt': self.excerpt,
'slug': self.slug,
'created_at': self.created_at.isoformat(),
'updated_at': self.updated_at.isoformat(),
'author_id': self.user_id,
'author_username': self.author.username,
'author_avatar': self.author.get_avatar_url(),
'is_published': self.is_published,
'is_featured': self.is_featured,
'view_count': self.view_count,
'featured_image': self.get_featured_image_url(),
'tags': self.tags.split(',') if self.tags else [],
'category': self.category,
'comment_count': len(self.comments),
'like_count': len(self.likes),
'reading_time': max(1, len(self.content.split()) // 200) if self.content else 1
}
class Comment(db.Model):
id = db.Column(db.Integer, primary_key=True)
content = db.Column(db.Text, nullable=False)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
post_id = db.Column(db.Integer, db.ForeignKey('post.id'), nullable=False)
parent_id = db.Column(db.Integer, db.ForeignKey('comment.id'), nullable=True)
replies = db.relationship('Comment', backref=db.backref('parent', remote_side=[id]), lazy=True)
def to_dict(self):
return {
'id': self.id,
'content': self.content,
'created_at': self.created_at.isoformat(),
'author_id': self.user_id,
'author_username': self.author.username,
'author_avatar': self.author.get_avatar_url(),
'post_id': self.post_id,
'parent_id': self.parent_id,
'replies': [reply.to_dict() for reply in self.replies]
}
class Like(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
post_id = db.Column(db.Integer, db.ForeignKey('post.id'), nullable=False)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
__table_args__ = (db.UniqueConstraint('user_id', 'post_id', name='unique_like'),)
# Security headers middleware
@app.after_request
def set_security_headers(response):
response.headers['X-Content-Type-Options'] = 'nosniff'
response.headers['X-Frame-Options'] = 'SAMEORIGIN'
response.headers['X-XSS-Protection'] = '1; mode=block'
return response
# ===== UTILITY FUNCTIONS =====
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS']
def save_image(file, folder, max_size=(800, 600)):
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
unique_filename = f"{secrets.token_hex(8)}_{filename}"
filepath = os.path.join(app.config['UPLOAD_FOLDER'], folder, unique_filename)
try:
image = Image.open(file.stream)
if image.mode in ('RGBA', 'P'):
image = image.convert('RGB')
image.thumbnail(max_size, Image.Resampling.LANCZOS)
image.save(filepath, optimize=True, quality=85)
return unique_filename
except Exception as e:
app.logger.error(f"Error processing image: {str(e)}")
return None
return None
def create_default_avatar(username, size=200):
bg_colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7', '#DDA0DD', '#98D8C8']
color = bg_colors[hash(username) % len(bg_colors)]
img = Image.new('RGB', (size, size), color=color)
draw = ImageDraw.Draw(img)
initials = ''.join([name[0].upper() for name in username.split()[:2]]) or username[0].upper()
# Simple text drawing (for demo)
from PIL import ImageFont
try:
font = ImageFont.truetype("arial.ttf", size//3)
except:
font = ImageFont.load_default()
bbox = draw.textbbox((0, 0), initials, font=font)
text_width = bbox[2] - bbox[0]
text_height = bbox[3] - bbox[1]
position = ((size - text_width) // 2, (size - text_height) // 2)
draw.text(position, initials, fill='white', font=font)
buffer = io.BytesIO()
img.save(buffer, format='PNG')
buffer.seek(0)
return buffer
def validate_email(email):
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return re.match(pattern, email) is not None
def validate_password(password):
if len(password) < 8:
return False, "Password must be at least 8 characters long"
if not re.search(r"[A-Z]", password):
return False, "Password must contain at least one uppercase letter"
if not re.search(r"[a-z]", password):
return False, "Password must contain at least one lowercase letter"
if not re.search(r"\d", password):
return False, "Password must contain at least one digit"
return True, "Password is valid"
# ===== DECORATORS =====
def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if 'user_id' not in session:
return jsonify({'success': False, 'message': 'Authentication required'}), 401
return f(*args, **kwargs)
return decorated_function
def admin_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if 'user_id' not in session:
return jsonify({'success': False, 'message': 'Authentication required'}), 401
user = User.query.get(session['user_id'])
if not user or not user.is_admin:
return jsonify({'success': False, 'message': 'Admin privileges required'}), 403
return f(*args, **kwargs)
return decorated_function
# ===== AUTH API =====
auth_api = Blueprint('auth_api', __name__, url_prefix='/api/auth')
@auth_api.route('/register', methods=['POST'])
def register_user():
try:
data = request.get_json()
if not data or not data.get('username') or not data.get('password') or not data.get('email'):
return jsonify({'success': False, 'message': 'Username, email and password are required'}), 400
username = data['username'].strip()
email = data['email'].strip().lower()
password = data['password']
if len(username) < 3:
return jsonify({'success': False, 'message': 'Username must be at least 3 characters long'}), 400
if not validate_email(email):
return jsonify({'success': False, 'message': 'Please provide a valid email address'}), 400
is_valid, msg = validate_password(password)
if not is_valid:
return jsonify({'success': False, 'message': msg}), 400
if User.query.filter_by(username=username).first():
return jsonify({'success': False, 'message': 'Username already exists'}), 409
if User.query.filter_by(email=email).first():
return jsonify({'success': False, 'message': 'Email already exists'}), 409
new_user = User(username=username, email=email)
new_user.set_password(password)
db.session.add(new_user)
db.session.commit()
session.permanent = True
session['user_id'] = new_user.id
session['username'] = new_user.username
return jsonify({
'success': True,
'message': 'User registered successfully',
'user': new_user.to_dict()
}), 201
except Exception as e:
db.session.rollback()
app.logger.error(f"Registration error: {str(e)}")
return jsonify({'success': False, 'message': 'Error registering user'}), 500
@auth_api.route('/login', methods=['POST'])
def login_user():
try:
data = request.get_json()
if not data or not data.get('username') or not data.get('password'):
return jsonify({'success': False, 'message': 'Username and password are required'}), 400
username = data['username']
password = data['password']
remember_me = data.get('remember_me', False)
user = User.query.filter_by(username=username).first()
if user and user.check_password(password):
if not user.is_active:
return jsonify({'success': False, 'message': 'Account is deactivated'}), 403
session.permanent = remember_me
session['user_id'] = user.id
session['username'] = user.username
user.last_login = datetime.utcnow()
db.session.commit()
return jsonify({
'success': True,
'message': 'Login successful',
'user': user.to_dict()
}), 200
else:
return jsonify({'success': False, 'message': 'Invalid username or password'}), 401
except Exception as e:
app.logger.error(f"Login error: {str(e)}")
return jsonify({'success': False, 'message': 'Error during login'}), 500
@auth_api.route('/logout', methods=['POST'])
def logout_user():
session.clear()
return jsonify({'success': True, 'message': 'Logout successful'}), 200
@auth_api.route('/user', methods=['GET'])
@login_required
def get_current_user():
user = User.query.get(session['user_id'])
return jsonify({'success': True, 'user': user.to_dict()}), 200
@auth_api.route('/upload-avatar', methods=['POST'])
@login_required
def upload_avatar():
try:
if 'avatar' not in request.files:
return jsonify({'success': False, 'message': 'No file selected'}), 400
file = request.files['avatar']
if file.filename == '':
return jsonify({'success': False, 'message': 'No file selected'}), 400
user = User.query.get(session['user_id'])
filename = save_image(file, 'avatars', max_size=(400, 400))
if filename:
if user.profile_picture and user.profile_picture != 'default.png':
old_path = os.path.join(app.config['UPLOAD_FOLDER'], 'avatars', user.profile_picture)
if os.path.exists(old_path):
os.remove(old_path)
user.profile_picture = filename
db.session.commit()
return jsonify({
'success': True,
'message': 'Avatar uploaded successfully',
'avatar_url': user.get_avatar_url()
}), 200
else:
return jsonify({'success': False, 'message': 'Invalid file type'}), 400
except Exception as e:
db.session.rollback()
app.logger.error(f"Avatar upload error: {str(e)}")
return jsonify({'success': False, 'message': 'Error uploading avatar'}), 500
# ===== BLOG API =====
blog_api = Blueprint('blog_api', __name__, url_prefix='/api/posts')
@blog_api.route('/', methods=['GET'])
def get_all_posts():
try:
page = request.args.get('page', 1, type=int)
per_page = request.args.get('per_page', 10, type=int)
search = request.args.get('search', '')
query = Post.query.filter_by(is_published=True)
if search:
query = query.filter(
db.or_(
Post.title.ilike(f'%{search}%'),
Post.content.ilike(f'%{search}%'),
Post.tags.ilike(f'%{search}%')
)
)
posts = query.order_by(Post.created_at.desc()).paginate(
page=page, per_page=per_page, error_out=False
)
return jsonify({
'success': True,
'posts': [post.to_dict() for post in posts.items],
'pagination': {
'page': page,
'per_page': per_page,
'total': posts.total,
'pages': posts.pages,
'has_next': posts.has_next,
'has_prev': posts.has_prev
}
}), 200
except Exception as e:
app.logger.error(f"Get posts error: {str(e)}")
return jsonify({'success': False, 'message': 'Error fetching posts'}), 500
@blog_api.route('/my', methods=['GET'])
@login_required
def get_my_posts():
try:
page = request.args.get('page', 1, type=int)
per_page = request.args.get('per_page', 10, type=int)
user_posts = Post.query.filter_by(user_id=session['user_id'])\
.order_by(Post.created_at.desc())\
.paginate(page=page, per_page=per_page, error_out=False)
return jsonify({
'success': True,
'posts': [post.to_dict() for post in user_posts.items],
'pagination': {
'page': page,
'per_page': per_page,
'total': user_posts.total,
'pages': user_posts.pages
}
}), 200
except Exception as e:
app.logger.error(f"Get my posts error: {str(e)}")
return jsonify({'success': False, 'message': 'Error fetching your posts'}), 500
@blog_api.route('/<int:post_id>', methods=['GET'])
def get_post(post_id):
try:
post = Post.query.get_or_404(post_id)
post.view_count += 1
db.session.commit()
return jsonify({'success': True, 'post': post.to_dict()}), 200
except Exception as e:
app.logger.error(f"Get post error: {str(e)}")
return jsonify({'success': False, 'message': 'Post not found'}), 404
@blog_api.route('/', methods=['POST'])
@login_required
def create_post():
try:
data = request.get_json()
if not data or not data.get('title') or not data.get('content'):
return jsonify({'success': False, 'message': 'Title and content are required'}), 400
user = User.query.get(session['user_id'])
if not user:
return jsonify({'success': False, 'message': 'User not found'}), 404
new_post = Post(
title=data['title'],
content=data['content'],
excerpt=data.get('excerpt', data['content'][:297] + '...' if len(data['content']) > 300 else data['content']),
author=user,
featured_image=data.get('featured_image'),
tags=','.join(data.get('tags', [])) if data.get('tags') else None,
category=data.get('category', 'General')
)
new_post.slug = new_post.generate_slug()
db.session.add(new_post)
db.session.commit()
return jsonify({
'success': True,
'message': 'Post created successfully',
'post': new_post.to_dict()
}), 201
except Exception as e:
db.session.rollback()
app.logger.error(f"Create post error: {str(e)}")
return jsonify({'success': False, 'message': 'Error creating post'}), 500
# Avatar API
@app.route('/api/avatar/<username>')
def generate_avatar(username):
try:
size = request.args.get('size', 200, type=int)
avatar_buffer = create_default_avatar(username, size)
return send_from_directory('.', '', mimetype='image/png')
except Exception as e:
app.logger.error(f"Avatar generation error: {str(e)}")
return "Error generating avatar", 500
# File serving route
@app.route('/uploads/<path:filename>')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
# ===== REGISTER BLUEPRINTS =====
app.register_blueprint(auth_api)
app.register_blueprint(blog_api)
# ===== FRONTEND ROUTES =====
@app.route('/')
def index():
return render_template('index.html', page='home')
@app.route('/login')
def login_view():
return render_template('login.html', page='login')
@app.route('/register')
def register_view():
return render_template('register.html', page='register')
@app.route('/dashboard')
def dashboard_view():
return render_template('dashboard.html', page='dashboard')
@app.route('/customer-dashboard')
def customer_dashboard_view():
return render_template('customer_dashboard.html', page='customer_dashboard')
@app.route('/admin-dashboard')
def admin_dashboard_view():
return render_template('admin_dashboard.html', page='admin_dashboard')
@app.route('/create-post')
def create_post_view():
return render_template('create_post.html', page='create_post')
@app.route('/profile')
def profile_view():
return render_template('profile.html', page='profile')
@app.route('/posts')
def posts_view():
return render_template('posts.html', page='posts')
@app.route('/post/<int:post_id>')
def view_post(post_id):
return render_template('view_post.html', page='view_post', post_id=post_id)
# ===== CONTEXT PROCESSOR =====
@app.context_processor
def inject_user():
if 'user_id' in session:
user = User.query.get(session['user_id'])
if user:
return {'current_user': user}
return {'current_user': None}
# ===== DATABASE INITIALIZATION =====
def init_db():
with app.app_context():
# Drop all tables and recreate (for development)
db.drop_all()
db.create_all()
# Create default admin user
admin = User(
username='admin',
email='admin@blog.com',
is_admin=True,
is_premium=True,
bio='System Administrator'
)
admin.set_password('Admin123!')
db.session.add(admin)
db.session.commit()
print("✅ Database initialized successfully!")
print("✅ Default admin user created: admin/Admin123!")
# ===== ERROR HANDLERS =====
@app.errorhandler(404)
def not_found(error):
if request.path.startswith('/api/'):
return jsonify({'success': False, 'message': 'Endpoint not found'}), 404
return render_template('404.html'), 404
@app.errorhandler(500)
def internal_error(error):
app.logger.error(f"Server Error: {str(error)}")
if request.path.startswith('/api/'):
return jsonify({'success': False, 'message': 'Internal server error'}), 500
return render_template('500.html'), 500
# ===== MAIN APPLICATION =====
if __name__ == '__main__':
print("🚀 Starting Premium Blog Application...")
init_db()
print("📍 Access: http://localhost:5000")
print("🔐 Default admin: admin / Admin123!")
app.logger.info('Premium Blog startup complete')
app.run(debug=True, host='0.0.0.0', port=5000)