Files
Hotel-Booking/Backend/seeders/blog_seeder.py
Iliyan Angelov 5a8ca3c475 updates
2025-12-06 03:27:35 +02:00

321 lines
20 KiB
Python

"""
Blog Seeder
Seeds the database with blog posts
All images are from Unsplash (free stock photos)
"""
import json
import sys
import re
from pathlib import Path
from datetime import datetime, timezone, timedelta
# Add parent directory to path to import modules
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from sqlalchemy.orm import Session
from src.shared.config.database import SessionLocal
from src.shared.config.logging_config import get_logger
from src.content.models.blog import BlogPost
from src.auth.models.user import User
# Import all models to ensure relationships are loaded correctly
from src.models import *
logger = get_logger(__name__)
def slugify(text):
"""Convert text to URL-friendly slug"""
text = text.lower()
text = re.sub(r'[^\w\s-]', '', text)
text = re.sub(r'[-\s]+', '-', text)
return text.strip('-')
def get_blog_posts_data(author_id: int):
"""Generate comprehensive blog posts data with Unsplash images"""
now = datetime.now(timezone.utc)
posts = [
{
'title': '10 Tips for Planning the Perfect Luxury Hotel Stay',
'slug': '10-tips-planning-perfect-luxury-hotel-stay',
'excerpt': 'Discover expert tips to make your luxury hotel experience unforgettable. From booking strategies to maximizing amenities, we share insider secrets.',
'content': '''<p>Planning a luxury hotel stay requires attention to detail and insider knowledge. Whether you're celebrating a special occasion or simply treating yourself, these tips will help you make the most of your experience.</p>
<h2>1. Book in Advance</h2>
<p>Luxury hotels often offer early bird discounts and better room availability when you book well in advance. Planning ahead also gives you access to special packages and upgrades.</p>
<h2>2. Communicate Your Preferences</h2>
<p>Don't hesitate to communicate your preferences when booking. Whether you prefer a high floor, specific room amenities, or have dietary restrictions, hotels are happy to accommodate.</p>
<h2>3. Join Loyalty Programs</h2>
<p>Most luxury hotels offer loyalty programs with exclusive benefits. Join before your stay to earn points, receive member rates, and enjoy perks like late checkout.</p>
<h2>4. Explore Hotel Amenities</h2>
<p>Take advantage of all the hotel has to offer - from spa treatments to fine dining. Many luxury hotels have world-class facilities that are worth experiencing.</p>
<h2>5. Use Concierge Services</h2>
<p>The concierge team is your gateway to the best local experiences. They can secure restaurant reservations, arrange transportation, and provide insider recommendations.</p>
<h2>6. Check for Special Packages</h2>
<p>Look for special packages that bundle accommodations with dining, spa, or local experiences. These often provide better value than booking separately.</p>
<h2>7. Review Cancellation Policies</h2>
<p>Understand the cancellation and modification policies before booking. Flexible rates may cost more but provide peace of mind.</p>
<h2>8. Pack Appropriately</h2>
<p>While luxury hotels provide many amenities, bringing appropriate attire for dining and activities ensures you're prepared for all experiences.</p>
<h2>9. Arrive Early or Late</h2>
<p>If possible, arrive early or late to avoid peak check-in times. This often results in better service and sometimes room upgrades if available.</p>
<h2>10. Leave Reviews</h2>
<p>Share your experience through reviews. Hotels value feedback and often reward guests who provide detailed, constructive reviews.</p>
<p>Remember, a luxury hotel stay is about creating memories. Take your time, enjoy every moment, and don't hesitate to ask for what will make your stay perfect.</p>''',
'featured_image': 'https://images.unsplash.com/photo-1566073771259-6a8506099945?w=1200&h=800&fit=crop',
'author_id': author_id,
'published_at': now - timedelta(days=5),
'is_published': True,
'tags': json.dumps(['travel tips', 'luxury travel', 'hotel guide', 'vacation planning']),
'meta_title': '10 Tips for Planning the Perfect Luxury Hotel Stay | Travel Guide',
'meta_description': 'Expert tips for planning an unforgettable luxury hotel stay. Learn booking strategies, how to maximize amenities, and insider secrets.',
'meta_keywords': 'luxury hotel tips, hotel booking guide, travel planning, luxury travel advice',
'sections': None
},
{
'title': 'The Art of Fine Dining: A Culinary Journey at Our Hotel',
'slug': 'art-fine-dining-culinary-journey',
'excerpt': 'Explore our award-winning restaurants and discover the culinary philosophy behind our Michelin-starred dining experiences.',
'content': '''<p>Fine dining is an art form that combines exceptional ingredients, masterful technique, and impeccable service. At our hotel, we've created culinary experiences that celebrate both tradition and innovation.</p>
<h2>Our Culinary Philosophy</h2>
<p>Our chefs believe in using the finest locally sourced ingredients, supporting sustainable practices, and creating dishes that tell a story. Each plate is a masterpiece, carefully crafted to delight all senses.</p>
<h2>Signature Dishes</h2>
<p>From our signature truffle risotto to our perfectly aged wagyu beef, every dish on our menu has been thoughtfully created. Our tasting menus offer a journey through flavors, textures, and culinary traditions.</p>
<h2>Wine Pairing Excellence</h2>
<p>Our sommeliers curate wine pairings that enhance every dish. With an extensive cellar featuring rare vintages and hidden gems, we ensure the perfect complement to your meal.</p>
<h2>Private Dining Experiences</h2>
<p>For special occasions, our private dining rooms offer intimate settings with personalized menus. Our chefs work closely with guests to create unforgettable culinary experiences.</p>
<p>Join us for a culinary journey that celebrates the art of fine dining and creates memories that last a lifetime.</p>''',
'featured_image': 'https://images.unsplash.com/photo-1414235077428-338989a2e8c0?w=1200&h=800&fit=crop',
'author_id': author_id,
'published_at': now - timedelta(days=10),
'is_published': True,
'tags': json.dumps(['fine dining', 'culinary', 'restaurant', 'gourmet']),
'meta_title': 'The Art of Fine Dining | Culinary Excellence',
'meta_description': 'Discover our award-winning restaurants and Michelin-starred dining experiences. Explore our culinary philosophy and signature dishes.',
'meta_keywords': 'fine dining, Michelin restaurant, gourmet cuisine, culinary experience',
'sections': None
},
{
'title': 'Wellness and Relaxation: Your Guide to Our Spa & Wellness Center',
'slug': 'wellness-relaxation-spa-wellness-center-guide',
'excerpt': 'Discover our world-class spa and wellness center. Learn about our treatments, wellness programs, and how to achieve ultimate relaxation.',
'content': '''<p>In today's fast-paced world, taking time for wellness and relaxation is essential. Our spa and wellness center offers a sanctuary where you can rejuvenate your mind, body, and spirit.</p>
<h2>Our Wellness Philosophy</h2>
<p>We believe in holistic wellness that addresses physical, mental, and emotional well-being. Our treatments combine traditional techniques with modern innovations to provide comprehensive care.</p>
<h2>Signature Treatments</h2>
<p>From our signature deep tissue massages to rejuvenating facials, each treatment is customized to your needs. Our expert therapists use premium products and time-tested techniques.</p>
<h2>Wellness Programs</h2>
<p>Beyond individual treatments, we offer comprehensive wellness programs including yoga classes, meditation sessions, and personalized fitness consultations.</p>
<h2>The Spa Environment</h2>
<p>Our spa facilities include steam rooms, saunas, relaxation lounges, and private treatment rooms. Every detail is designed to create a serene, peaceful atmosphere.</p>
<h2>Couples Experiences</h2>
<p>Share the relaxation experience with our couples treatments. Perfect for romantic getaways or celebrating special moments together.</p>
<p>Whether you're seeking stress relief, muscle recovery, or simply a moment of tranquility, our spa and wellness center provides the perfect escape.</p>''',
'featured_image': 'https://images.unsplash.com/photo-1544161515-4ab6ce6db874?w=1200&h=800&fit=crop',
'author_id': author_id,
'published_at': now - timedelta(days=15),
'is_published': True,
'tags': json.dumps(['spa', 'wellness', 'relaxation', 'self-care']),
'meta_title': 'Wellness and Relaxation Guide | Spa & Wellness Center',
'meta_description': 'Discover our world-class spa and wellness center. Learn about treatments, wellness programs, and how to achieve ultimate relaxation.',
'meta_keywords': 'spa, wellness, relaxation, massage, hotel spa',
'sections': None
},
{
'title': 'Sustainable Luxury: Our Commitment to Environmental Responsibility',
'slug': 'sustainable-luxury-environmental-responsibility',
'excerpt': 'Learn about our sustainability initiatives and how we balance luxury with environmental responsibility. Discover our green practices and commitment to the planet.',
'content': '''<p>Luxury and sustainability are not mutually exclusive. At our hotel, we've proven that you can enjoy world-class amenities while protecting the environment for future generations.</p>
<h2>Our Sustainability Mission</h2>
<p>We're committed to reducing our environmental footprint through innovative practices, renewable energy, and responsible sourcing. Our goal is carbon neutrality while maintaining the highest standards of luxury.</p>
<h2>Green Building Practices</h2>
<p>Our facilities incorporate energy-efficient systems, water conservation measures, and sustainable materials. We continuously invest in technologies that reduce our environmental impact.</p>
<h2>Local and Sustainable Sourcing</h2>
<p>We prioritize local suppliers and sustainable ingredients in our restaurants. This not only reduces our carbon footprint but also supports local communities and ensures the freshest quality.</p>
<h2>Waste Reduction</h2>
<p>Through comprehensive recycling programs, composting, and waste reduction initiatives, we've significantly decreased our waste output. Single-use plastics have been eliminated throughout the property.</p>
<h2>Guest Participation</h2>
<p>We invite guests to join us in our sustainability efforts through optional programs like towel reuse, energy conservation, and supporting local conservation projects.</p>
<p>Together, we can enjoy luxury experiences while protecting our planet. Every small action contributes to a more sustainable future.</p>''',
'featured_image': 'https://images.unsplash.com/photo-1470071459604-3b5ec3a7fe05?w=1200&h=800&fit=crop',
'author_id': author_id,
'published_at': now - timedelta(days=20),
'is_published': True,
'tags': json.dumps(['sustainability', 'environment', 'green hotel', 'eco-friendly']),
'meta_title': 'Sustainable Luxury | Environmental Responsibility',
'meta_description': 'Learn about our sustainability initiatives and how we balance luxury with environmental responsibility. Discover our green practices.',
'meta_keywords': 'sustainable luxury, green hotel, environmental responsibility, eco-friendly',
'sections': None
},
{
'title': 'Celebrating 30 Years of Excellence in Hospitality',
'slug': 'celebrating-30-years-excellence-hospitality',
'excerpt': 'Join us as we celebrate three decades of providing exceptional hospitality. Learn about our journey, milestones, and vision for the future.',
'content': '''<p>This year marks a significant milestone - 30 years of excellence in hospitality. From our humble beginnings to becoming an internationally recognized destination, our journey has been remarkable.</p>
<h2>Our Beginnings</h2>
<p>Founded in 1993, we started with a simple vision: to create a sanctuary of luxury and sophistication. What began as a small boutique property has grown into a world-class destination.</p>
<h2>Key Milestones</h2>
<p>Over three decades, we've achieved numerous milestones - from our first five-star rating to receiving international awards. Each achievement represents our commitment to excellence.</p>
<h2>Our Team</h2>
<p>None of this would be possible without our dedicated team. Their passion, professionalism, and commitment to service excellence have been the foundation of our success.</p>
<h2>Looking Forward</h2>
<p>As we celebrate this milestone, we're also looking to the future. We continue to innovate, invest in our facilities, and enhance our services to exceed guest expectations.</p>
<h2>Thank You</h2>
<p>To all our guests, partners, and team members - thank you for being part of our journey. Here's to the next 30 years of creating unforgettable experiences.</p>
<p>Join us in celebrating this special anniversary with special packages and events throughout the year.</p>''',
'featured_image': 'https://images.unsplash.com/photo-1520250497591-112f2f40a3f4?w=1200&h=800&fit=crop',
'author_id': author_id,
'published_at': now - timedelta(days=25),
'is_published': True,
'tags': json.dumps(['anniversary', 'hotel history', 'milestone', 'celebration']),
'meta_title': 'Celebrating 30 Years of Excellence | Hotel Anniversary',
'meta_description': 'Join us as we celebrate three decades of providing exceptional hospitality. Learn about our journey, milestones, and vision for the future.',
'meta_keywords': 'hotel anniversary, 30 years, hospitality excellence, milestone',
'sections': None
},
{
'title': 'The Ultimate Business Traveler\'s Guide to Our Hotel',
'slug': 'ultimate-business-traveler-guide',
'excerpt': 'Discover how our hotel caters to business travelers with state-of-the-art facilities, convenient services, and amenities designed for productivity and comfort.',
'content': '''<p>Business travel doesn't have to mean sacrificing comfort or productivity. Our hotel is designed specifically to meet the needs of modern business travelers.</p>
<h2>Business Facilities</h2>
<p>Our fully equipped business center provides everything you need - from high-speed internet to meeting rooms with state-of-the-art AV equipment. Work seamlessly from anywhere in the hotel.</p>
<h2>Convenient Services</h2>
<p>Express check-in and checkout, 24/7 concierge service, and flexible meeting arrangements ensure your business needs are met efficiently. We understand that time is valuable.</p>
<h2>Comfortable Accommodations</h2>
<p>Our rooms feature dedicated workspaces, ergonomic furniture, and premium amenities. After a long day of meetings, relax in comfort and recharge for tomorrow.</p>
<h2>Networking Opportunities</h2>
<p>Our restaurants and lounges provide perfect settings for business networking. Whether hosting clients or connecting with colleagues, we provide the ideal atmosphere.</p>
<h2>Wellness for Business Travelers</h2>
<p>Maintain your wellness routine with our fitness center, spa services, and healthy dining options. We help you stay balanced even when traveling for business.</p>
<p>Experience business travel redefined - where productivity meets luxury, and comfort enhances performance.</p>''',
'featured_image': 'https://images.unsplash.com/photo-1497366216548-37526070297c?w=1200&h=800&fit=crop',
'author_id': author_id,
'published_at': now - timedelta(days=30),
'is_published': True,
'tags': json.dumps(['business travel', 'corporate', 'productivity', 'meetings']),
'meta_title': 'Business Traveler\'s Guide | Corporate Accommodation',
'meta_description': 'Discover how our hotel caters to business travelers with state-of-the-art facilities, convenient services, and productivity-focused amenities.',
'meta_keywords': 'business travel, corporate hotel, business facilities, meeting rooms',
'sections': None
}
]
return posts
def seed_blog_posts(db: Session, clear_existing: bool = False):
"""Seed blog posts into the database"""
try:
# Get admin user as author
admin_user = db.query(User).filter(User.email == 'admin@hotel.com').first()
if not admin_user:
logger.error('Admin user not found. Please run user seeder first.')
raise ValueError('Admin user not found. Please run user seeder first.')
if clear_existing:
logger.info('Clearing existing blog posts...')
db.query(BlogPost).delete()
db.commit()
logger.info('Existing blog posts cleared.')
posts_data = get_blog_posts_data(admin_user.id)
now = datetime.now(timezone.utc)
created_count = 0
updated_count = 0
for post_data in posts_data:
# Generate slug if not provided
if not post_data.get('slug'):
post_data['slug'] = slugify(post_data['title'])
existing = db.query(BlogPost).filter(BlogPost.slug == post_data['slug']).first()
if existing:
logger.debug(f"Blog post '{post_data['title']}' already exists. Updating...")
for key, value in post_data.items():
setattr(existing, key, value)
existing.updated_at = now
updated_count += 1
else:
logger.debug(f"Creating blog post: {post_data['title']}")
post = BlogPost(**post_data)
db.add(post)
created_count += 1
db.commit()
logger.info(f'Successfully seeded blog posts! Created: {created_count}, Updated: {updated_count}, Total: {len(posts_data)}')
except Exception as e:
db.rollback()
logger.error(f'Error seeding blog posts: {str(e)}', exc_info=True)
raise
def main():
import argparse
parser = argparse.ArgumentParser(description='Seed blog posts')
parser.add_argument(
'--clear',
action='store_true',
help='Clear existing blog posts before seeding'
)
args = parser.parse_args()
db = SessionLocal()
try:
seed_blog_posts(db, clear_existing=args.clear)
except Exception as e:
logger.error(f'Failed to seed blog posts: {str(e)}', exc_info=True)
sys.exit(1)
finally:
db.close()
if __name__ == '__main__':
main()