def __init__(self, query=None, orcid_id=None, orcid_email=None, sandbox=True):
        """Initialize

        Parameters
        ----------
        :param orcid_id: string
            Needs orcid_id to perform a request by orcid_id.
        :param orcid_email: string
            Needs an email address to perform a request by email.
        """
        if orcid_email:
            self.search_obj = OrcidSearchResults(sandbox)
            self.data = self.search_obj.basic_search(orcid_email)
            self.orcid_id = self.get_id()
        elif query:
            self.sandbox = sandbox
            self.search_obj = OrcidSearchResults(sandbox)
            self.search_obj.basic_search(query)
            self.orcid_id = self.select_id()
        else:
            self.search_obj = OrcidSearchResults(sandbox)
            self.orcid_id = orcid_id

        if self.orcid_id is not None:
            try:
                self.url = self.search_obj.api._endpoint_public + '/' + self.orcid_id
                self.headers = {'Accept': 'text/turtle'}
                self.turtle_config = None
            except:
                print('Orcid ID or email is invalid.  Please try again.')
                exit()
Example #2
0
def basic_search(query, sandbox):
    """ Function for initializing a search for an orcid id.

    Parameters
    ----------
    :param query: string
        Query built from user input.

    Returns
    -------
    :returns: no return.
    """
    # Initialize and populate all variables and dictionaries
    search_obj = OrcidSearchResults(sandbox)
    search_obj.basic_search(query)
    actual_total = search_obj.actual_total_results
    total_results = search_obj.total_results

    # Print results
    search_obj.print_basic()

    # Print total results if actual results are above 100
    if total_results < actual_total:
        print('Actual Total Results: {}'.format(actual_total))
        print('')

    # Ask user if they would like to search again.
    while True:
        new_instance = click.prompt('Would you like to search again [y/N]?', default='N', show_default=False)
        print('')

        if new_instance in ('y', 'Y', 'yes', 'YES', 'Yes'):
            if sandbox:
                search_type(args=['-b', '-s'])
            else:
                search_type(args=['-b'])
            break
        elif new_instance in ('n', 'N', 'no', 'NO', 'No'):
            exit(1)
        else:
            print('You did not pick an appropriate answer.')
Example #3
0
    def __init__(self,
                 query=None,
                 orcid_id=None,
                 orcid_email=None,
                 sandbox=True):
        """Initialize

        Parameters
        ----------
        :param orcid_id: string
            Needs orcid_id to perform a request by orcid_id.
        :param orcid_email: string
            Needs an email address to perform a request by email.
        """
        if orcid_email:
            self.search_obj = OrcidSearchResults(sandbox)
            self.data = self.search_obj.basic_search(orcid_email)
            self.orcid_id = self.get_id()
        elif query:
            self.sandbox = sandbox
            self.search_obj = OrcidSearchResults(sandbox)
            self.search_obj.basic_search(query)
            self.orcid_id = self.select_id()
        else:
            self.search_obj = OrcidSearchResults(sandbox)
            self.orcid_id = orcid_id

        if self.orcid_id is not None:
            try:
                self.url = self.search_obj.api._endpoint_public + '/' + self.orcid_id
                self.headers = {'Accept': 'text/turtle'}
                self.turtle_config = None
            except:
                print('Orcid ID or email is invalid.  Please try again.')
                exit()
