util.py 1.53 KB
Newer Older
1 2 3 4
#!/usr/bin/env python3
"""
    Util functions
"""
5 6 7 8
import json
from collections import namedtuple
from io import BytesIO

9
from flask import flash
10 11
from tabulator import helpers
from tabulator.loader import Loader
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31


def flash_error(msg):
    """ Flash bootstrap error message """
    flash(msg, 'danger')


def flash_warning(msg):
    """ Flash bootstrap warning message """
    flash(msg, 'warning')


def flash_success(msg):
    """ Flash bootstrap success message """
    flash(msg, 'success')


def flash_info(msg):
    """ Flash bootstrap info message """
    flash(msg, 'info')
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60


class ValidataSource():
    """ Handy class to handle different sort of data source """

    def __init__(self, data, name, type):
        """ Initialization """
        self.data = data
        self.name = name
        self.type = type
        self.scheme = None
        self.format = None

    def get_goodtables_source(self):
        """ Creates source ready to be ingested by tabulator """

        self.scheme, self.format = helpers.detect_scheme_and_format(self.name)

        # In case of uploaded file (we work with bytes string)
        if self.type == 'file':

            # CSV: converts to string
            if self.format == 'csv':
                self.scheme = 'text'
                encoding = helpers.detect_encoding(self.data)
                self.data = self.data.decode(encoding)

            # Else use custom BytesLoader
            else:
61
                self.scheme = 'bytes'
62

63
        return {'source': self.data, 'format': self.format, 'scheme': self.scheme}