Professional URL shortening service with analytics, bulk operations, and enterprise features Organized as a Python package with CLI management tools
ποΈ Architecture β’ π Quick Start β’ π οΈ CLI Commands β’ π API Documentation β’ π§ͺ Development
The codebase has been reorganized into a professional Python package structure following Flask best practices:
Url_Shortner_python/
βββ π url_shortener/ # Main Python package
β βββ π __init__.py # Package initialization
β βββ π app.py # Flask application factory
β βββ π config.py # Configuration management
β βββ π models.py # Database models & operations
β βββ π services.py # Business logic & services
β βββ π routes.py # API routes & endpoints
β βββ π utils.py # Utility functions
β βββ π templates/ # Jinja2 templates
β βββ π static/ # Static files (CSS, JS)
βββ π tests/ # Test suite
β βββ π __init__.py
β βββ π unit/ # Unit tests
β βββ π test_url_shortener.py
βββ π run.py # CLI entry point
βββ π setup.py # Package setup configuration
βββ π requirements.txt # Python dependencies
βββ π README.md # This file
- URLModel: Database operations for URL shortening
- RateLimitModel: Rate limiting management
- SQLite database with optimized indexes
- Comprehensive analytics tracking
- URLService: Core URL shortening business logic
- AnalyticsService: Advanced analytics processing
- Validation, rate limiting, and error handling
- Separation of business logic from Flask
- API Routes: RESTful API endpoints under
/api/ - Web Routes: HTML templates and web interface
- Blueprint-based organization
- Comprehensive error handling
- DevelopmentConfig: Development environment settings
- ProductionConfig: Production environment settings
- TestingConfig: Testing environment settings
- Environment-based configuration management
- create_app(): Flask application factory pattern
- Blueprint registration
- Logging configuration
- Service initialization
-
Clone and setup
git clone https://github.com/GrandmaEJ/api.git cd Url_Shortner_python -
Install dependencies
# Using pip pip install -r requirements.txt # Or using uv (recommended) uv add flask validators click
-
Initialize database
python run.py init-db
-
Start the server
python run.py run
-
Access the application
- π Web Interface:
http://localhost:8398 - π API Base:
http://localhost:8398/api - π Health Check:
http://localhost:8398/health
- π Web Interface:
The application provides comprehensive CLI management commands:
# Start development server
python run.py run
# Start with custom options
python run.py run --host 0.0.0.0 --port 5000 --debug
# Use specific configuration
python run.py run --config production# Initialize database
python run.py init-db
# Clean up expired URLs
python run.py cleanup-expired# Run test suite
python run.py test# View all available commands
python run.py --help
# View specific command help
python run.py run --help- Base URL:
http://localhost:8398 - API Version:
v2.0 - Content-Type:
application/json
POST /api/short
Content-Type: application/json
{
"url": "https://example.com/very/long/url",
"custom_id": "mycustom", # Optional
"title": "My Website", # Optional
"description": "Main website", # Optional
"expiry_days": 30 # Optional (default: 30)
}POST /api/urls/bulk
Content-Type: application/json
{
"urls": [
"https://example.com",
{"url": "https://google.com", "custom_id": "google"},
{"url": "https://github.com", "title": "GitHub"}
]
}GET /api/urls/<short_id>/analyticsGET /api/urls?limit=50&offset=0GET /<short_id> # Redirects to original URLGET /health
Response: {"status": "healthy", "version": "2.0.0"}GET /api/version
Response: {"version": "2.0.0", "status": "active"}- Navigate to
http://localhost:8398 - Enter your long URL
- Optionally add custom ID, title, and description
- Click "Shorten URL"
- View result with copy and preview options
# Create short URL
curl -X POST http://localhost:8398/api/short \
-H "Content-Type: application/json" \
-d '{"url": "https://example.com", "custom_id": "example"}'
# Bulk creation
curl -X POST http://localhost:8398/api/urls/bulk \
-H "Content-Type: application/json" \
-d '{"urls": ["https://site1.com", "https://site2.com"]}'import requests
# Create short URL
response = requests.post('http://localhost:8398/api/short', json={
'url': 'https://www.python.org/',
'custom_id': 'python',
'title': 'Python Official'
})
data = response.json()
print(f"Short link: {data['short_link']}")The application includes a comprehensive test suite:
# Run all tests
python run.py test
# Run specific test file
python -m pytest tests/unit/test_url_shortener.py -v-
Clone repository
git clone <repository-url> cd Url_Shortner_python
-
Setup virtual environment
# Using venv python -m venv venv source venv/bin/activate # Linux/Mac # or venv\Scripts\activate # Windows # Using uv (recommended) uv venv source .venv/bin/activate
-
Install dependencies
pip install -r requirements.txt # or uv add flask validators click -
Run tests
python run.py test
# Install in development mode
pip install -e .
# Install with development dependencies
pip install -e ".[dev]"# Install package
pip install url-shortener-v2
# Use CLI commands
url-shortener run --port 5000# Database
DATABASE_PATH=url_shortener_v2.db
# Security
SECRET_KEY=your-secret-key
ADMIN_KEY=your-admin-key
# URLs
BASE_URL=https://your-domain.com
DEFAULT_EXPIRY_DAYS=30
# Rate Limiting
RATE_LIMIT_ENABLED=true
RATE_LIMIT_DEFAULT_REQUESTS=30
RATE_LIMIT_BULK_REQUESTS=10
# Logging
LOG_LEVEL=INFO
LOG_FILE=url_shortener_v2.log# Default configuration
DATABASE_PATH=url_shortener_v2.db
BASE_URL=http://localhost:8398
DEBUG=True
RATE_LIMIT_ENABLED=True# Production configuration
SECRET_KEY=os.environ.get('SECRET_KEY')
BASE_URL=https://your-domain.com
DEBUG=False
RATE_LIMIT_ENABLED=True
RATE_LIMIT_DEFAULT_REQUESTS=20- π Smart URL Shortening - Auto-generate or custom short URLs
- π Real-time Analytics - Click tracking, browser analysis, referrer tracking
- β‘ Bulk Operations - Shorten multiple URLs simultaneously
- π‘οΈ Rate Limiting - Built-in request throttling
- π― Custom Metadata - Support for titles, descriptions, and expiry
- π Auto-cleanup - Automatic expired URL management
- π Application Factory - Flask factory pattern for scalability
- π¦ Python Package - Professional package structure
- π§ CLI Tools - Comprehensive management commands
- π§ͺ Test Suite - Unit tests with pytest
- π Configuration - Environment-based configuration
- π Documentation - Comprehensive API documentation
- π¨ Modern UI - Responsive web interface
- URL Validation - Strict URL format and safety checking
- Rate Limiting - Per-IP request throttling
- Input Sanitization - XSS and injection prevention
- Secure Headers - Security-focused HTTP headers
- Admin Protection - Protected admin endpoints
FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
EXPOSE 8398
CMD ["python", "run.py", "run", "--config", "production"][Unit]
Description=URL Shortener v2.0
After=network.target
[Service]
User=www-data
Group=www-data
WorkingDirectory=/opt/url-shortener
ExecStart=/opt/url-shortener/venv/bin/python run.py run --config production
Restart=always
[Install]
WantedBy=multi-user.target# Production environment
export FLASK_ENV=production
export DATABASE_PATH=/var/lib/url-shortener/url_shortener_v2.db
export BASE_URL=https://your-domain.com
export SECRET_KEY=your-production-secret-key
# Run with production config
python run.py run --config production# Reset database
rm url_shortener_v2.db
python run.py init-db
# Check database
python run.py cleanup-expired# Fix permissions
chmod +x run.py
chmod 664 *.db *.log# Use different port
python run.py run --port 8399# Enable debug logging
export LOG_LEVEL=DEBUG
python run.py run --debug# Check application health
curl http://localhost:8398/health
# Check API version
curl http://localhost:8398/api/version
# Test database
python run.py init-dbpip install url-shortener-v2git clone <repository>
cd Url_Shortner_python
pip install -e .# Available commands
url-shortener run
url-shortener test
url-shortener init-db
url-shortener cleanup-expired- Fork the repository
- Create feature branch:
git checkout -b feature-name - Make changes and add tests
- Run test suite:
python run.py test - Submit pull request
- Python: Follow PEP 8
- Testing: Add tests for new features
- Documentation: Update README and docstrings
- Architecture: Maintain separation of concerns
- Include comprehensive tests
- Update documentation
- Follow existing code style
- Add changelog entry
This project is licensed under the MIT License - see the LICENSE file for details.
- π§ Issues: GitHub Issues
- π¬ Discussions: GitHub Discussions
- π Wiki: Project Wiki
- β Star this repository
- π Report bugs via GitHub Issues
- π‘ Suggest features via GitHub Discussions
- π€ Contribute by submitting pull requests
ποΈ Professional Python Package β’ π Enterprise Features β’ π οΈ CLI Management
Made with β€οΈ using Python, Flask, and SQLite
π― URL Shortener v2.0 - Now as a Professional Python Package!