Flask @app.route behaviour in Python 3.11 / 3.12 behaves differently on different instances

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.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa

Flask @app.route behaviour in Python 3.11 / 3.12 behaves differently on different instances

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.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật