Skip to content

Commit

Permalink
fix: Fixes dynamic loading of blueprints
Browse files Browse the repository at this point in the history
  • Loading branch information
drorganvidez committed Feb 19, 2024
1 parent 4e57f6e commit d07471f
Show file tree
Hide file tree
Showing 32 changed files with 69 additions and 71 deletions.
56 changes: 33 additions & 23 deletions app/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
from flask_sqlalchemy import SQLAlchemy
from dotenv import load_dotenv
from flask_migrate import Migrate
from flask_wtf import CSRFProtect

# Load environment variables
load_dotenv()
Expand Down Expand Up @@ -41,24 +40,9 @@ def create_app(config_name=None):
db.init_app(app)
migrate.init_app(app, db)

# Automatically scan and register blueprints
blueprints_directory = app.root_path
excluded_folders = {'static', 'templates', 'tests'}

for folder_name in os.listdir(blueprints_directory):
folder_path = os.path.join(blueprints_directory, folder_name)
if os.path.isdir(folder_path) and folder_name not in excluded_folders:
for filename in os.listdir(folder_path):
if filename.endswith('.py') and not filename.startswith('__'):
module_name = filename[:-3]
module_path = os.path.join(folder_path, filename)
spec = importlib.util.spec_from_file_location(module_name, module_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
for item_name in dir(module):
item = getattr(module, item_name)
if isinstance(item, Blueprint):
app.register_blueprint(item)
# Register blueprints
register_blueprints(app)
print_registered_blueprints(app)

from flask_login import LoginManager
login_manager = LoginManager()
Expand All @@ -67,7 +51,7 @@ def create_app(config_name=None):

@login_manager.user_loader
def load_user(user_id):
from app.auth.models import User
from app.blueprints.auth import User
return User.query.get(int(user_id))

# Logging
Expand Down Expand Up @@ -121,7 +105,7 @@ def upload_folder_name():

def get_user_by_token(token):
# TODO
from app.auth.models import User
from app.blueprints.auth import User
return User.query.first()


Expand All @@ -132,15 +116,41 @@ def get_authenticated_user_profile():


def datasets_counter() -> int:
from app.dataset.models import DataSet
from app.blueprints.dataset.models import DataSet
count = DataSet.query.count()
return count


def feature_models_counter() -> int:
from app.dataset.models import FeatureModel
from app.blueprints.dataset.models import FeatureModel
count = FeatureModel.query.count()
return count


def register_blueprints(app):
app.blueprint_url_prefixes = {}
base_dir = os.path.abspath(os.path.dirname(__file__))
blueprints_dir = os.path.join(base_dir, 'blueprints')
for blueprint_name in os.listdir(blueprints_dir):
blueprint_path = os.path.join(blueprints_dir, blueprint_name)
if os.path.isdir(blueprint_path) and not blueprint_name.startswith('__'):
try:
routes_module = importlib.import_module(f'app.blueprints.{blueprint_name}.routes')
for item in dir(routes_module):
if isinstance(getattr(routes_module, item), Blueprint):
blueprint = getattr(routes_module, item)
url_prefix = f'/{blueprint_name if blueprint_name != "public" else ""}'
app.register_blueprint(blueprint, url_prefix=url_prefix)
app.blueprint_url_prefixes[blueprint.name] = url_prefix
except ModuleNotFoundError as e:
print(f"Could not load the module for Blueprint '{blueprint_name}': {e}")


def print_registered_blueprints(app):
print("Registered blueprints")
for name, blueprint in app.blueprints.items():
url_prefix = app.blueprint_url_prefixes.get(name, 'No URL prefix set')
print(f"Name: {name}, URL prefix: {url_prefix}")


app = create_app()
Empty file added app/blueprints/__init__.py
Empty file.
File renamed without changes.
File renamed without changes.
File renamed without changes.
13 changes: 6 additions & 7 deletions app/auth/routes.py → app/blueprints/auth/routes.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
from flask import (render_template, redirect, url_for,
request, current_app)
from flask import (render_template, redirect, url_for)
from flask_login import current_user, login_user, logout_user

from app.auth import auth_bp
from app.auth.forms import SignupForm, LoginForm
from app.blueprints.auth import auth_bp
from app.blueprints.auth.forms import SignupForm, LoginForm

from app.profile.models import UserProfile
from app.blueprints.profile.models import UserProfile


@auth_bp.route("/signup/", methods=["GET", "POST"])
Expand All @@ -20,7 +19,7 @@ def show_signup_form():
email = form.email.data
password = form.password.data

from app.auth.models import User
from app.blueprints.auth.models import User
user = User.get_by_email(email)
if user is not None:
error = f'Email {email} in use'
Expand All @@ -47,7 +46,7 @@ def login():
return redirect(url_for('public.index'))
form = LoginForm()
if form.validate_on_submit():
from app.auth.models import User
from app.blueprints.auth.models import User
user = User.get_by_email(form.email.data)

if user is not None and user.check_password(form.password.data):
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
3 changes: 1 addition & 2 deletions app/dataset/forms.py → app/blueprints/dataset/forms.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
from flask_wtf import FlaskForm
from wtforms import StringField, SelectField, FieldList, FormField, SubmitField, TextAreaField
from wtforms.validators import DataRequired, URL, Optional
from enum import Enum

from app.dataset.models import PublicationType
from app.blueprints.dataset.models import PublicationType


class AuthorForm(FlaskForm):
Expand Down
File renamed without changes.
16 changes: 6 additions & 10 deletions app/dataset/routes.py → app/blueprints/dataset/routes.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import io
import logging
import os
import json
Expand All @@ -11,19 +10,16 @@
from typing import List
from zipfile import ZipFile

from flask import flash, redirect, render_template, url_for, request, jsonify, send_file, send_from_directory, abort, \
current_app, make_response
from flask import render_template, request, jsonify, send_from_directory, current_app, make_response
from flask_login import login_required, current_user
from werkzeug.utils import secure_filename

import app
from app.dataset.forms import DataSetForm
from app.dataset.models import DataSet, DSMetrics, FeatureModel, File, FMMetaData, FMMetrics, DSMetaData, Author, \
from app.blueprints.dataset.forms import DataSetForm
from app.blueprints.dataset.models import DataSet, FeatureModel, File, FMMetaData, DSMetaData, Author, \
PublicationType, DSDownloadRecord, DSViewRecord, FileDownloadRecord
from app.dataset import dataset_bp
from app.auth.models import User
from app.flama import flamapy_valid_model
from app.zenodo import zenodo_create_new_deposition, test_zenodo_connection, zenodo_upload_file, \
from app.blueprints.dataset import dataset_bp
from app.blueprints.auth.models import User
from app.zenodo import zenodo_create_new_deposition, zenodo_upload_file, \
zenodo_publish_deposition, zenodo_get_doi, test_full_zenodo_connection


Expand Down
File renamed without changes.
File renamed without changes.
10 changes: 5 additions & 5 deletions app/explore/routes.py → app/blueprints/explore/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@

import unidecode

from flask import render_template, request, abort, jsonify
from sqlalchemy import or_, desc, asc, any_
from flask import render_template, request, jsonify
from sqlalchemy import or_, any_

from app.explore import explore_bp
from app.explore.forms import ExploreForm
from app.dataset.models import DataSet, DSMetaData, Author, FeatureModel, FMMetaData, PublicationType
from app.blueprints.explore import explore_bp
from app.blueprints.explore.forms import ExploreForm
from app.blueprints.dataset.models import DataSet, DSMetaData, Author, FeatureModel, FMMetaData, PublicationType


@explore_bp.route('/explore', methods=['GET', 'POST'])
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
7 changes: 3 additions & 4 deletions app/profile/routes.py → app/blueprints/profile/routes.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
from flask import request, render_template, flash, redirect, url_for
from flask import request, render_template, flash
from flask_login import login_required

from app.profile import profile_bp
from app.profile.forms import UserProfileForm
from app.blueprints.profile import profile_bp
from app.blueprints.profile.forms import UserProfileForm

from app.profile.models import UserProfile
from app import get_authenticated_user_profile


Expand Down
File renamed without changes.
7 changes: 3 additions & 4 deletions app/public/__init__.py → app/blueprints/public/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from flask import Blueprint

public_bp = Blueprint('public', __name__, template_folder='templates')

from flask import Blueprint

public_bp = Blueprint('public', __name__, template_folder='templates')
7 changes: 3 additions & 4 deletions app/public/routes.py → app/blueprints/public/routes.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import logging
import app

from flask import request, current_app, render_template

from app.public import public_bp
from app.dataset.models import DataSet, DSMetaData
from flask import request, current_app, render_template, Blueprint
from app.blueprints.public import public_bp
from ..dataset.models import DataSet, DSMetaData

logger = logging.getLogger(__name__)

Expand Down
File renamed without changes.
File renamed without changes.
8 changes: 8 additions & 0 deletions app/blueprints/team/routes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from flask import render_template

from app.blueprints.team import team_bp


@team_bp.route('/team', methods=['GET'])
def index():
return render_template('team/index.html')
File renamed without changes.
9 changes: 0 additions & 9 deletions app/team/routes.py

This file was deleted.

4 changes: 1 addition & 3 deletions app/zenodo.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
"""

import os
from typing import Tuple, List

import requests

Expand All @@ -12,7 +11,7 @@
from flask_login import current_user

import app
from app.dataset.models import DataSet, FeatureModel
from app.blueprints.dataset.models import DataSet, FeatureModel

load_dotenv()

Expand Down Expand Up @@ -156,7 +155,6 @@ def zenodo_upload_file(deposition_id: int, feature_model: FeatureModel, user=Non
Returns:
dict: The response in JSON format with the details of the uploaded file.
"""
from app.auth.models import User
uvl_filename = feature_model.fm_meta_data.uvl_filename
data = {'name': uvl_filename}
user_id = current_user.id if user is None else user.id
Expand Down

0 comments on commit d07471f

Please sign in to comment.