On the remote server the app behaviour of the route is that it treats all urls as short urls instead of treating the specified /stats and /login as their respective site. It also treats actual short urls as they are expired.
Due to a error in the CloudLinux repo that my host uses i had to degrade from 3.12 to 3.11 on the server, though i have 3.12 on my local machine locally everything work as expected.
Full code of the main python file.
from flask import Flask, request, redirect, render_template, url_for, flash
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
from flask_wtf import FlaskForm, CSRFProtect
from wtforms import StringField, PasswordField
from wtforms.validators import DataRequired
from datetime import datetime
import connect_db
import os
import secrets
# Load environment variables
from dotenv import load_dotenv
load_dotenv()
# Create a secret key
secret_key = secrets.token_urlsafe(16)
# Flask app configuration
app = Flask(__name__)
csrf = CSRFProtect(app)
app.secret_key = secret_key
# Flask-Login configuration
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
# Form for login
class LoginForm(FlaskForm):
username = StringField('Username', validators=[DataRequired()])
password = PasswordField('Password', validators=[DataRequired()])
# User class
class User(UserMixin):
def __init__(self, id):
self.id = id
# User loader function
@login_manager.user_loader
def load_user(user_id):
return User(user_id)
# Fetch data function
def fetch_data():
conn, cursor = connect_db.connect_to_database()
cursor.execute(
"SELECT id, original_url, short_url, uses, max_uses, created_at, expiration_date FROM urls",
)
data = cursor.fetchall()
connect_db.close_connection(conn, cursor)
return data
# Main page for the URL shortener
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
original_url = request.form['original_url']
custom_short_url = request.form.get('custom_short_url')
expiration_date = request.form.get('expiration_date')
max_uses = request.form.get('max_uses')
conn, cursor = connect_db.connect_to_database()
cursor.execute(
"INSERT INTO urls (original_url, short_url, expiration_date, max_uses) VALUES (%s, %s, %s, %s)",
(original_url, custom_short_url, expiration_date, max_uses)
)
conn.commit()
connect_db.close_connection(conn, cursor)
return redirect(url_for('index'))
return render_template('index.html')
# Login route
@app.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
username = form.username.data
password = form.password.data
# Replace with your own user validation logic
if username == os.getenv('LOGIN_USERNAME') and password == os.getenv('LOGIN_PASSWORD'):
user = User(id=1)
login_user(user)
return redirect(url_for('index'))
else:
flash('Invalid credentials')
return render_template('login.html', form=form)
# Logout route
@app.route('/logout')
@login_required
def logout():
logout_user()
return redirect(url_for('login'))
# Display statistics of all URLs in the database
@app.route('/stats')
@login_required
def stats():
data = fetch_data()
return render_template('stats.html', urls=data)
@app.route('/<short_url>')
def redirect_to_original(short_url):
predefined_routes = ['login', 'logout', 'stats', 'index']
# Check if the short_url matches any predefined route
if short_url in predefined_routes:
return "URL not found", 404
# Fetch the corresponding original URL from the database
conn, cursor = connect_db.connect_to_database()
cursor.execute(
"SELECT original_url, expiration_date, uses, max_uses FROM urls WHERE short_url = %s",
(short_url,)
)
result = cursor.fetchone()
connect_db.close_connection(conn, cursor)
if result:
original_url, expiration_date, uses, max_uses = result
# Check if expiration_date exists and convert to a datetime object if necessary
if expiration_date:
if isinstance(expiration_date, str):
# Parse string to datetime if needed
expiration_date = datetime.strptime(expiration_date, '%Y-%m-%d %H:%M:%S')
# Compare expiration date to current date
if expiration_date.date() < datetime.now().date():
return "URL expired", 410 # 410 Gone for expired URLs
# Check max uses limit
if max_uses is not None and max_uses != 0 and uses >= max_uses:
return "Max uses reached", 410
# Increment uses count and redirect to the original URL
conn, cursor = connect_db.connect_to_database()
cursor.execute(
"UPDATE urls SET uses = uses + 1 WHERE short_url = %s",
(short_url,)
)
conn.commit()
connect_db.close_connection(conn, cursor)
return redirect(original_url)
# If no result is found, return a 404
return "URL not found", 404
if __name__ == '__main__':
app.run(debug=False)
When using it on a local server on my own machine with 3.12 it works just as expected. But when its setup on the remote server on my host it treats all links as expired short-urls.