An admin interface that builds itself from the dbbasic modules you install; its pages follow file paths, like CGI.

0 downloads

Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-admin.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-admin.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-admin.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

danq9 Add automatic TSV discovery and admin handlers 5e2fd8f 1 year, 1 month ago History
discover.py · 3.8 KB · 150 lines
1"""
2TSV table auto-discovery for admin interface
3"""
4import os
5from pathlib import Path
6from typing import List, Dict, Any
7
8
9def get_data_dir() -> Path:
10 """Get the data directory path"""
11 # Look for data directory in current working directory
12 cwd = Path.cwd()
13 data_dir = cwd / "data"
14
15 if not data_dir.exists():
16 # Try _data as alternative
17 data_dir = cwd / "_data"
18
19 return data_dir
20
21
22def discover_tsv_tables() -> List[Dict[str, Any]]:
23 """
24 Auto-discover TSV tables in the data directory.
25
26 Returns:
27 List of dicts with table metadata:
28 [
29 {
30 'name': 'posts',
31 'file': 'data/posts.tsv',
32 'size': 12345,
33 'rows': 42,
34 'columns': ['id', 'title', 'content', 'author', 'created']
35 },
36 ...
37 ]
38 """
39 data_dir = get_data_dir()
40
41 if not data_dir.exists():
42 return []
43
44 tables = []
45
46 # Find all .tsv files
47 for tsv_file in data_dir.glob("*.tsv"):
48 try:
49 # Get file size
50 file_size = tsv_file.stat().st_size
51
52 # Read first line to get columns
53 columns = []
54 row_count = 0
55
56 with open(tsv_file, 'r', encoding='utf-8') as f:
57 # First line is column headers
58 first_line = f.readline().strip()
59 if first_line:
60 columns = first_line.split('\t')
61 row_count = 1 # header
62
63 # Count remaining rows
64 for line in f:
65 if line.strip():
66 row_count += 1
67
68 tables.append({
69 'name': tsv_file.stem,
70 'file': str(tsv_file.relative_to(Path.cwd())),
71 'size': file_size,
72 'rows': max(0, row_count - 1), # Exclude header from count
73 'columns': columns
74 })
75
76 except Exception as e:
77 # Skip files we can't read
78 print(f"Warning: Could not read {tsv_file}: {e}")
79 continue
80
81 # Sort by name
82 tables.sort(key=lambda x: x['name'])
83
84 return tables
85
86
87def read_tsv_data(table_name: str, limit: int = 100) -> List[Dict[str, str]]:
88 """
89 Read data from a TSV table.
90
91 Args:
92 table_name: Name of the table (without .tsv extension)
93 limit: Maximum number of rows to return
94
95 Returns:
96 List of dicts, one per row
97 """
98 data_dir = get_data_dir()
99 tsv_file = data_dir / f"{table_name}.tsv"
100
101 if not tsv_file.exists():
102 return []
103
104 rows = []
105
106 try:
107 with open(tsv_file, 'r', encoding='utf-8') as f:
108 # Read header
109 header_line = f.readline().strip()
110 if not header_line:
111 return []
112
113 columns = header_line.split('\t')
114
115 # Read data rows
116 for i, line in enumerate(f):
117 if i >= limit:
118 break
119
120 line = line.strip()
121 if not line:
122 continue
123
124 values = line.split('\t')
125
126 # Pad values if needed
127 while len(values) < len(columns):
128 values.append('')
129
130 # Create dict
131 row_dict = dict(zip(columns, values))
132 rows.append(row_dict)
133
134 except Exception as e:
135 print(f"Error reading {tsv_file}: {e}")
136 return []
137
138 return rows
139
140
141def format_file_size(size_bytes: int) -> str:
142 """Format file size in human-readable format"""
143 if size_bytes < 1024:
144 return f"{size_bytes} B"
145 elif size_bytes < 1024 * 1024:
146 return f"{size_bytes / 1024:.1f} KB"
147 elif size_bytes < 1024 * 1024 * 1024:
148 return f"{size_bytes / (1024 * 1024):.1f} MB"
149 else:
150 return f"{size_bytes / (1024 * 1024 * 1024):.1f} GB"