mrs_plugin/content_sets.py
def add_content_set(content_dir=None, service_id=None, **kwargs):
    """Adds content to the given MRS service

    Args:
        content_dir (str): The path to the content directory
        service_id (int): The id of the service the schema should be added to
        **kwargs: Additional options

    Keyword Args:
        request_path (str): The request_path
        requires_auth (bool): Whether authentication is required to access
            the content
        comments (str): Comments about the content
        session (object): The database session to use.
        interactive (bool): Indicates whether to execute in interactive mode
        raise_exceptions (bool): If set to true exceptions are raised

    Returns:
        None in interactive mode, a dict with content_set_id and
            number_of_files_uploaded
    """

    import os

    request_path = kwargs.get("request_path")
    requires_auth = kwargs.get("requires_auth")
    comments = kwargs.get("comments")
    session = kwargs.get("session")
    interactive = kwargs.get("interactive", core.get_interactive_default())
    raise_exceptions = kwargs.get("raise_exceptions", not interactive)

    try:
        session = core.get_current_session(session)

        service = mrs_services.get_service(
            service_id=service_id, auto_select_single=True,
            session=session, interactive=interactive,
            return_formatted=False)

        # Get request_path
        if not request_path and interactive:
            request_path = core.prompt(
                "Please enter the request path for this content set ["
                f"/content]: ",
                {'defaultValue': '/content'}).strip()

        if not request_path.startswith('/'):
            raise Exception("The request_path has to start with '/'.")

        core.check_request_path(
            service.get('url_host_name') + service.get('url_context_root') +
            request_path,
            session=session)

        # Get the content_dir
        if not content_dir and interactive:
            content_dir = core.prompt(
                message=('Please enter the file path to the directory '
                         'that contains the static content: '))

        if not content_dir:
            if interactive:
                raise ValueError('Operation cancelled.')
            else:
                raise ValueError('No content directory path given.')

        # Convert Unix path to Windows
        content_dir = os.path.abspath(
            os.path.expanduser(content_dir))

        # If a content_dir has been provided, check if that directory exists
        if not os.path.isdir(content_dir):
            raise ValueError(
                f"The given content directory path '{content_dir}' "
                "does not exists.")

        # Get requires_auth
        if not requires_auth:
            if interactive:
                requires_auth = core.prompt(
                    "Should the content require authentication [y/N]: ",
                    {'defaultValue': 'n'}).strip().lower() == 'y'
            else:
                requires_auth = False

        # Get comments
        if not comments and interactive:
            comments = core.prompt_for_comments()

        # Create the content_set, ensure it is created as "not enabled"
        res = session.run_sql("""
            INSERT INTO `mysql_rest_service_metadata`.`content_set`(
                service_id, request_path, requires_auth, enabled, comments)
            VALUES(?, ?, ?, ?, ?)
            """, [service.get("id"),
                  request_path,
                  1 if requires_auth else 0,
                  0,
                  comments])
        content_set_id = res.auto_increment_value

        file_list = []
        for root, dirs, files in os.walk(content_dir):
            for file in files:
                file_list.append(os.path.join(root, file))

        for file in file_list:
            # Read the file content
            with open(file, 'rb') as f:
                data = f.read()

            # Upload it to the content table
            res = session.run_sql("""
                INSERT INTO `mysql_rest_service_metadata`.`content_file`(
                    content_set_id, request_path, requires_auth, enabled,
                    content)
                VALUES(?, ?, ?, ?, ?)
                """, [content_set_id,
                      file[len(content_dir):],
                      1 if requires_auth else 0,
                      1,
                      data])

        if interactive:
            print(f"{len(file_list)} files added.")

        # Enable the content_set after all content has been uploaded
        res = session.run_sql("""
            UPDATE `mysql_rest_service_metadata`.`content_set`
            SET enabled = 1
            WHERE id = ?
            """, [content_set_id])

        if interactive:
            return "\n" + "Content added successfully."
        else:
            return {
                "content_set_id": content_set_id,
                "number_of_files_uploaded": len(file_list)
            }

    except Exception as e:
        if raise_exceptions:
            raise
        print(f"Error: {str(e)}")
