예제 #1
0
def memory_repo():
    repo = memory_repository.MemoryRepository()
    movie_1 = Movie("Movie1", 2000)
    movie_2 = Movie("Movie2", 2001)
    movie_3 = Movie("Movie3", 2002)
    movie_4 = Movie("Movie4", 2003)
    movie_5 = Movie("Movie5", 2004)
    repo.add_movie(movie_1)
    repo.add_movie(movie_2)
    repo.add_movie(movie_3)
    repo.add_movie(movie_4)
    repo.add_movie(movie_5)
    return repo
예제 #2
0
def memory_repo():
    repo = memory_repository.MemoryRepository()
    movie_1 = Movie('Movie1', 2000)
    movie_2 = Movie('Movie2', 2001)
    movie_3 = Movie('Movie3', 2002)
    movie_4 = Movie('Movie4', 2003)
    movie_5 = Movie('Movie5', 2004)
    actor1 = Actor('Actor1')
    actor2 = Actor('Actor2')
    actor3 = Actor('Actor3')
    actor4 = Actor('Actor4')
    actor5 = Actor('Actor5')
    director1 = Director('Director1')
    director2 = Director('Director2')
    movie_1.add_actor(actor1)
    movie_1.add_actor(actor2)
    movie_1.add_actor(actor4)
    movie_1.add_actor(actor5)
    movie_2.add_actor(actor2)
    movie_2.add_actor(actor4)
    movie_2.add_actor(actor5)
    movie_3.add_actor(actor3)
    movie_3.add_actor(actor5)
    movie_4.add_actor(actor3)
    movie_4.add_actor(actor4)
    movie_4.add_actor(actor5)
    movie_5.add_actor(actor3)
    movie_5.add_actor(actor4)
    movie_5.add_actor(actor5)
    movie_1.director = director1
    movie_2.director = director1
    movie_3.director = director1
    movie_4.director = director2
    movie_5.director = director2
    genre1 = Genre('Genre1')
    genre2 = Genre('Genre2')
    movie_1.add_genre(genre1)
    movie_2.add_genre(genre2)
    movie_3.add_genre(genre1)
    movie_4.add_genre(genre2)
    movie_5.add_genre(genre1)
    repo.add_movie(movie_1)
    repo.add_movie(movie_2)
    repo.add_movie(movie_3)
    repo.add_movie(movie_4)
    repo.add_movie(movie_5)

    user = User(username='******', password='******')
    repo.add_user(user)
    return repo
def create_app(test_config=None):
    """Construct the core application."""

    # Create the Flask app object.
    app = Flask(__name__)

    # Configure the app from configuration-file settings.
    app.config.from_object('config.Config')
    data_path = os.path.join('movie', 'adapters', 'data')
    if test_config is not None:
        # Load test configuration, and override any configuration settings.
        app.config.from_mapping(test_config)
        data_path = app.config['TEST_DATA_PATH']

    # Here the "magic" of our repository pattern happens. We can easily switch between in memory data and
    # persistent database data storage for our application.

    if app.config['REPOSITORY'] == 'memory':
        # Create the MemoryRepository instance for a memory-based repository.
        repo.repo_instance = memory_repository.MemoryRepository()
        memory_repository.populate(data_path, repo.repo_instance)

    elif app.config['REPOSITORY'] == 'database':
        # Configure database.
        database_uri = app.config['SQLALCHEMY_DATABASE_URI']

        # We create a comparatively simple SQLite database, which is based on a single file (see .env for URI).
        # For example the file database could be located locally and relative to the application in covid-19.db,
        # leading to a URI of "sqlite:///movie.db".
        # Note that create_engine does not establish any actual DB connection directly!
        database_echo = app.config['SQLALCHEMY_ECHO']
        database_engine = create_engine(
            database_uri,
            connect_args={"check_same_thread": False},
            poolclass=NullPool,
            echo=database_echo)

        if app.config['TESTING'] == 'True' or len(
                database_engine.table_names()) == 0:
            print("REPOPULATING DATABASE")
            # For testing, or first-time use of the web application, reinitialise the database.
            clear_mappers()
            metadata.create_all(
                database_engine)  # Conditionally create database tables.
            for table in reversed(metadata.sorted_tables
                                  ):  # Remove any data from the tables.
                database_engine.execute(table.delete())

            # Generate mappings that map domain model classes to the database tables.
            map_model_to_tables()

            database_repository.populate(database_engine, data_path)

        else:
            # Solely generate mappings that map domain model classes to the database tables.
            map_model_to_tables()

        # Create the database session factory using sessionmaker (this has to be done once, in a global manner)
        session_factory = sessionmaker(autocommit=False,
                                       autoflush=True,
                                       bind=database_engine)
        # Create the SQLAlchemy DatabaseRepository instance for an sqlite3-based repository.
        repo.repo_instance = database_repository.SqlAlchemyRepository(
            session_factory)

    # Build the application - these steps require an application context.
    with app.app_context():

        # Register blueprints.
        from .home import home
        app.register_blueprint(home.home_blueprint)

        from .movies import movies
        app.register_blueprint(movies.movies_blueprint)

        from .authentication import authentication
        app.register_blueprint(authentication.authentication_blueprint)

        from .utilities import utilities
        app.register_blueprint(utilities.utilities_blueprint)

        # Register a callback the makes sure that database sessions are associated with http requests
        # We reset the session inside the database repository before a new flask request is generated
        @app.before_request
        def before_flask_http_request_function():
            if isinstance(repo.repo_instance,
                          database_repository.SqlAlchemyRepository):
                repo.repo_instance.reset_session()

        # Register a tear-down method that will be called after each request has been processed.
        @app.teardown_appcontext
        def shutdown_session(exception=None):
            if isinstance(repo.repo_instance,
                          database_repository.SqlAlchemyRepository):
                repo.repo_instance.close_session()

    return app
