A modern, responsive news website built with Flask - Works with demo data or real NewsAPI
β¨ Ready to use immediately - No API keys required for demo mode!
π§ Production ready - Easy upgrade to live NewsAPI integration
π― Perfect for learning - Clean code, comprehensive documentation
π Quick Start β’ π Documentation β’ π οΈ Features β’ οΏ½ Live API Setup β’ π€ Contributing
Clean, modern homepage with featured news articles and smooth animations
Responsive news grid with category filtering and real-time search
Real-time search functionality with category-based filtering
Fully responsive design optimized for all device sizes
Enhanced contact form with real-time validation and smooth animations
- π Modern Dark Theme - Glassmorphism design with smooth animations
- π± Fully Responsive - Works perfectly on all device sizes (320px to 1200px+)
- π Real-time Search - Filter news articles instantly as you type
- π Smooth Animations - Micro-interactions and hover effects
- π Interactive UI - Modern card design with hover states
- π‘ Demo News Feed - Sample articles included for instant demo
- π Live News Option - Easy integration with NewsAPI for real data
- π― Category Filtering - Browse by Business, Technology, Sports, etc.
- π Responsive Design - Optimized for all device sizes
- π Read More - Interactive article cards with external links
- π·οΈ Source Attribution - Clear source and author information
- π Search Functionality - Find articles by title or content
- π Fast Loading - Optimized images with lazy loading
- πΎ Lightweight - No external API dependencies
- π― SEO Friendly - Clean URLs and meta tags
- π± PWA Ready - Progressive Web App capabilities
- π Environment Variables - Secure configuration management
- π‘οΈ Input Validation - XSS and injection protection
- π Security Headers - HSTS, XSS Protection, Content Security
- π« Safe Demo Mode - No API keys required for demo
- β Production Ready - Easy switch to live data
- Python 3.7+
- NewsAPI Key (optional) - Free from newsapi.org for live news
-
Clone the repository
git clone https://github.com/Shriraj888/flask-news-website.git cd flask-news-website
-
Create virtual environment
python -m venv venv # Activate virtual environment # On Windows: venv\Scripts\activate # On macOS/Linux: source venv/bin/activate
-
Install dependencies
pip install -r requirements.txt
-
Run the application
python app.py
π Visit
http://localhost:5000
to see your website with demo data!
This version includes demo news data and requires no external API keys or configuration!
If you want to fetch live news data instead of using demo content, follow these steps:
-
Get a free NewsAPI key
- Visit newsapi.org
- Create a free account (70,000 requests/month free)
- Copy your API key
-
Create environment file
# Create .env file in project root echo "NEWS_API_KEY=YOUR_ACTUAL_API_KEY_HERE" > .env
-
Update your app.py Replace the demo data function with live API calls:
import requests import os from dotenv import load_dotenv load_dotenv() API_KEY = os.getenv('NEWS_API_KEY') def get_news_articles(category='general', query=None): if not API_KEY: return get_sample_articles() # Fallback to demo data url = 'https://newsapi.org/v2/top-headlines' params = { 'apiKey': API_KEY, 'country': 'us', 'pageSize': 20 } if category and category != 'all': params['category'] = category if query: params['q'] = query try: response = requests.get(url, params=params) response.raise_for_status() return response.json().get('articles', []) except requests.RequestException: return get_sample_articles() # Fallback to demo on error
-
Install additional dependency
pip install requests python-dotenv
-
Restart your application
python app.py
- Never commit your API key to version control
- Keep your
.env
file private and add it to.gitignore
- Use environment variables in production deployments
- The app automatically falls back to demo data if API calls fail
flask-news-website/
βββ π± Core Application
β βββ app.py # Main Flask application with routes
β βββ requirements.txt # Python dependencies
β βββ gunicorn.conf.py # Production server configuration
β
βββ π§ Configuration
β βββ .env.example # Environment variables template
β βββ .gitignore # Git exclusion rules
β βββ verify_deployment.py # Deployment verification script
β
βββ π Deployment
β βββ deploy.sh # Linux/Mac deployment script
β βββ deploy.bat # Windows deployment script
β βββ PRODUCTION_CHECKLIST.md # Production deployment guide
β
βββ π¨ Frontend
β βββ templates/ # Jinja2 HTML templates
β β βββ base.html # Base template with navigation
β β βββ index.html # Homepage
β β βββ news.html # News listing page
β β βββ about.html # About page
β β βββ contact.html # Contact form
β β βββ 404.html # Error page
β β
β βββ static/ # Static assets
β βββ css/
β β βββ style.css # Modern CSS with dark theme
β βββ js/
β βββ main.js # Core JavaScript functionality
β βββ image-utils.js # Image optimization utilities
β
βββ πΈ Documentation
βββ README.md # This file
βββ screenshots/ # Website screenshots
# Install production dependencies
pip install -r requirements.txt
# Run with Gunicorn
gunicorn -c gunicorn.conf.py app:app
export SECRET_KEY="your-super-secret-key"
export FLASK_ENV="production"
export FLASK_DEBUG="False"
export PORT="5000"
Create a Dockerfile
:
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 5000
CMD ["gunicorn", "-c", "gunicorn.conf.py", "app:app"]
Build and run:
docker build -t flask-news-website .
docker run -p 5000:5000 flask-news-website
Platform | Configuration | Notes |
---|---|---|
Heroku | Procfile : web: gunicorn app:app |
Simple git-based deployment |
Railway | Auto-deploy from Git | Automatic deployments from GitHub |
DigitalOcean App Platform | App spec configuration | Container-based deployment |
Vercel | vercel.json configuration |
Serverless deployment |
Netlify | Build configuration | Static site hosting |
- Flask 2.3.3 - Lightweight WSGI web application framework
- Python 3.7+ - Programming language
- Gunicorn - WSGI HTTP Server for UNIX
- Jinja2 - Template engine for Python
- HTML5 - Semantic markup
- CSS3 - Modern styling with CSS Grid and Flexbox
- JavaScript (ES6+) - Modern JavaScript features
- Bootstrap 5.3.0 - CSS framework for responsive design
- Font Awesome 6.4.0 - Icon library
- Google Fonts - Inter & Poppins typography
- Demo Data - Self-contained sample news articles
- Responsive Design - Mobile-first approach
- Modern UI/UX - Dark theme with glassmorphism effects
Edit static/css/style.css
:
:root {
--primary-color: #6366f1; /* Primary brand color */
--bg-primary: #0f0f23; /* Dark background */
--bg-secondary: #1a1a2e; /* Secondary background */
--text-primary: #e2e8f0; /* Primary text color */
--text-secondary: #94a3b8; /* Secondary text color */
}
Edit app.py
in the /news
route:
categories = [
{'value': 'technology', 'label': 'Technology'},
{'value': 'business', 'label': 'Business'},
{'value': 'sports', 'label': 'Sports'},
{'value': 'health', 'label': 'Health'},
# Add your custom categories here
{'value': 'science', 'label': 'Science'},
]
Change the default country in app.py
:
# Change from 'us' to your preferred country code
country = request.args.get('country', 'gb') # UK news
- β Environment Variables - API keys stored securely
- β Input Validation - XSS and injection protection
- β Security Headers - HSTS, XSS Protection, Content Security
- β Rate Limiting - API call optimization
- β Error Handling - No sensitive data in error messages
- β CSRF Protection - Built-in Flask protection
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
Strict-Transport-Security: max-age=31536000; includeSubDomains
Device | Screen Size | Columns | Features |
---|---|---|---|
Mobile | 320px - 480px | 1 | Stack layout, full-width cards |
Tablet | 481px - 768px | 2 | Responsive grid, touch-friendly |
Desktop | 769px - 1200px | 3 | Optimized grid layout |
Large Desktop | 1200px+ | 4 | Maximum content width |
- π± Mobile Navigation - Collapsible hamburger menu
- π Adaptive Search - Full-width on mobile, compact on desktop
- πΌοΈ Responsive Images - Optimized loading and display
- π Flexible Typography - Scalable font sizes
- π― Touch Targets - Minimum 44px touch targets for mobile
- π API Caching - 5-minute response cache reduces API calls
- πΌοΈ Lazy Loading - Images load on scroll for faster initial load
- π¦ Asset Optimization - Minified CSS and JavaScript
- π HTTP/2 Ready - Modern web standards support
- π Performance Monitoring - Built-in performance tracking
- Page Load Time: < 3 seconds
- Mobile Performance: 90+ Lighthouse score
- API Response: < 2 seconds (cached: < 100ms)
- Memory Usage: < 100MB per worker
- All routes load correctly (/, /news, /about, /contact)
- News articles fetch and display properly
- Category filtering works
- Search functionality operates correctly
- Contact form validates and submits
- Responsive design works on all devices
- Error pages display correctly (404, 500)
Run the verification script:
python verify_deployment.py
We welcome contributions! Here's how to get started:
- Fork the repository
- Create a feature branch
git checkout -b feature/amazing-feature
- Set up development environment
cp .env.example .env # Add your own API key for testing
- Make your changes
- Test thoroughly
- Commit your changes
git commit -m 'Add amazing feature'
- Push to the branch
git push origin feature/amazing-feature
- Open a Pull Request
- Follow PEP 8 style guidelines for Python
- Use semantic commit messages
- Add comments for complex logic
- Test on multiple devices/browsers
- Update documentation as needed
- π Internationalization (i18n)
- π Analytics integration
- π Advanced search features
- π± PWA implementation
- π¨ Additional themes
- π§ Performance optimizations
οΏ½ App won't start
Solution:
- Ensure Python 3.7+ is installed:
python --version
- Install dependencies:
pip install -r requirements.txt
- Verify you're in the correct directory
- Check for port conflicts (default: 5000)
π° No articles showing
Solution:
- Check if the Flask app is running properly
- Verify there are no JavaScript errors in browser console
- Clear browser cache and reload
- Check that demo data is loading correctly
π± Mobile layout issues
Solution:
- Clear browser cache
- Test in different browsers
- Check viewport meta tag in templates
- Verify CSS media queries are loading
For development debugging:
# Windows
set FLASK_DEBUG=True
python app.py
# Linux/Mac
export FLASK_DEBUG=True
python app.py
- Website won't load: Check if Flask is running on port 5000
- Styling broken: Ensure Bootstrap CDN is accessible
- Search not working: Demo search filters local demo articles only
- Images not loading: Demo uses Unsplash, check internet connection
- No news loading: Verify your NewsAPI key is correct in
.env
- API errors: Check your API usage limits (70,000 requests/month free)
- SSL errors: Ensure your environment supports HTTPS requests
- Rate limiting: NewsAPI has request limits, app falls back to demo data
# Check if .env is loaded correctly (when using live API)
python -c "import os; from dotenv import load_dotenv; load_dotenv(); print('API Key loaded:', bool(os.getenv('NEWS_API_KEY')))"
This project is licensed under the MIT License - see the LICENSE file for details.
MIT License
Copyright (c) 2025 Flask News Website
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
- Flask - For the lightweight and flexible web framework
- Bootstrap - For the responsive CSS framework
- Font Awesome - For the beautiful icon library
- Google Fonts - For the modern typography (Inter & Poppins)
Need help? Here's how to get support:
- π Check the Documentation - Review this README and the troubleshooting section
- π Search Issues - Look through existing GitHub issues
- π¬ Ask Questions - Open a new issue with the "question" label
- π Report Bugs - Open an issue with the "bug" label
- π‘ Request Features - Open an issue with the "enhancement" label
- GitHub Issues: Open an issue
- Email: [email protected] (for security issues)