Пример #1
0
def test_str_to_date():
    import datetime
    assert date.str_to_date("12/11/2014") == datetime.datetime(2014, 11, 12)
    assert date.str_to_date("12-11-2014") == datetime.datetime(2014, 11, 12)
    assert date.str_to_date(None) == ""
Пример #2
0
def format_input_value(value, sqla_column_dict, force_rel_creation=False):
    """
    format value to fetch the database storage expectations
    For example dates are input in dd/mm/yyyy format, we want datetime objects

    Relationship technics:

        ManyToOne relationship : we use the related_key (attribute of the
        related element) to find the related element we're supposed to point to

        OneToMany relationship: we use the related key (attribute of the related
        element) to instantiate a new related element. NB: It only works with
        related elements with one argument (typically list of dates ...)

    :param str value: The value coming from the csv file
    :param dict sqla_column_dict: The datas collected about the destination
    attribute
    :param bool force_rel_creation: Should we force the creation of a related
    element on import (default False), only in case of many to one
    relationships.  Note : the related_key attribute should be sufficient to
    create a new instance of the related element
    :returns: The formatted value
    :rtype: object (datetime) or string depending on the column
    """

    prop = sqla_column_dict['__col__']

    res = value

    if isinstance(prop, RelationshipProperty):
        # Handle the relationship
        # Get the id of the corresponding model and return it
        if sqla_column_dict['rel_type'] == 'manytoone':
            related_key = sqla_column_dict['related_key']
            class_ = prop.mapper.class_
            # We query the database to get the corresponding element filtering
            # on the configured related_key
            res = class_.query().filter(
                getattr(class_, related_key) == value
            ).first()
            if res is None and force_rel_creation:
                if value is not None and value.strip():
                    logger.debug("Creating a new element : %s %s" % (
                        related_key, value)
                    )
                    creation_dict = {related_key: value}
                    res = class_(**creation_dict)
        else:
            # We have a one to many relationship, we generate an instance using
            # the related_key as instanciation attribute
            related_key = sqla_column_dict['related_key']
            class_ = prop.mapper.class_
            if 'formatter' in sqla_column_dict:
                value = sqla_column_dict['formatter'](value)
            args = {related_key: value}
            res = [class_(**args)]

    else:

        column = prop.columns[0]
        column_type = getattr(column.type, 'impl', column.type)

        if 'formatter' in sqla_column_dict:
            res = sqla_column_dict['formatter'](value)

        elif isinstance(column_type, Boolean):
            if value in ('0', 'false', 'non', '', 'False'):
                res = False
            else:
                res = True

        elif isinstance(column_type, (DateTime, Date,)):
            res = date_utils.str_to_date(value)
    return res
Пример #3
0
def format_input_value(value, sqla_column_dict, force_rel_creation=False):
    """
    format value to fetch the database storage expectations
    For example dates are input in dd/mm/yyyy format, we want datetime objects

    Relationship technics:

        ManyToOne relationship : we use the related_key (attribute of the
        related element) to find the related element we're supposed to point to

        OneToMany relationship: we use the related key (attribute of the related
        element) to instantiate a new related element. NB: It only works with
        related elements with one argument (typically list of dates ...)

    :param str value: The value coming from the csv file
    :param dict sqla_column_dict: The datas collected about the destination
    attribute
    :param bool force_rel_creation: Should we force the creation of a related
    element on import (default False), only in case of many to one
    relationships.  Note : the related_key attribute should be sufficient to
    create a new instance of the related element
    :returns: The formatted value
    :rtype: object (datetime) or string depending on the column
    """

    prop = sqla_column_dict['__col__']

    res = value

    if isinstance(prop, RelationshipProperty):
        # Handle the relationship
        # Get the id of the corresponding model and return it
        if sqla_column_dict['rel_type'] == 'manytoone':
            related_key = sqla_column_dict['related_key']
            class_ = prop.mapper.class_
            # We query the database to get the corresponding element filtering
            # on the configured related_key
            res = class_.query().filter(
                getattr(class_, related_key) == value
            ).first()
            if res is None and force_rel_creation:
                if value is not None and value.strip():
                    logger.debug("Creating a new element : %s %s" % (
                        related_key, value)
                    )
                    creation_dict = {related_key: value}
                    res = class_(**creation_dict)
        else:
            # We have a one to many relationship, we generate an instance using
            # the related_key as instanciation attribute
            related_key = sqla_column_dict['related_key']
            class_ = prop.mapper.class_
            if 'formatter' in sqla_column_dict:
                value = sqla_column_dict['formatter'](value)
            args = {related_key: value}
            res = [class_(**args)]

    else:

        column = prop.columns[0]
        column_type = getattr(column.type, 'impl', column.type)

        if 'formatter' in sqla_column_dict:
            res = sqla_column_dict['formatter'](value)

        elif isinstance(column_type, Boolean):
            if value in ('0', 'false', 'non', '', 'False'):
                res = False
            else:
                res = True

        elif isinstance(column_type, (DateTime, Date,)):
            res = date_utils.str_to_date(value)
    return res
Пример #4
0
def test_str_to_date():
    import datetime
    assert date.str_to_date("12/11/2014") == datetime.datetime(2014, 11, 12)
    assert date.str_to_date("12-11-2014") == datetime.datetime(2014, 11, 12)
    assert date.str_to_date(None) == ""