class OrcidManager(object):
    """Class for OrcidManager"""

    def __init__(self, query=None, orcid_id=None, orcid_email=None, sandbox=True):
        """Initialize

        Parameters
        ----------
        :param orcid_id: string
            Needs orcid_id to perform a request by orcid_id.
        :param orcid_email: string
            Needs an email address to perform a request by email.
        """
        if orcid_email:
            self.search_obj = OrcidSearchResults(sandbox)
            self.data = self.search_obj.basic_search(orcid_email)
            self.orcid_id = self.get_id()
        elif query:
            self.sandbox = sandbox
            self.search_obj = OrcidSearchResults(sandbox)
            self.search_obj.basic_search(query)
            self.orcid_id = self.select_id()
        else:
            self.search_obj = OrcidSearchResults(sandbox)
            self.orcid_id = orcid_id

        if self.orcid_id is not None:
            try:
                self.url = self.search_obj.api._endpoint_public + '/' + self.orcid_id
                self.headers = {'Accept': 'text/turtle'}
                self.turtle_config = None
            except:
                print('Orcid ID or email is invalid.  Please try again.')
                exit()

    def get_id(self):
        """Get the Orcid_id from the email search

        Parameters
        ----------
        :param: None

        Returns
        -------
        :returns orcid_id[0]: string
            returns the Orcid ID from the email search
        """
        if not self.data:
            print('No data was found.')
        else:
            orcid_id = self.data.keys()
            return orcid_id[0]

    def get_turtle(self):
        """Get the user information in a Turtle syntax

        Parameters
        ----------
        :param: None

        Returns
        -------
        :returns self.turtle_config.text: string
            user data in a text format with Turtle syntax
        """
        self.turtle_config = requests.get(self.url, headers=self.headers)

        if (self.turtle_config.status_code == 404) or (self.turtle_config.status_code == 500):
            print('Orcid ID not found.  Please try again.')
            exit()
        else:
            print(str(self.url) + ", Status: " + str(self.turtle_config.status_code))
            return self.turtle_config.text

    def select_id(self):
        """ Function for initializing a search for an orcid id, and then creates a RDF
            configuration file automatically.

        Parameters
        ----------
        :param query: string
            Query built from user input.

        Returns
        -------
        :returns: no return.
        """

        # Initialize and populate all variables and dictionaries
        actual_total = self.search_obj.actual_total_results
        total_results = self.search_obj.total_results
        # orcid_id = search_obj.orcid_id

        # Print results
        self.search_obj.print_basic_alt()

        # Print total results if actual results are above 100
        if total_results < actual_total:
            print 'Actual Total Results: {}'.format(actual_total)
            print('')

        # Get list of Orcid ID's from results
        id_list = self.search_obj.orcid_id

        # Return ID if only one result was found
        if total_results == 1:
            orcid_id = id_list[0]
            return orcid_id
        # If no results are found
        elif total_results == 0:
            print("No results where found. Please try again.\n")
            orcid_id = None
            return orcid_id

        # Allow user to select Orcid profile if multiple results are found
        else:
            id_dict = dict()
            # Get list of Orcid ID's and correspond count with ID
            for i, d in enumerate(id_list):
                id_dict[i + 1] = d

            selected = None
            while not selected:
                try:
                    selected = click.prompt('Select the result # of the record (Type "N" for another search, '
                                            '"Exit" to abort)')
                    print("")
                    orcid_id = id_dict[int(selected)]
                    return orcid_id
                except KeyError:
                    print('That is not a valid selection.  Please try again.\n')
                    selected = None
                except ValueError:
                    if selected in ('N', 'n'):
                        return None
                    elif selected in ('exit', 'Exit', 'EXIT'):
                        exit()
                    else:
                        print('That is not a valid selection.  Please try again.\n')
                        selected = None
Example #5
0
def advanced_search(query, record_type, sandbox):
    """ Function for initializing an advanced search for an orcid id.  Utilizes OrcidSearchResults() class
        from search.py

    Parameters
    ----------
    :param query: string
        Orcid ID inputted by user
    :param record_type: string
        User selected record_type that they want to display.  Must have corresponding put-code

    Returns
    -------
    :returns: no return.
        Will write to file for a 'activities' record, or print record to screen for all other records.
        Will prompt user to see if they would like to write customer records to file.

        A large amount of information can be gathered for a 'activities' record_type.  The only option
        allowed at this time is for the JSON output to be written to a JSON file.
    """
    search_obj = OrcidSearchResults(sandbox)

    # Will be 'not None' only if record type is other than 'activities'
    # if record_type == 'write-rdf':
    #     config = ConfigManager()
    #     config.get_config(_id=query, sandbox=sandbox)
    #     config.write_config()
    # elif record_type == 'read-rdf':
    #     config = ConfigManager()
    #     rdf_graph = config.read_config()
    #     print rdf_graph
    if record_type is not None:
        put_code = click.prompt('Please enter the put-code (must match record type)')
        results = search_obj.advanced_search(query, record_type, put_code)
        print('')
        print(json.dumps(results, sort_keys=True, indent=4, ensure_ascii=False))

        # Ask user if they would like to send this information to file
        while True:
            send_to_file = click.prompt('Would you like to send this output to a file [y/N]?', default='N',
                                        show_default=False)

            if send_to_file in ('y', 'Y', 'yes', 'YES', 'Yes'):
                with io.open(query + '_' + record_type + '_' + put_code + '.json', 'w', encoding='utf8') \
                        as json_file:
                    data = json.dumps(results, json_file, sort_keys=True, indent=4, ensure_ascii=False)
                    # unicode(data) auto-decodes data to unicode if str
                    try:
                        json_file.write(str(data))
                    except (NameError, TypeError):
                        json_file.write(unicode(data))
                break
            elif send_to_file in ('n', 'N', 'no', 'NO', 'No'):
                break
            else:
                print('You did not pick an appropriate answer.')
    else:
        # When 'activities' (option 1 - summary) is selected, prints to file
        results = search_obj.advanced_search(query)

        home_path = expanduser("~")
        dir_path = home_path + "/.sc/"
        filename = query + '.json'
        if os.path.exists(dir_path):
            config_path = dir_path + filename
        else:
            os.mkdir(home_path + "/.sc/")
            config_path = dir_path + filename

        with io.open(config_path, 'w', encoding='utf8') as json_file:
            data = json.dumps(results, json_file, sort_keys=True, indent=4, ensure_ascii=False)
            # unicode(data) auto-decodes data to unicode if str
            try:
                json_file.write(str(data))
            except (NameError, TypeError):
                json_file.write(unicode(data))

    # Ask user if they would like to go back to the advanced search selection menu
    while True:
        new_instance = click.prompt('Back to \'Selection\' menu [y/EXIT]?', default='EXIT', show_default=False)
        print('')

        if new_instance in ('y', 'Y', 'yes', 'YES', 'Yes'):
            if sandbox:
                search_type(args=['-a', '-s'])
            else:
                search_type(args=['-a'])
            break
        elif new_instance in ('exit', 'EXIT', 'Exit'):
            exit(1)
        else:
            print('You did not pick an appropriate answer.')
