def setUp(self): # Start with MyTable class MyTable(Table): name = Col('Name') # Then dynamically extend it. self.table_cls = create_table(base=MyTable) self.table_cls.add_column('number', Col('Number'))
def index(): def internalGenerator(): # connect to db client = InfluxDBClient('localhost', 8086) client.switch_database('test') a = client.query( "select last(*), min(*), max(*) from test.autogen.sensors group by id" ) for item in a.get_points(): yield item['last_id_field'] TableCls = create_table() \ .add_column('sensor', Col('Sensors')) \ .add_column('status', Col('OK')) \ .add_column('min', Col('Min')) \ .add_column('actual', Col('Actual')) \ .add_column('max', Col('Max')) getSensors = internalGenerator() sensorsList = [] for sensor in getSensors: sensorsList.append( dict(sensor=sensor, status='', min='', actual='', max='')) table = TableCls( sensorsList, html_attrs={'id': 'sensorTab'}, no_items='Error', classes=['table table-hover ' 'table-striped ' 'table-condensed']) return render_template('sensorsTest.html', test=table)
def create_dynamic_table(contents,name='Dynamic Table', **sort_kwargs): def dynamic_sort_url(self, col_key, reverse=False): if reverse: direction = 'desc' else: direction = 'asc' return url_for('main.dynamic_flask_table', sort=col_key, direction=direction) options = dict( border = True, allow_sort = True, no_items = "No Samples", html_attrs = {"style":'font-size:18px'}, table_id = 'vert_table', classes = ["table-striped"] ) table_class = create_table(name,options=options) table_class.sort_url = dynamic_sort_url sort = sort_kwargs.get('sort_by') reverse = sort_kwargs.get('sort_reverse') table_class.add_column('state',Col('state')) if "Mercer" not in contents.fetch('county'): table_class.add_column('county',Col('county')) sorted_contents = sorted(contents.fetch(as_dict=True), key=partial(table_sorter,sort_key=sort),reverse=reverse) table = table_class(sorted_contents) table.sort_by = sort table.sort_reverse = reverse return table
def index(): # get list of accounts from database u = User.query.get(current_user.id) TableCls = create_table(base=BaseTable).add_column('account', Col('Account')) TableCls.add_column('otp', Col('One-Time Password')) TableCls.add_column( 'delete', LinkCol('Remove', 'main.confirm_remove_account', attr='remove_symbol', url_kwargs=dict(id='id'))) TableCls.add_column( 'reveal', LinkCol(u'Show key', 'main.show_key', attr='show_symbol', url_kwargs=dict(id='id'))) try: table = TableCls([ dict(account=a.name, otp=get_otp(decrypt_key(a.key)), id=a.id, remove_symbol='\u274E', show_symbol='\U0001F441') for a in u.accounts ]) except TypeError: flash('Session expired - please log in again.', 'warning') return redirect(url_for('auth.login')) # calculate time (in ms) before OTPs expire now = time() time_to_expiry = (30 - round(now) % 30) * 1000 return render_template('index.html', table=table, t=time_to_expiry)
def get_table(headers, items, name): table = create_table(name+'Table', base=Table) for h in headers: table.add_column(h, Col(h)) # Populate, construct & return the table return table(items)
def get_table(headers, items, name): table = create_table(name + 'Table', base=Table) for h in headers: table.add_column(h, Col(h)) # Populate, construct & return the table return table(items)
def main_table(data, years): options = dict(classes=['table', 'table-hover'], thead_classes=['thead-light'], no_items='N/A') TableCls = create_table(options=options) for year in years: TableCls.add_column(str(year), DateCol(year)) table = TableCls(data) return table
def new_log(device_type, device_id): device_type = str(device_type) device_id = int(device_id) table = find_database_table(device_type) try: offset = request.get_json(force=True).get("offset") except: offset = None if offset is None: offset = 0 else: offset = offset if db.session.query(table).filter_by( device_id=device_id).first() and offset == 0: log_list = query_new_log(table, device_id) TableCls = create_table('TableCls', options=dict( classes=['table', 'table-bordered'], no_items='No Items')) for key in log_list[0].keys(): TableCls.add_column(key, Col(key.capitalize())) table = TableCls(log_list) # print(table.__html__()) warn = 0 elif offset == 0: warn = 'No logs for this device!' table = 0 else: log_list = query_new_log(table, device_id, offset=offset) TableCls = create_table('TableCls', options=dict( classes=['table', 'table-bordered'], no_items='No Items')) if len(log_list) != 0: for key in log_list[0].keys(): TableCls.add_column(key, Col(key.capitalize())) table = TableCls(log_list) return table.__html__() return render_template('log/device_log.html', warn=warn, table=table, url=url_for('form.new_log', device_type=device_type, device_id=device_id))
def create_table(self): """ create the table with rows and columns """ blank_table = create_table(options={'classes': ['comp-table']}) for i in self.COLUMNS: blank_table.add_column(i, Col(i)) table_obj = blank_table(self.rows) return table_obj
def get_ftable(keys, rows): DynamicTable = ft.create_table( 'dynamic', options={'classes': ('table', 'table-striped', 'table-bordered')}) for col_name in keys: DynamicTable.add_column(col_name, ft.Col(col_name)) dynamic_table = DynamicTable(rows) return dynamic_table
def rel2table(relation): rel_fields = dir(relation) ignored_fields = ['metadata'] sorted_fields = ['id','name'] fields = [f for f in sorted_fields if f in rel_fields ] + [x for x in rel_fields if not x.startswith('_') and not (x in ignored_fields or x in sorted_fields)] print(rel_fields) table_class = create_table(options={'classes':['table','is-bordered', 'is-striped', 'is-narrow']}) for f in fields: table_class.add_column(f, Col(f.capitalize())) entries = ScopedSession.query(relation).all() return table_class(entries)
class ItemTableDynamicSubTable(Table): border=True name = Col('Name') description = Col('Description') subtable_options = { 'table_id':'dynamic_subtable', 'border':True } subtable_class = create_table('subtable',options=subtable_options) subtable_class.add_column('col1',Col('col1')) subtable_class.add_column('col2',Col('col2')) subtable = NestedTableCol('Subtable', subtable_class)
def get_machine_activity_table(timestamp_start, timestamp_end): """ Create a CSV listing the amount of time spent for each activity_code.""" # Dynamically create the table using flask-table Tbl = create_table("MachineActivityTable").add_column( 'machine', Col('Machine Activity Durations (minutes)')) # The column names will be the short descriptions of each activity code act_codes = ActivityCode.query.all() activity_code_descriptions = [code.short_description for code in act_codes] for activity_description in activity_code_descriptions: Tbl.add_column(activity_description, Col(activity_description)) # Add the names of scheduled/unscheduled hours as columns schedule_dict = get_schedule_dict( 1, timestamp_start, timestamp_end ) # Get the dict for any machine, just to parse the keys and create columns for key in schedule_dict: Tbl.add_column(key, Col(key)) # Add the class to the table so it's picked up by datatables Tbl.classes = ["dataTable table table-striped table-bordered"] machines = Machine.query.all() items = [] for machine in machines: # Get a dictionary containing all the activities for the machine machine_dict = get_activity_duration_dict( requested_start=timestamp_start, requested_end=timestamp_end, machine_id=machine.id, use_description_as_key=True, units="minutes") # Get a dictionary containing the schedule for the machine machine_dict.update( get_schedule_dict(timestamp_start=timestamp_start, timestamp_end=timestamp_end, machine_id=machine.id, units="minutes")) # Format the times in the dictionary (Do this before adding the machine names) machine_dict = format_dictionary_durations(machine_dict) # The first column will be the name of the machine machine_dict["machine"] = machine.name items.append(machine_dict) table = Tbl(items=items) return table.__html__()
def csv_table(content, delimiter): reader = csv.reader(io.StringIO(content.decode("utf-8")), delimiter=delimiter) headers = next(reader) TableCls = create_table("TableCls") column_names = [column_name(index) for index, _ in enumerate(headers)] app.logger.debug("Column names %s", column_names) for col, name in zip(column_names, headers): TableCls.add_column(col, Col(name)) ItemCls = namedtuple("ItemCls", column_names) table = TableCls((ItemCls(*r) for r in reader), table_id="s3Table") return table
def main(): TableCls = create_table()\ .add_column('name', Col('Name'))\ .add_column('description', Col('Description')) items = [dict(name='Name1', description='Description1'), dict(name='Name2', description='Description2'), dict(name='Name3', description='Description3')] table = TableCls(items) print(table.__html__()) """Outputs:
class DynamicColsInheritTest(TableTest): # Start with MyTable class MyTable(Table): name = Col('Name') # Then dynamically extend it. table_cls = create_table(base=MyTable) table_cls.add_column('number', Col('Number')) def test_one(self): items = [{'name': 'TestName', 'number': 10}] self.assert_html_equivalent_from_file('dynamic_cols_inherit_test', 'test_one', items)
def create_datajoint_table(rels, name='DataJoint Table', selection=None, check_funcs=None, **fetch_kwargs): if not isinstance(rels, list): rels = [rels] table_class = flask_table.create_table(name) if selection is None: selection = set(rels[0].heading.attributes) for rel in rels[1:]: selection &= set(rel.heading.attributes) for col in rels[0].heading.attributes: if col in selection: table_class.add_column(col, flask_table.Col(col)) if check_funcs is not None: for col in check_funcs: table_class.add_column(col, SimpleCheckMarkCol(col)) items = [] for rel in rels: new_items = rel.proj(*rel.heading.non_blobs).fetch(as_dict=True, **fetch_kwargs) for item in new_items: for blob_col in rel.heading.blobs: item[blob_col] = '<BLOB>' if selection is not None: for i in range(len(new_items)): entry = { k: v for k, v in new_items[i].items() if k in selection } if check_funcs is not None: add = {} for col, f in check_funcs.items(): add[col] = f(entry) entry.update(add) new_items[i] = entry items.extend(new_items) table_class.classes = ['Relation'] table = table_class(items) return table
def main(): TableCls = create_table()\ .add_column('name', Col('Name'))\ .add_column('description', Col('Description')) items = [ dict(name='Name1', description='Description1'), dict(name='Name2', description='Description2'), dict(name='Name3', description='Description3') ] table = TableCls(items) print(table.__html__()) """Outputs:
class DynamicColsNumColsTest(TableTest): table_cls = create_table() for i in range(3): table_cls.add_column(str(i), Col(str(i))) def test_one(self): items = [{str(i): i for i in range(3)}] self.assert_html_equivalent_from_file('dynamic_cols_num_cols_test', 'test_one', items) def test_ten(self): items = [{str(i): i for i in range(3)}] * 10 self.assert_html_equivalent_from_file('dynamic_cols_num_cols_test', 'test_ten', items)
def make_Genotype_full_table(results, segment, private=False, classes=()): t = create_table(base=Genotype_full_table) if segment not in ["D", "JH", "JL"]: t._cols["unique_vs"].show = False if segment not in ["VH", "JH"]: t._cols["unique_ds"].show = False if segment not in ["VH", "D", "VL"]: t._cols["unique_js"].show = False if segment not in ["D", "JH", "JL"]: t._cols["unique_vs_unmutated"].show = False if segment not in ["VH", "JH"]: t._cols["unique_ds_unmutated"].show = False if segment not in ["VH", "D", "VL"]: t._cols["unique_js_unmutated"].show = False return t(results, classes=classes)
def dashboard(): form = MemberAccountForm() form.tav.data = 159231 form.remit_date.data = datetime.strptime('3/20/2020', '%m/%d/%Y') form.remit_amount.data = 20009 class DaysAgoCol(Col): def td_format(self, content): today = datetime.now() age = relativedelta(today, content) years = age.years months = age.months days = age.days hours = age.hours minutes = age.minutes if years: s = str(years) + (' years' if years > 1 else ' year') elif months: s = str(months) + (' months' if months > 1 else ' month') elif days: s = str(days) + (' days' if days > 1 else ' day') elif hours: s = str(hours) + (' hours' if hours > 1 else ' hour') elif minutes: s = str(minutes) + (' minutes' if minutes > 1 else ' minute') else: s = 'A few seconds ' return content.strftime('%Y-%m-%d') + ' (' + s + ' ago)' LoanTable = create_table('LoanTable')\ .add_column('date_filed', DateCol('Date Filed', date_format='YYYY-MM-dd'))\ .add_column('date_filed', DaysAgoCol('Date Filed'))\ .add_column('amount', Col('Principal'))\ .add_column('terms', Col('Terms')) LoanTable.classes = ['table', 'table-condensed', 'table-striped'] loans = Loan.query.filter_by(user_id=current_user.id)\ .order_by(Loan.date_filed.desc()).limit(5).all() table = LoanTable(loans) services = Service.query.order_by(Service.id).all() return render_template('main/dashboard.html', form=form, services=services, loans=loans, table=table)
def djtable(table, **kwargs): tbl_cls = create_table(table.__class__.__name__) for col in table.heading.non_blobs: tbl_cls.add_column(col, Col(col)) for col in table.heading.blobs: tbl_cls.add_column(col, Col(col)) content = table.proj(*table.heading.non_blobs).fetch(as_dict=True, **kwargs) for d in content: for col in table.heading.blobs: d[col] = '- blob -' tbl_cls.classes = ['Relation'] table = tbl_cls(content) return table
class DynamicColsOptionsTest(TableTest): tbl_options = dict(classes=['cls1', 'cls2'], thead_classes=['cls_head1', 'cls_head2'], no_items='Empty') table_cls = create_table(options=tbl_options) table_cls.add_column('name', Col('Name Heading')) def test_one(self): items = [Item(name='one')] self.assert_html_equivalent_from_file('dynamic_cols_options_test', 'test_one', items) def test_none(self): items = [] self.assert_html_equivalent_from_file('dynamic_cols_options_test', 'test_none', items)
def tabulate(stats): # create a nested table using NestedTableCol TopTable = create_table('TopTable', base=Table) # Mung data until it looks good for tabulation: items = {} for series in stats: t_data = transpose(stats[series]) # Transpose row/col ordering headers = t_data[0] # Separate out headers t_data = [dict(zip(headers, v)) for v in t_data[1:]] # Separate the rest of the rows items[series.lower() + '_table'] = t_data # Store items for table construction table = get_table(headers, t_data, series) # Construct sub-table class # Tabulate the data: add column to top-level table for this series TopTable.add_column(series.lower() + '_table', NestedTableCol(dh.TYPE_LABELS[series], table.__class__)) return TopTable([items])
def get_user_activity_table(timestamp_start, timestamp_end): """Create a table listing the amount of time spent for each activity_code""" # Dynamically create the table using flask-table Tbl = create_table("UserActivityTable").add_column( 'user', Col('User Activity Durations (minutes)')) # The column names will be the short descriptions of each activity code act_codes = ActivityCode.query.all() activity_code_descriptions = [code.short_description for code in act_codes] # Remove the value for no user, so we don't show a value for "No User" in the user CSV no_user_description = ActivityCode.query.get( Config.NO_USER_CODE_ID).short_description activity_code_descriptions.remove(no_user_description) for activity_description in activity_code_descriptions: Tbl.add_column(activity_description, Col(activity_description)) # Add the html class to the table so it's picked up by datatables Tbl.classes = ["dataTable table table-striped table-bordered"] users = User.query.all() items = [] no_user_description = ActivityCode.query.get( Config.NO_USER_CODE_ID).short_description for user in users: # Get a dict with the activities in user_dict = get_activity_duration_dict(requested_start=timestamp_start, requested_end=timestamp_end, user_id=user.id, use_description_as_key=True, units="minutes") user_dict = format_dictionary_durations(user_dict) user_dict["user"] = user.username user_dict.pop(no_user_description ) # Don't show a value for "No User" in the user CSV items.append(user_dict) table = Tbl(items=items) return table.__html__()
def create_pandas_table(rels, name='Pandas Table', selection=None, check_funcs=None, **fetch_kwargs): if not isinstance(rels, list): rels = [rels] table_class = flask_table.create_table(name) if selection is None: selection = set(rels[0].columns) for rel in rels[1:]: selection &= set(rel.columns) for col in rels[0].columns: if col in selection: table_class.add_column(col, flask_table.Col(col)) if check_funcs is not None: for col in check_funcs: table_class.add_column(col, SimpleCheckMarkCol(col)) items = [] for new_items in rels: for d in map(lambda x: x[1].to_dict(), new_items.iterrows()): if selection is not None: entry = {k: v for k, v in d.items() if k in selection} else: entry = d if check_funcs is not None: add = {} for col, f in check_funcs.items(): add[col] = f(entry) entry.update(add) items.append(entry) table_class.classes = ['Relation'] table = table_class(items) return table
def tabulate(stats): # create a nested table using NestedTableCol TopTable = create_table('TopTable', base=Table) # Mung data until it looks good for tabulation: items = {} for series in stats: t_data = transpose(stats[series]) # Transpose row/col ordering headers = t_data[0] # Separate out headers t_data = [dict(zip(headers, v)) for v in t_data[1:]] # Separate the rest of the rows items[series.lower() + '_table'] = t_data # Store items for table construction table = get_table(headers, t_data, series) # Construct sub-table class # Tabulate the data: add column to top-level table for this series TopTable.add_column( series.lower() + '_table', NestedTableCol(dh.TYPE_LABELS[series], table.__class__)) return TopTable([items])
def dynamic_table_custom_rows(contents,name='Dynamic Table Custom Rows', **sort_kwargs): def dynamic_get_tr_attrs(self, item, reverse=False): if item['age'] ==22: return {'bgcolor':'#FCA5A4'} else: return {} options = dict( border = True, allow_sort = False, no_items = "No data", html_attrs = {"style":'font-size:18px'}, classes = ["table-striped"] ) table_class = create_table(name,options=options) table_class.get_tr_attrs = dynamic_get_tr_attrs # print(table_class.tr_attrs) table_class.add_column('age',Col('age')) table_class.add_column('sex',Col('sex')) table = table_class(contents) return table
def create_custom_border_table(contents,name='Dynamic Table', **sort_kwargs): def dynamic_sort_url(self, col_key, reverse=False): if reverse: direction = 'desc' else: direction = 'asc' return url_for('main.flask_table_custom_border', sort=col_key, direction=direction) def get_tr_attrs(self, item): if item: return {'style': 'outline: thin solid'} else: return {} options = dict( border = True, allow_sort = True, no_items = "No Samples", html_attrs = {"style":'font-size:18px'}, table_id = 'vert_table', classes = ["table-striped"] ) table_class = create_table(name,options=options) table_class.sort_url = dynamic_sort_url sort = sort_kwargs.get('sort_by') reverse = sort_kwargs.get('sort_reverse') table_class.add_column('state',Col('state')) table_class.add_column('clearing parameters',EmptyCol('clearing parameters')) table_class.add_column('county',Col('county')) sorted_contents = sorted(contents.fetch(as_dict=True), key=partial(table_sorter,sort_key=sort),reverse=reverse) table = table_class(sorted_contents) table.sort_by = sort table.sort_reverse = reverse return table
def generate_table( device_type: str, device_id: int or str) -> 'flask_table Table object' or None: """ generate html table according to device type and device_id :param string device_type: :param int or str device_id: :return: flask_table Table object or None """ table = find_database_table(device_type) devices = db.session.query( table.device_id).distinct() # find all distinct devices available_devices = [] table = None for device in devices: device = Device.query.filter_by(id=device.device_id).first() if device.id == int( device_id ): # only record devices with different id from booked device pass elif device.device_inuse: # only record devices not used pass else: available_devices.append({ "device_id": device.id, "device_name": device.name, "booking_link": device.id }) if len(available_devices) != 0: TableCls = create_table('TableCls', options=dict(classes=['table', 'table-bordered'], no_items='No Items')) \ .add_column('device_id', Col('Device ID')) \ .add_column('device_name', Col('Device Name')) \ .add_column('booking_link', LinkCol('Booking Link', 'appointment.calendar', url_kwargs=dict(selected_device='booking_link'))) table = TableCls(available_devices) return table
def model2table(obj, selected): """ Give me an SQLALCHEMY obj to get an HTML table """ table_name = 'Table' + obj.__name__ TableCls = create_table(table_name, base=ItemTable) mapper = inspect(obj) for column in mapper.attrs: # What to skip if selected and column.key not in selected: continue colname = column.key.replace('_', ' ').capitalize() if column.key == 'id': # 'patient_id': TableCls.add_column(column.key, AnchorCol(colname)) else: TableCls.add_column(column.key, Col(colname)) TableCls.classes = ['table', 'table-hover'] TableCls.thead_classes = ["thead-default"] TableCls.allow_sort = True return TableCls
def getStudentFileTable(student_id): FileTableCls = create_table('FileTableCls', options=tbl_options)\ .add_column('container', Col('Container')) FileTableCls.add_column( 'home', HackLinkCol('Home', 'home_file_select', url_kwargs=dict(student_id='student_id', container='container'), attr='home')) FileTableCls.add_column( 'results', HackLinkCol('Results', 'results_file_select', url_kwargs=dict(student_id='student_id', container='container'), attr='results')) student_dir = os.path.join(lab_dir, student_id) glob_mask = '%s/*' % student_id dlist = glob.glob(glob_mask) file_rows = [] for d in dlist: if os.path.isdir(d): container_id = os.path.basename(d) container = container_id.split('.')[1] row = {} row['container'] = container row['home'] = 'home' if hasResults(student_dir, container_id): row['results'] = 'results' else: row['results'] = None row['student_id'] = student_id file_rows.append(row) file_table = FileTableCls(file_rows) return file_table
def __init__(self, data): columns = create_table() columns.add_column("Name", Col("Name")) columns.add_column("Rating", Col("Rating")) columns.add_column("Price", Col("Price Range")) self.table = columns(data)
from stravalib import client, unithelper import datetime from flask_table import create_table, Col, DatetimeCol tableCls=create_table()\ .add_column("dist", Col("Dist"))\ .add_column("date", DatetimeCol("Date"))\ .add_column("time", DatetimeCol("Time"))\ .add_column("pace", Col("Avg. Pace"))\ .add_column("maxPace", Col("Max Pace"))\ .add_column("el", Col("Elevation"))\ .add_column("name", Col("Name")) def minPerMile(meterPerSec): secPerMile=1609.34/float(meterPerSec) return str(datetime.timedelta(seconds=secPerMile)) def runsToTable(runList): items=list() for act in runList: items.append(dict(dist=unithelper.miles(act.distance), time=act.moving_time.seconds, date=act.start_date, pace=minPerMile(act.average_speed), maxPace=minPerMile(act.max_speed), el=act.total_elevation_gain, name=act.name)) return tableCls(items)
def setUp(self): self.table_cls = create_table().add_column('name', Col('Name Heading'))
def setUp(self): self.table_cls = create_table() for i in range(3): self.table_cls.add_column(str(i), Col(str(i)))