0
# Lona
1
2
A comprehensive Python web application framework that enables developers to build responsive, interactive web applications entirely in Python without requiring separate JavaScript development. Lona provides a unified architecture where both server-side logic and client-side interactions are handled through Python code, using a specialized protocol that communicates between a Python backend and a JavaScript browser library.
3
4
## Package Information
5
6
- **Package Name**: lona
7
- **Language**: Python
8
- **Installation**: `pip install lona`
9
10
## Core Imports
11
12
```python
13
import lona
14
from lona import App, View, Request, Route, Channel, Bucket, MATCH_ALL
15
```
16
17
Common imports for HTML and responses:
18
19
```python
20
from lona.html import HTML, H1, H2, P, Div, Button, Input, Form
21
from lona.responses import Response, HtmlResponse, JsonResponse, RedirectResponse
22
```
23
24
Event handling:
25
26
```python
27
from lona.events import CLICK, CHANGE, FOCUS, BLUR
28
```
29
30
## Basic Usage
31
32
```python
33
from lona import App, View
34
from lona.html import HTML, H1, Button, P
35
36
# Create the app
37
app = App(__file__)
38
39
# Define a simple view
40
@app.route('/')
41
class IndexView(View):
42
def handle_request(self, request):
43
return HTML(
44
H1('Welcome to Lona'),
45
P('This is a simple web application built with Python!')
46
)
47
48
# Define an interactive view
49
@app.route('/interactive')
50
class InteractiveView(View):
51
def handle_request(self, request):
52
click_count = 0
53
button = Button('Click me!')
54
counter = P(f'Clicks: {click_count}')
55
56
html = HTML(
57
H1('Interactive Example'),
58
counter,
59
button
60
)
61
62
self.show(html)
63
64
# Handle button clicks
65
while True:
66
self.await_click(button)
67
click_count += 1
68
counter.set_text(f'Clicks: {click_count}')
69
70
# Run the application
71
if __name__ == '__main__':
72
app.run(host='localhost', port=8080)
73
```
74
75
## Architecture
76
77
Lona's architecture eliminates the traditional frontend/backend separation by providing:
78
79
- **Server-side Views**: Python classes that handle both HTTP requests and real-time user interactions
80
- **HTML Object Model**: Python objects representing HTML elements with automatic DOM synchronization
81
- **Event System**: Async event handling for user interactions (clicks, form changes, etc.)
82
- **Channel Communication**: Pub/sub messaging system for inter-view communication
83
- **File Management**: Secure file upload/download with bucket system
84
- **Response System**: Multiple response types including HTML, JSON, templates, and redirects
85
86
This design allows Python developers to create full-stack web applications using familiar Python patterns while automatically handling client-server communication, DOM manipulation, and real-time updates.
87
88
## Capabilities
89
90
### Core Application Framework
91
92
Essential classes and patterns for building Lona web applications, including the main App class, View base class for handling requests and interactions, and Request objects containing HTTP data.
93
94
```python { .api }
95
class App:
96
def __init__(self, script_path: str): ...
97
def route(self, raw_pattern: str | int, name: str = '', interactive: bool = True,
98
http_pass_through: bool = False, frontend_view=None): ...
99
def run(self, host: str = 'localhost', port: int = 8080, **kwargs): ...
100
101
class View:
102
def handle_request(self, request: 'Request'): ...
103
def show(self, html=None, template: str = None, template_string: str = None,
104
title: str = None, template_context: dict = None): ...
105
def await_click(self, *nodes, timeout=None): ...
106
def await_change(self, *nodes, timeout=None): ...
107
def send_str(self, string: str, broadcast: bool = False,
108
filter_connections=None, wait: bool = True): ...
109
def fire_view_event(self, name: str, data=None): ...
110
def subscribe(self, topic: str, handler, implicit_show: bool = True): ...
111
def ping(self) -> str: ...
112
113
class Request:
114
GET: dict
115
POST: dict
116
method: str
117
url: str
118
user: object
119
id: str
120
interactive: bool
121
server: 'Server'
122
route: 'Route'
123
match_info: dict
124
```
125
126
[Core Framework](./core-framework.md)
127
128
### HTML System
129
130
Comprehensive HTML element system with 60+ node classes covering all HTML5 elements, plus utilities for HTML parsing and document building. All HTML elements support event handling and real-time updates.
131
132
```python { .api }
133
def HTML(*args, **kwargs) -> 'Node': ...
134
135
class Node:
136
def __init__(self, *args, **kwargs): ...
137
def set_text(self, text: str): ...
138
def append(self, *nodes): ...
139
140
# Document structure
141
class Html(Node): ...
142
class Head(Node): ...
143
class Body(Node): ...
144
class Title(Node): ...
145
146
# Common elements
147
class H1(Node): ...
148
class P(Node): ...
149
class Div(Node): ...
150
class Button(Node): ...
151
class Input(Node): ...
152
```
153
154
[HTML System](./html-system.md)
155
156
### Response Types
157
158
Various response classes for different content types and HTTP behaviors, including HTML responses, JSON responses, template responses, file downloads, and redirects.
159
160
```python { .api }
161
class Response:
162
def __init__(self, content: str = '', status: int = 200, headers: dict = None): ...
163
164
class HtmlResponse(Response):
165
def __init__(self, html, status: int = 200, headers: dict = None): ...
166
167
class JsonResponse(Response):
168
def __init__(self, json_data, status: int = 200, headers: dict = None): ...
169
170
class RedirectResponse(Response):
171
def __init__(self, redirect_url: str): ...
172
173
class FileResponse(Response):
174
def __init__(self, path: str, content_type: str = None, as_attachment: bool = False): ...
175
```
176
177
[Response System](./response-system.md)
178
179
### Events and Interactivity
180
181
Event system for handling user interactions including clicks, form changes, focus events, and custom events. Supports both synchronous and asynchronous event handling patterns.
182
183
```python { .api }
184
# Event constants
185
CLICK: int
186
CHANGE: int
187
FOCUS: int
188
BLUR: int
189
190
class InputEvent:
191
def __init__(self, event_type, node, data: dict = None): ...
192
193
# View event methods
194
def await_input_event(self, *nodes, timeout=None) -> 'InputEvent': ...
195
def await_click(self, *nodes, timeout=None) -> 'InputEvent': ...
196
def await_change(self, *nodes, timeout=None) -> 'InputEvent': ...
197
def fire_view_event(self, name: str, data=None): ...
198
```
199
200
[Events and Interactivity](./events-interactivity.md)
201
202
### Channel Communication
203
204
Pub/sub messaging system for communication between views, background tasks, and external services. Supports topic-based messaging with message expiry and local/broadcast modes.
205
206
```python { .api }
207
class Channel:
208
def __init__(self, topic: str): ...
209
def subscribe(self, handler): ...
210
def unsubscribe(self): ...
211
def send(self, message_data=None, expiry=None, local: bool = False): ...
212
213
class Message:
214
topic: str
215
data: object
216
timestamp: float
217
```
218
219
[Channel Communication](./channel-communication.md)
220
221
### File Management
222
223
Secure file upload and download system using bucket containers with configurable limits, automatic URL generation, and integration with view lifecycle.
224
225
```python { .api }
226
class Bucket:
227
def __init__(self, request, max_files: int = None, max_size: int = None,
228
index: bool = True, on_add=None, on_delete=None): ...
229
def get_path(self, file_name: str = '') -> str: ...
230
def get_url(self, file_name: str = '') -> str: ...
231
def get_file_names(self) -> list: ...
232
def get_size(self) -> int: ...
233
def get_add_url(self) -> str: ...
234
def get_delete_url(self, file_name: str) -> str: ...
235
```
236
237
[File Management](./file-management.md)
238
239
### Routing and URLs
240
241
URL routing system with pattern matching, named routes, and support for both interactive and non-interactive views. Includes route decorators and programmatic route registration.
242
243
```python { .api }
244
class Route:
245
def __init__(self, raw_pattern: str, view, name: str = '',
246
interactive: bool = True, http_pass_through: bool = False): ...
247
248
# Route matching constant (value = 1)
249
MATCH_ALL: int
250
251
# App routing methods
252
def route(self, raw_pattern: str | int, name: str = '', interactive: bool = True,
253
http_pass_through: bool = False, frontend_view=None): ...
254
def add_route(self, route: 'Route'): ...
255
```
256
257
[Routing and URLs](./routing-urls.md)
258
259
### Static Files and Assets
260
261
Static file management system for CSS, JavaScript, images, and other assets with automatic URL generation, dependency ordering, and development/production optimization.
262
263
```python { .api }
264
class StaticFile:
265
def __init__(self, name: str, path: str = '', string: str = ''): ...
266
267
class StyleSheet(StaticFile): ...
268
class Script(StaticFile): ...
269
270
# Sort order constants
271
class SORT_ORDER:
272
FRAMEWORK: int
273
LIBRARY: int
274
APPLICATION: int
275
```
276
277
[Static Files and Assets](./static-files-assets.md)
278
279
### Exception Handling
280
281
Exception and error handling classes for view lifecycle management, HTTP errors, and custom error responses with built-in error view support.
282
283
```python { .api }
284
# View control exceptions
285
class StopReason(Exception): ...
286
class UserAbort(StopReason): ...
287
class ServerStop(StopReason): ...
288
289
# HTTP error classes
290
class ForbiddenError(Exception): ...
291
class NotFoundError(Exception): ...
292
class ClientError(Exception): ...
293
```
294
295
[Exception Handling](./exception-handling.md)
296
297
## Constants
298
299
```python { .api }
300
# Package version information
301
VERSION: tuple # Version tuple (major, minor, patch)
302
VERSION_STRING: str # Version as string (e.g., "1.16.2")
303
304
# Route matching
305
MATCH_ALL: int = 1 # Matches any URL pattern
306
```
307
308
## Types
309
310
```python { .api }
311
# Core type definitions used across capabilities
312
from typing import Union, Optional, Dict, List, Callable, Any
313
314
NodeContent = Union[str, int, float, 'Node']
315
HTMLContent = Union[NodeContent, List[NodeContent]]
316
EventHandler = Callable[['InputEvent'], None]
317
ChannelHandler = Callable[['Message'], None]
318
ViewHandler = Callable[['Request'], Any]
319
MiddlewareHandler = Callable[['Request'], 'Request']
320
```