Example #6
0
class OrcidManager(object):
    """Class for OrcidManager"""
    def __init__(self,
                 query=None,
                 orcid_id=None,
                 orcid_email=None,
                 sandbox=True):
        """Initialize

        Parameters
        ----------
        :param orcid_id: string
            Needs orcid_id to perform a request by orcid_id.
        :param orcid_email: string
            Needs an email address to perform a request by email.
        """
        if orcid_email:
            self.search_obj = OrcidSearchResults(sandbox)
            self.data = self.search_obj.basic_search(orcid_email)
            self.orcid_id = self.get_id()
        elif query:
            self.sandbox = sandbox
            self.search_obj = OrcidSearchResults(sandbox)
            self.search_obj.basic_search(query)
            self.orcid_id = self.select_id()
        else:
            self.search_obj = OrcidSearchResults(sandbox)
            self.orcid_id = orcid_id

        if self.orcid_id is not None:
            try:
                self.url = self.search_obj.api._endpoint_public + '/' + self.orcid_id
                self.headers = {'Accept': 'text/turtle'}
                self.turtle_config = None
            except:
                print('Orcid ID or email is invalid.  Please try again.')
                exit()

    def get_id(self):
        """Get the Orcid_id from the email search

        Parameters
        ----------
        :param: None

        Returns
        -------
        :returns orcid_id[0]: string
            returns the Orcid ID from the email search
        """
        if not self.data:
            print('No data was found.')
        else:
            orcid_id = self.data.keys()
            return orcid_id[0]

    def get_turtle(self):
        """Get the user information in a Turtle syntax

        Parameters
        ----------
        :param: None

        Returns
        -------
        :returns self.turtle_config.text: string
            user data in a text format with Turtle syntax
        """
        self.turtle_config = requests.get(self.url, headers=self.headers)

        if (self.turtle_config.status_code
                == 404) or (self.turtle_config.status_code == 500):
            print('Orcid ID not found.  Please try again.')
            exit()
        else:
            print(
                str(self.url) + ", Status: " +
                str(self.turtle_config.status_code))
            return self.turtle_config.text

    def select_id(self):
        """ Function for initializing a search for an orcid id, and then creates a RDF
            configuration file automatically.

        Parameters
        ----------
        :param query: string
            Query built from user input.

        Returns
        -------
        :returns: no return.
        """

        # Initialize and populate all variables and dictionaries
        actual_total = self.search_obj.actual_total_results
        total_results = self.search_obj.total_results
        # orcid_id = search_obj.orcid_id

        # Print results
        self.search_obj.print_basic_alt()

        # Print total results if actual results are above 100
        if total_results < actual_total:
            print 'Actual Total Results: {}'.format(actual_total)
            print('')

        # Get list of Orcid ID's from results
        id_list = self.search_obj.orcid_id

        # Return ID if only one result was found
        if total_results == 1:
            orcid_id = id_list[0]
            return orcid_id
        # If no results are found
        elif total_results == 0:
            print("No results where found. Please try again.\n")
            orcid_id = None
            return orcid_id

        # Allow user to select Orcid profile if multiple results are found
        else:
            id_dict = dict()
            # Get list of Orcid ID's and correspond count with ID
            for i, d in enumerate(id_list):
                id_dict[i + 1] = d

            selected = None
            while not selected:
                try:
                    selected = click.prompt(
                        'Select the result # of the record (Type "N" for another search, '
                        '"Exit" to abort)')
                    print("")
                    orcid_id = id_dict[int(selected)]
                    return orcid_id
                except KeyError:
                    print(
                        'That is not a valid selection.  Please try again.\n')
                    selected = None
                except ValueError:
                    if selected in ('N', 'n'):
                        return None
                    elif selected in ('exit', 'Exit', 'EXIT'):
                        exit()
                    else:
                        print(
                            'That is not a valid selection.  Please try again.\n'
                        )
                        selected = None