Adds content to the given MRS service

    Args:
        content_dir (str): The path to the content directory
        service_id (int): The id of the service the schema should be added to
        **kwargs: Additional options

    Keyword Args:
        request_path (str): The request_path
        requires_auth (bool): Whether authentication is required to access
            the content
        comments (str): Comments about the content
        session (object): The database session to use.
        interactive (bool): Indicates whether to execute in interactive mode
        raise_exceptions (bool): If set to true exceptions are raised

    Returns:
        None in interactive mode, a dict with content_set_id and
            number_of_files_uploaded
    
Adds content to the given MRS service
Adds content to the given MRS service
def add_content_set(content_dir=None, service_id=None, **kwargs):
    import os
    request_path = kwargs.get("request_path")
    requires_auth = kwargs.get("requires_auth")
    comments = kwargs.get("comments")
    session = kwargs.get("session")
    interactive = kwargs.get("interactive", core.get_interactive_default())
    raise_exceptions = kwargs.get("raise_exceptions", not interactive)
    try:
        session = core.get_current_session(session)
        service = mrs_services.get_service(
            service_id=service_id, auto_select_single=True,
            session=session, interactive=interactive,
            return_formatted=False)
        if not request_path and interactive:
            request_path = core.prompt(
                "Please enter the request path for this content set ["
                f"/content]: ",
                {'defaultValue': '/content'}).strip()
        if not request_path.startswith('/'):
            raise Exception("The request_path has to start with '/'.")
        core.check_request_path(
            service.get('url_host_name') + service.get('url_context_root') +
            request_path,
            session=session)
        if not content_dir and interactive:
            content_dir = core.prompt(
                message=('Please enter the file path to the directory '
                         'that contains the static content: '))
        if not content_dir:
            if interactive:
                raise ValueError('Operation cancelled.')
            else:
                raise ValueError('No content directory path given.')
        content_dir = os.path.abspath(
            os.path.expanduser(content_dir))
        if not os.path.isdir(content_dir):
            raise ValueError(
                f"The given content directory path '{content_dir}' "
                "does not exists.")
        if not requires_auth:
            if interactive:
                requires_auth = core.prompt(
                    "Should the content require authentication [y/N]: ",
                    {'defaultValue': 'n'}).strip().lower() == 'y'
            else:
                requires_auth = False
        if not comments and interactive:
            comments = core.prompt_for_comments()
        res = session.run_sql("""
            INSERT INTO `mysql_rest_service_metadata`.`content_set`(
                service_id, request_path, requires_auth, enabled, comments)
            VALUES(?, ?, ?, ?, ?)
            """, [service.get("id"),
                  request_path,
                  1 if requires_auth else 0,
                  0,
                  comments])
        content_set_id = res.auto_increment_value
        file_list = []
        for root, dirs, files in os.walk(content_dir):
            for file in files:
                file_list.append(os.path.join(root, file))
        for file in file_list:
            with open(file, 'rb') as f:
                data = f.read()
            res = session.run_sql("""
                INSERT INTO `mysql_rest_service_metadata`.`content_file`(
                    content_set_id, request_path, requires_auth, enabled,
                    content)
                VALUES(?, ?, ?, ?, ?)
                """, [content_set_id,
                      file[len(content_dir):],
                      1 if requires_auth else 0,
                      1,
                      data])
        if interactive:
            print(f"{len(file_list)} files added.")
        res = session.run_sql("""
            UPDATE `mysql_rest_service_metadata`.`content_set`
            SET enabled = 1
            WHERE id = ?
            """, [content_set_id])
        if interactive:
            return "\n" + "Content added successfully."
        else:
            return {
                "content_set_id": content_set_id,
                "number_of_files_uploaded": len(file_list)
            }
    except Exception as e:
        if raise_exceptions:
            raise
        print(f"Error: {str(e)}")
