예제 #1
0
 def removePrio(self, animeTitleOrAlias, key):
     animeTitle = self.getTitleFromAlias(animeTitleOrAlias)
     if not animeTitle:
         return False
     if checkers.is_integer(key):
         prioManager = self.numPrioManager
     else:
         prioManager = self.tagPrioManager
     prioManager.removePrio(animeTitle, key)
예제 #2
0
def validate_favorite_form(json: dict):
    try:
        user_id = json['user_id']
        user_id_valid = checkers.is_integer(user_id)
    except TypeError:
        user_id_valid = False
    serie_id_valid = False
    try:
        serie_id = json['serie_id']
        serie_id_valid = checkers.is_integer(serie_id)
    except TypeError:
        serie_id_valid = False
    invalid_fields = []
    if not serie_id_valid:
        invalid_fields.append(InvalidField('serie_id', f'Invalid value'))
    if not user_id_valid:
        invalid_fields.append(InvalidField('user_id', f'Invalid value'))
    if len(invalid_fields) > 0:
        raise InvalidForm(invalid_fields)
    return user_id, serie_id
예제 #3
0
def validate_add_serie_form(json: dict):
    try:
        serie_id = json['serie_id']
        serie_id_valid = checkers.is_integer(serie_id)
    except TypeError:
        serie_id_valid = False
    invalid_fields = []
    if not serie_id_valid:
        invalid_fields.append(InvalidField('serie_id', f'Invalid value'))
        raise InvalidForm(invalid_fields)
    return serie_id
예제 #4
0
async def setCurrEp(message, args):
    args = message.content.split()
    if len(args) != 3:
        errMsg = 'Please enter the form of: "!setEp animeTitle/animeAlias epNum".'
        await message.channel.send(errMsg)
    ep = args[-1]

    if checkers.is_integer(ep):
        key = "".join(args[1:-1])
        trueKey = amadeusDriver.getTitleFromKey(key)
        amadeusDriver.setEpisode(trueKey, ep)
        succMsg = 'Updated stack of {0} to episode {1}'.format(trueKey, ep)
        await message.channel.send(succMsg)
    else:
        errMsg = 'Please ensure "{0}" is a valid number'.format(ep)
        await message.channel.send(errMsg)
예제 #5
0
def decode(data: str) -> [int, float, bool, str]:
    if data.endswith('%'):
        data = data.replace('%', '')
    elif data.endswith("B"):
        i = len(data)
        for i, character in enumerate(data):
            if character in ascii_uppercase:
                break
        data, m = decode(data[:i]), data[i:].replace('B', '').lower()
        if m == 'm':
            m = 10**6
        elif m == 'k':
            m = 10**3
        return data * m
    if checkers.is_integer(data):
        return int(float(data))
    elif checkers.is_float(data):
        return float(data)
    elif data.lower() == 'false':
        return False
    elif data.lower() == 'true':
        return True
    else:
        return data
def get_type_mapping(value,
                     type_mapping=None,
                     skip_nested=True,
                     default_to_str=False):
    """Retrieve the SQL type mapping for ``value``.

    :param value: The value whose SQL type will be returned.

    :param type_mapping: Determines how the value type of ``value`` map to
      SQL column data types. To add a new mapping or override a default, set a
      key to the name of the value type in Python, and set the value to a
      :doc:`SQLAlchemy Data Type <sqlalchemy:core/types>`. The following are the
      default mappings applied:

      .. list-table::
         :widths: 30 30
         :header-rows: 1

         * - Python Literal
           - SQL Column Type
         * - ``bool``
           - :class:`Boolean <sqlalchemy:sqlalchemy.types.Boolean>`
         * - ``str``
           - :class:`Text <sqlalchemy:sqlalchemy.types.Text>`
         * - ``int``
           - :class:`Integer <sqlalchemy:sqlalchemy.types.Integer>`
         * - ``float``
           - :class:`Float <sqlalchemy:sqlalchemy.types.Float>`
         * - ``date``
           - :class:`Date <sqlalchemy:sqlalchemy.types.Date>`
         * - ``datetime``
           - :class:`DateTime <sqlalchemy:sqlalchemy.types.DateTime>`
         * - ``time``
           - :class:`Time <sqlalchemy:sqlalchemy.types.Time>`
         * - ``timedelta``
           - :class:`Interval <sqlalchemy:sqlalchemy.types.Interval>`

    :type type_mapping: :class:`dict <python:dict>` with type names as keys and
      column data types as values / :obj:`None <python:None>`

    :param skip_nested: If ``True`` then if ``value`` is a nested item (e.g.
      iterable, :class:`dict <python:dict>` objects, etc.) it will return
      :obj:`None <python:None>`. If ``False``, will treat nested items as
      :class:`str <python:str>`. Defaults to ``True``.
    :type skip_nested: :class:`bool <python:bool>`

    :param default_to_str: If ``True``, will automatically set a ``value`` whose
      value type cannot be determined to ``str``
      (:class:`Text <sqlalchemy:sqlalchemy.types.Text>`). If ``False``, will
      use the value type's ``__name__`` attribute and attempt to find a mapping.
      Defaults to ``False``.
    :type default_to_str: :class:`bool <python:bool>`

    :returns: The :doc:`SQLAlchemy Data Type <sqlalchemy:core/types>` for ``value``, or
      :obj:`None <python:None>` if the value should be skipped
    :rtype: :doc:`SQLAlchemy Data Type <sqlalchemy:core/types>` / :obj:`None`

    :raises UnsupportedValueTypeError: when ``value`` does not have corresponding
      :doc:`SQLAlchemy Data Type <sqlalchemy:core/types>`

    """
    if not type_mapping:
        type_mapping = DEFAULT_PYTHON_SQL_TYPE_MAPPING

    for key in DEFAULT_PYTHON_SQL_TYPE_MAPPING:
        if key not in type_mapping:
            type_mapping[key] = DEFAULT_PYTHON_SQL_TYPE_MAPPING[key]

    if checkers.is_callable(value):
        raise UnsupportedValueTypeError('value ("%s") cannot be callable' %
                                        value)
    elif checkers.is_iterable(value) and skip_nested:
        return None
    elif checkers.is_iterable(value) and default_to_str:
        target_type = 'str'
    elif value is None and default_to_str:
        target_type = 'str'
    elif isinstance(value, bool):
        target_type = 'bool'
    elif checkers.is_numeric(value):
        if checkers.is_integer(value):
            target_type = 'int'
        else:
            target_type = 'float'
    elif checkers.is_time(value) and not checkers.is_datetime(value):
        target_type = 'time'
    elif checkers.is_datetime(value):
        target_type = 'datetime'
    elif checkers.is_date(value):
        target_type = 'date'
    elif default_to_str:
        target_type = 'str'
    else:
        target_type = type(value).__name__

    column_type = type_mapping.get(target_type, None)
    if not column_type:
        raise UnsupportedValueTypeError(
            'value ("%s") is not a supported type (%s)' % (value, target_type))

    return column_type