#!/usr/bin/env python3 """ Util functions """ import json from collections import namedtuple from io import BytesIO from flask import flash from tabulator import helpers from tabulator.loader import Loader 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') 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: self.scheme = 'bytes' return {'source': self.data, 'format': self.format, 'scheme': self.scheme}