예제 #4
0
def create_app(test_config=None):
    """ Construct the core application. """

    # Create the Flask app object.
    app = Flask(__name__)

    # Configure the app from configuration-file settings.
    app.config.from_object('config.Config')

    is_dev = app.config['FLASK_ENV'] == 'development'

    if not is_dev:
        app.config.from_object('config.HerokuProductionConfig')

    data_path = os.path.join('movie', 'adapters', 'data', 'Data1000Movies.csv')

    if test_config is not None:
        # Load test configuration, and override any configuration settings.
        app.config.from_mapping(test_config)
        data_path = app.config['TEST_DATA_PATH']

    # Setup our repository
    repo: Union[memory_repository.MemoryRepository,
                database_repository.SqlAlchemyRepository, None] = None
    repository = app.config['REPOSITORY']

    max_num_lines = app.config['MAX_LINES_TO_LOAD']

    if repository == 'memory':
        # Create the MemoryRepository implementation for a memory-based repository.
        repo = memory_repository.MemoryRepository()
        populate(repo,
                 data_path,
                 123,
                 simulate_activity=is_dev,
                 max_num_lines=max_num_lines)

    elif repository == 'database':
        # Configure database.
        database_uri = app.config['SQLALCHEMY_DATABASE_URI']

        database_echo = app.config['SQLALCHEMY_ECHO']
        database_engine = create_engine(
            database_uri,
            # connect_args={"check_same_thread": False},
            # poolclass=NullPool,
            echo=database_echo)

        is_testing_or_init = app.config['TESTING'] is True or len(
            database_engine.table_names()) == 0

        if is_testing_or_init:
            # For testing, or first-time use of the web application, reinitialise the database.
            clear_mappers()
            metadata.create_all(
                database_engine)  # Conditionally create database tables.
            for table in reversed(metadata.sorted_tables
                                  ):  # Remove any data from the tables.
                database_engine.execute(table.delete())

        # Generate mappings that map domain model classes to the database tables.
        map_model_to_tables()

        # Create the database session factory using sessionmaker (this has to be done once, in a global manner)
        session_factory = sessionmaker(autocommit=False,
                                       autoflush=True,
                                       bind=database_engine)

        # Create the SQLAlchemy DatabaseRepository instance for an sqlite3-based repository.
        repo = database_repository.SqlAlchemyRepository(session_factory)

        if is_testing_or_init:
            print(
                "-----------------------------------------------------------")
            print(
                "------------------ REPOPULATING DATABASE ------------------")
            print(
                "-----------------------------------------------------------")

            populate(repo,
                     data_path,
                     123,
                     simulate_activity=is_dev,
                     max_num_lines=max_num_lines)
    else:
        raise ValueError(
            f"Invalid repository '{repository}', should be 'memory' or 'database'"
        )

    app.config['REPOSITORY'] = repo

    # Build the application - these steps require an application context.
    with app.app_context():
        # Register blueprints.
        from .home import home
        app.register_blueprint(home.home_blueprint)

        from .search import search
        app.register_blueprint(search.search_blueprint)

        from .movie import movie
        app.register_blueprint(movie.movie_blueprint)

        from .auth import auth
        app.register_blueprint(auth.auth_blueprint)

        from .watchlist import watchlist
        app.register_blueprint(watchlist.watchlist_blueprint)

        from .user import user
        app.register_blueprint(user.user_blueprint)

        from .utilities import utilities
        app.register_blueprint(utilities.utilities_blueprint)

        app.register_error_handler(404, page_not_found)

        if isinstance(repo, database_repository.SqlAlchemyRepository):
            # Register a callback that associates database sessions with http requests
            # Sessions are reset inside the database repository before a new flask request is generated
            @app.before_request
            def before_flask_http_request_function():
                repo.reset_session()

            # Register a tear-down method that will be called after each request has been processed
            @app.teardown_appcontext
            def shutdown_session(exception=None):
                repo.close_session()

    cache.init_app(app)
    return app