0
# Application Resources
1
2
Cross-platform application directory management for user data, site data, cache, and log directories. The resources module provides file operations, subdirectory management with automatic directory creation, and platform-appropriate directory locations following OS conventions.
3
4
## Capabilities
5
6
### Initialization
7
8
Initialize application directories with vendor and application name for cross-platform directory management.
9
10
```python { .api }
11
def init(vendor, name):
12
"""
13
Initialize application directories for the given vendor and application name.
14
15
Args:
16
vendor (str): Vendor/company name
17
name (str): Application name
18
19
Side Effects:
20
Sets up global user, site, cache, and log directory instances
21
with platform-appropriate paths
22
"""
23
```
24
25
**Usage Example:**
26
27
```python
28
from clint import resources
29
30
# Initialize application directories
31
resources.init('MyCompany', 'MyApp')
32
33
# Now you can use the global directory instances
34
config_file = resources.user.write('config.json', '{"setting": "value"}')
35
log_entry = resources.log.append('app.log', 'Application started\n')
36
```
37
38
### Application Directory Class
39
40
Main class for managing application directories with file operations and subdirectory support.
41
42
```python { .api }
43
class AppDir:
44
"""
45
Application Directory object for managing files and subdirectories.
46
47
Args:
48
path (str): Directory path (optional, can be set later)
49
50
Attributes:
51
path (str): The directory path
52
_exists (bool): Internal flag tracking directory existence
53
"""
54
55
def __init__(self, path=None):
56
"""Initialize AppDir with optional path."""
57
```
58
59
### File Writing Operations
60
61
Write content to files within the application directory with automatic directory creation.
62
63
```python { .api }
64
def write(self, filename, content, binary=False):
65
"""
66
Write content to a file in the application directory.
67
68
Args:
69
filename (str): Name of the file to write
70
content (str or bytes): Content to write to the file
71
binary (bool): Whether to write in binary mode (default: False)
72
73
Side Effects:
74
Creates the application directory if it doesn't exist
75
Creates or overwrites the specified file
76
"""
77
78
def append(self, filename, content, binary=False):
79
"""
80
Append content to a file in the application directory.
81
82
Args:
83
filename (str): Name of the file to append to
84
content (str or bytes): Content to append to the file
85
binary (bool): Whether to write in binary mode (default: False)
86
87
Returns:
88
bool: True on successful append
89
90
Side Effects:
91
Creates the application directory if it doesn't exist
92
Creates the file if it doesn't exist, otherwise appends
93
"""
94
```
95
96
**Usage Examples:**
97
98
```python
99
from clint import resources
100
101
resources.init('MyCompany', 'MyApp')
102
103
# Write configuration file
104
resources.user.write('settings.ini', '[DEFAULT]\ntheme=dark\n')
105
106
# Write binary data
107
image_data = b'\x89PNG\r\n\x1a\n...' # PNG file data
108
resources.user.write('avatar.png', image_data, binary=True)
109
110
# Append to log file
111
resources.log.append('error.log', '2023-01-01 12:00:00 - Error occurred\n')
112
113
# Append binary data
114
resources.cache.append('data.bin', b'\x00\x01\x02', binary=True)
115
```
116
117
### File Reading Operations
118
119
Read content from files within the application directory with support for both text and binary modes.
120
121
```python { .api }
122
def read(self, filename, binary=False):
123
"""
124
Read content from a file in the application directory.
125
126
Args:
127
filename (str): Name of the file to read
128
binary (bool): Whether to read in binary mode (default: False)
129
130
Returns:
131
str or bytes or None: File content, or None if file doesn't exist
132
"""
133
134
def open(self, filename, mode='r'):
135
"""
136
Open a file in the application directory and return file object.
137
138
Args:
139
filename (str): Name of the file to open
140
mode (str): File open mode ('r', 'w', 'a', 'rb', etc.)
141
142
Returns:
143
file: File object for the opened file
144
"""
145
```
146
147
**Usage Examples:**
148
149
```python
150
from clint import resources
151
152
resources.init('MyCompany', 'MyApp')
153
154
# Read text file
155
config_content = resources.user.read('config.txt')
156
if config_content:
157
print("Config:", config_content)
158
159
# Read binary file
160
image_data = resources.user.read('avatar.png', binary=True)
161
if image_data:
162
print("Image size:", len(image_data), "bytes")
163
164
# Use file object for more control
165
with resources.log.open('app.log', 'r') as f:
166
for line in f:
167
if 'ERROR' in line:
168
print("Error found:", line.strip())
169
170
# Write with file object
171
with resources.user.open('data.csv', 'w') as f:
172
f.write('name,age,city\n')
173
f.write('John,25,NYC\n')
174
```
175
176
### File and Directory Management
177
178
Delete files and directories, and manage subdirectories within the application directory.
179
180
```python { .api }
181
def delete(self, filename=''):
182
"""
183
Delete a file or directory within the application directory.
184
185
Args:
186
filename (str): Name of file/directory to delete, or empty string
187
to delete the application directory itself
188
189
Side Effects:
190
Removes the specified file or directory
191
Ignores errors if file/directory doesn't exist
192
"""
193
194
def sub(self, path):
195
"""
196
Create an AppDir instance for a subdirectory.
197
198
Args:
199
path (str or list): Subdirectory path or path components
200
201
Returns:
202
AppDir: New AppDir instance for the subdirectory
203
"""
204
```
205
206
**Usage Examples:**
207
208
```python
209
from clint import resources
210
211
resources.init('MyCompany', 'MyApp')
212
213
# Create subdirectory
214
config_dir = resources.user.sub('config')
215
config_dir.write('database.ini', '[database]\nhost=localhost\n')
216
217
# Nested subdirectories
218
temp_dir = resources.cache.sub(['temp', 'downloads'])
219
temp_dir.write('file.tmp', 'temporary data')
220
221
# Delete specific file
222
resources.log.delete('old.log')
223
224
# Delete subdirectory
225
config_dir.delete() # Deletes the entire config subdirectory
226
227
# Path components as list
228
logs_dir = resources.log.sub(['application', 'errors'])
229
logs_dir.write('critical.log', 'Critical error occurred')
230
```
231
232
### Global Directory Instances
233
234
Pre-configured global directory instances available after initialization.
235
236
```python { .api }
237
user = AppDir() # User data directory
238
site = AppDir() # Site-wide data directory
239
cache = AppDir() # User cache directory
240
log = AppDir() # User log directory
241
```
242
243
**Platform-specific Directory Locations:**
244
245
After calling `resources.init('Vendor', 'App')`, directories are set to platform-appropriate locations:
246
247
- **Linux/Unix**:
248
- user: `~/.local/share/App`
249
- cache: `~/.cache/App`
250
- log: `~/.cache/App/log`
251
252
- **macOS**:
253
- user: `~/Library/Application Support/App`
254
- cache: `~/Library/Caches/App`
255
- log: `~/Library/Logs/App`
256
257
- **Windows**:
258
- user: `%APPDATA%\Vendor\App`
259
- cache: `%LOCALAPPDATA%\Vendor\App\Cache`
260
- log: `%LOCALAPPDATA%\Vendor\App\Logs`
261
262
**Usage Examples:**
263
264
```python
265
from clint import resources
266
267
# Must initialize first
268
resources.init('MyCompany', 'MyApp')
269
270
# User data (settings, user files)
271
resources.user.write('preferences.json', '{"theme": "dark"}')
272
273
# Site-wide data (shared across users)
274
resources.site.write('templates.json', '{"default": "template.html"}')
275
276
# Cache data (temporary, can be deleted)
277
resources.cache.write('downloaded_data.json', '{"cached_at": "2023-01-01"}')
278
279
# Log files
280
resources.log.write('app.log', '2023-01-01 12:00:00 - App started\n')
281
resources.log.append('app.log', '2023-01-01 12:01:00 - User logged in\n')
282
```
283
284
### Exception Handling
285
286
Exception raised when attempting to use directories before initialization.
287
288
```python { .api }
289
class NotConfigured(IOError):
290
"""
291
Exception raised when attempting to use AppDir before calling init().
292
293
Raised when:
294
- File operations are attempted on uninitialized AppDir instances
295
- Global directory instances are used before resources.init()
296
"""
297
```
298
299
**Usage Example:**
300
301
```python
302
from clint import resources
303
304
try:
305
# This will raise NotConfigured
306
resources.user.write('test.txt', 'content')
307
except resources.NotConfigured:
308
print("Must call resources.init() first")
309
resources.init('MyCompany', 'MyApp')
310
resources.user.write('test.txt', 'content') # Now works
311
```
312
313
## Complete Usage Pattern
314
315
```python
316
from clint import resources
317
318
# Initialize application directories
319
resources.init('MyCompany', 'AwesomeApp')
320
321
# Write configuration
322
config = {
323
'database_url': 'sqlite:///app.db',
324
'debug': False,
325
'log_level': 'INFO'
326
}
327
resources.user.write('config.json', json.dumps(config, indent=2))
328
329
# Create organized subdirectories
330
db_dir = resources.user.sub('database')
331
db_dir.write('schema.sql', 'CREATE TABLE users (id INTEGER PRIMARY KEY);')
332
333
templates_dir = resources.site.sub('templates')
334
templates_dir.write('base.html', '<html><head><title>{{title}}</title></head></html>')
335
336
# Cache management
337
cache_data = {'last_update': '2023-01-01', 'version': '1.0'}
338
resources.cache.write('metadata.json', json.dumps(cache_data))
339
340
# Logging setup
341
import datetime
342
log_entry = f"{datetime.datetime.now()} - Application initialized\n"
343
resources.log.write('app.log', log_entry)
344
345
# Clean up old cache files
346
resources.cache.delete('old_cache.json')
347
348
# Read configuration on startup
349
saved_config = resources.user.read('config.json')
350
if saved_config:
351
config = json.loads(saved_config)
352
print(f"Loaded config: {config}")
353
```