def add_content_set ( content_dir = None , service_id = None , ** kwargs ) : import os request_path = kwargs . get ( "request_path" ) requires_auth = kwargs . get ( "requires_auth" ) comments = kwargs . get ( "comments" ) session = kwargs . get ( "session" ) interactive = kwargs . get ( "interactive" , core . get_interactive_default ( ) ) raise_exceptions = kwargs . get ( "raise_exceptions" , not interactive ) try : session = core . get_current_session ( session ) service = mrs_services . get_service ( service_id = service_id , auto_select_single = True , session = session , interactive = interactive , return_formatted = False ) if not request_path and interactive : request_path = core . prompt ( "Please enter the request path for this content set [" f"/content]: " , { 'defaultValue' : '/content' } ) . strip ( ) if not request_path . startswith ( '/' ) : raise Exception ( "The request_path has to start with '/'." ) core . check_request_path ( service . get ( 'url_host_name' ) + service . get ( 'url_context_root' ) + request_path , session = session ) if not content_dir and interactive : content_dir = core . prompt ( message = ( 'Please enter the file path to the directory ' 'that contains the static content: ' ) ) if not content_dir : if interactive : raise ValueError ( 'Operation cancelled.' ) else : raise ValueError ( 'No content directory path given.' ) content_dir = os . path . abspath ( os . path . expanduser ( content_dir ) ) if not os . path . isdir ( content_dir ) : raise ValueError ( f"The given content directory path '{content_dir}' " "does not exists." ) if not requires_auth : if interactive : requires_auth = core . prompt ( "Should the content require authentication [y/N]: " , { 'defaultValue' : 'n' } ) . strip ( ) . lower ( ) == 'y' else : requires_auth = False if not comments and interactive : comments = core . prompt_for_comments ( ) res = session . run_sql ( """
            INSERT INTO `mysql_rest_service_metadata`.`content_set`(
                service_id, request_path, requires_auth, enabled, comments)
            VALUES(?, ?, ?, ?, ?)
            """ , [ service . get ( "id" ) , request_path , 1 if requires_auth else 0 , 0 , comments ] ) content_set_id = res . auto_increment_value file_list = [ ] for root , dirs , files in os . walk ( content_dir ) : for file in files : file_list . append ( os . path . join ( root , file ) ) for file in file_list : with open ( file , 'rb' ) as f : data = f . read ( ) res = session . run_sql ( """
                INSERT INTO `mysql_rest_service_metadata`.`content_file`(
                    content_set_id, request_path, requires_auth, enabled,
                    content)
                VALUES(?, ?, ?, ?, ?)
                """ , [ content_set_id , file [ len ( content_dir ) : ] , 1 if requires_auth else 0 , 1 , data ] ) if interactive : print ( f"{len(file_list)} files added." ) res = session . run_sql ( """
            UPDATE `mysql_rest_service_metadata`.`content_set`
            SET enabled = 1
            WHERE id = ?
            """ , [ content_set_id ] ) if interactive : return "\n" + "Content added successfully." else : return { "content_set_id" : content_set_id , "number_of_files_uploaded" : len ( file_list ) } except Exception as e : if raise_exceptions : raise print ( f"Error: {str(e)}" )
Adds content to the given MRS service
Adds content to the given MRS service
"""Adds content to the given MRS service

    Args:
        content_dir (str): The path to the content directory
        service_id (int): The id of the service the schema should be added to
        **kwargs: Additional options

    Keyword Args:
        request_path (str): The request_path
        requires_auth (bool): Whether authentication is required to access
            the content
        comments (str): Comments about the content
        session (object): The database session to use.
        interactive (bool): Indicates whether to execute in interactive mode
        raise_exceptions (bool): If set to true exceptions are raised

    Returns:
        None in interactive mode, a dict with content_set_id and
            number_of_files_uploaded
    """ # Get request_path # Get the content_dir # Convert Unix path to Windows # If a content_dir has been provided, check if that directory exists # Get requires_auth # Get comments # Create the content_set, ensure it is created as "not enabled" # Read the file content # Upload it to the content table # Enable the content_set after all content has been uploaded
None in interactive mode, a dict with content_set_id and
number_of_files_uploaded
None in interactive mode a dict with content_set_id and number_of_files_uploaded
content_dir
The path to the content directory
The path to the content directory
service_id
The id of the service the schema should be added to
The id of the service the schema should be added to
**kwargs
None