perspective-python 4.5.2__cp311-abi3-pyemscripten_2025_0_wasm32.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. perspective/__init__.py +403 -0
  2. perspective/extension/finos-perspective-nbextension.json +5 -0
  3. perspective/handlers/__init__.py +11 -0
  4. perspective/handlers/aiohttp.py +69 -0
  5. perspective/handlers/starlette.py +63 -0
  6. perspective/handlers/tornado.py +192 -0
  7. perspective/perspective.abi3.so +0 -0
  8. perspective/templates/exported_widget.html.template +35 -0
  9. perspective/tests/__init__.py +11 -0
  10. perspective/tests/async/test_async_client.py +83 -0
  11. perspective/tests/async/test_websocket_client.py +124 -0
  12. perspective/tests/conftest.py +263 -0
  13. perspective/tests/core/__init__.py +11 -0
  14. perspective/tests/core/test_async.py +351 -0
  15. perspective/tests/multi_threaded/__init__.py +11 -0
  16. perspective/tests/multi_threaded/test_multi_threaded.py +201 -0
  17. perspective/tests/server/__init__.py +11 -0
  18. perspective/tests/server/test_server.py +1016 -0
  19. perspective/tests/server/test_session.py +110 -0
  20. perspective/tests/table/__init__.py +11 -0
  21. perspective/tests/table/arrow/date32.arrow +0 -0
  22. perspective/tests/table/arrow/date64.arrow +0 -0
  23. perspective/tests/table/arrow/dict.arrow +0 -0
  24. perspective/tests/table/arrow/dict_update.arrow +0 -0
  25. perspective/tests/table/arrow/int_float_str.arrow +0 -0
  26. perspective/tests/table/arrow/int_float_str_file.arrow +0 -0
  27. perspective/tests/table/arrow/int_float_str_update.arrow +0 -0
  28. perspective/tests/table/object_sequence.py +402 -0
  29. perspective/tests/table/test_column_paths.py +89 -0
  30. perspective/tests/table/test_delete.py +124 -0
  31. perspective/tests/table/test_exception.py +65 -0
  32. perspective/tests/table/test_join.py +115 -0
  33. perspective/tests/table/test_leaks.py +105 -0
  34. perspective/tests/table/test_ports.py +178 -0
  35. perspective/tests/table/test_remove.py +102 -0
  36. perspective/tests/table/test_table.py +641 -0
  37. perspective/tests/table/test_table_arrow.py +500 -0
  38. perspective/tests/table/test_table_datetime.py +2409 -0
  39. perspective/tests/table/test_table_infer.py +201 -0
  40. perspective/tests/table/test_table_limit.py +45 -0
  41. perspective/tests/table/test_table_numpy.py +1022 -0
  42. perspective/tests/table/test_table_page_to_disk.py +304 -0
  43. perspective/tests/table/test_table_pandas.py +1018 -0
  44. perspective/tests/table/test_table_polars.py +251 -0
  45. perspective/tests/table/test_table_view_table.py +130 -0
  46. perspective/tests/table/test_to_arrow.py +417 -0
  47. perspective/tests/table/test_to_arrow_lz4.py +32 -0
  48. perspective/tests/table/test_to_format.py +1024 -0
  49. perspective/tests/table/test_to_polars.py +26 -0
  50. perspective/tests/table/test_update.py +536 -0
  51. perspective/tests/table/test_update_arrow.py +980 -0
  52. perspective/tests/table/test_update_pandas.py +211 -0
  53. perspective/tests/table/test_view.py +2444 -0
  54. perspective/tests/table/test_view_expression.py +1940 -0
  55. perspective/tests/test_dependencies.py +53 -0
  56. perspective/tests/viewer/__init__.py +11 -0
  57. perspective/tests/viewer/test_viewer.py +246 -0
  58. perspective/tests/virtual_servers/__init__.py +12 -0
  59. perspective/tests/virtual_servers/test_coerce_types.py +209 -0
  60. perspective/tests/virtual_servers/test_duckdb.py +908 -0
  61. perspective/tests/virtual_servers/test_polars.py +1032 -0
  62. perspective/tests/widget/__init__.py +11 -0
  63. perspective/tests/widget/test_widget.py +278 -0
  64. perspective/tests/widget/test_widget_pandas.py +453 -0
  65. perspective/virtual_servers/__init__.py +142 -0
  66. perspective/virtual_servers/clickhouse.py +240 -0
  67. perspective/virtual_servers/duckdb.py +236 -0
  68. perspective/virtual_servers/polars.py +710 -0
  69. perspective/widget/__init__.py +349 -0
  70. perspective/widget/viewer/__init__.py +15 -0
  71. perspective/widget/viewer/validate.py +22 -0
  72. perspective/widget/viewer/viewer.py +343 -0
  73. perspective/widget/viewer/viewer_traitlets.py +101 -0
  74. perspective_python-4.5.2.dist-info/METADATA +29 -0
  75. perspective_python-4.5.2.dist-info/RECORD +79 -0
  76. perspective_python-4.5.2.dist-info/WHEEL +4 -0
  77. perspective_python-4.5.2.dist-info/licenses/LICENSE.md +193 -0
  78. perspective_python-4.5.2.dist-info/licenses/LICENSE_THIRDPARTY_cargo.yml +19255 -0
  79. perspective_python-4.5.2.dist-info/sboms/perspective-python.cyclonedx.json +5546 -0
@@ -0,0 +1,403 @@
1
+ # ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
2
+ # ┃ ██████ ██████ ██████ █ █ █ █ █ █▄ ▀███ █ ┃
3
+ # ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█ ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄ ▀█ █ ▀▀▀▀▀ ┃
4
+ # ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄ █ ▄▄▄▄▄ ┃
5
+ # ┃ █ ██████ █ ▀█▄ █ ██████ █ ███▌▐███ ███████▄ █ ┃
6
+ # ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫
7
+ # ┃ Copyright (c) 2017, the Perspective Authors. ┃
8
+ # ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃
9
+ # ┃ This file is part of the Perspective library, distributed under the terms ┃
10
+ # ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃
11
+ # ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
12
+
13
+ __version__ = "4.5.2"
14
+ __all__ = [
15
+ "_jupyter_labextension_paths",
16
+ "Server",
17
+ "Client",
18
+ "Table",
19
+ "View",
20
+ "PerspectiveError",
21
+ "ProxySession",
22
+ "AsyncClient",
23
+ "AsyncServer",
24
+ "GenericSQLVirtualServerModel",
25
+ "VirtualDataSlice",
26
+ "VirtualServer",
27
+ "num_cpus",
28
+ "set_num_cpus",
29
+ "system_info",
30
+ ]
31
+
32
+ __doc__ = """
33
+ The Python language bindings for [Perspective](https://perspective-dev.github.io), a
34
+ high performance data-visualization and analytics component for the web browser.
35
+
36
+ A simple example which loads an [Apache Arrow](https://arrow.apache.org/) and
37
+ computes a "Group By" operation, returning a new Arrow.
38
+
39
+ ```python
40
+ from perspective import Server
41
+
42
+ client = Server().new_local_client()
43
+ table = client.table(arrow_bytes_data)
44
+ view = table.view(group_by = ["CounterParty", "Security"])
45
+ arrow = view.to_arrow()
46
+ ```
47
+
48
+ Perspective for Python uses the exact same C++ data engine used by the
49
+ [WebAssembly version](https://docs.rs/perspective-js/latest/perspective_js/) and
50
+ [Rust version](https://docs.rs/crate/perspective/latest). The library consists
51
+ of many of the same abstractions and API as in JavaScript, as well as
52
+ Python-specific data loading support for [NumPy](https://numpy.org/),
53
+ [Pandas](https://pandas.pydata.org/) (and
54
+ [Apache Arrow](https://arrow.apache.org/), as in JavaScript).
55
+
56
+ Additionally, `perspective-python` provides a session manager suitable for
57
+ integration into server systems such as
58
+ [Tornado websockets](https://www.tornadoweb.org/en/stable/websocket.html),
59
+ [AIOHTTP](https://docs.aiohttp.org/en/stable/web_quickstart.html#websockets), or
60
+ [Starlette](https://www.starlette.io/websockets/)/[FastAPI](https://fastapi.tiangolo.com/advanced/websockets/),
61
+ which allows fully _virtual_ Perspective tables to be interacted with by
62
+ multiple `<perspective-viewer>` in a web browser. You can also interact with a
63
+ Perspective table from python clients, and to that end client libraries are
64
+ implemented for both Tornado and AIOHTTP.
65
+
66
+ As `<perspective-viewer>` will only consume the data necessary to render the
67
+ current screen, this runtime mode allows _ludicrously-sized_ datasets with
68
+ instant-load after they've been manifest on the server (at the expense of
69
+ network latency on UI interaction).
70
+
71
+ The included `PerspectiveWidget` allows running such a viewer in
72
+ [JupyterLab](https://jupyterlab.readthedocs.io/en/stable/) in either server or
73
+ client (via WebAssembly) mode, and the included `PerspectiveTornadoHandler`
74
+ makes it simple to extend a Tornado server with virtual Perspective support.
75
+
76
+ The `perspective` module exports several tools:
77
+
78
+ - `Server` the constructor for a new isntance of the Perspective data engine.
79
+ - The `perspective.widget` module exports `PerspectiveWidget`, the JupyterLab
80
+ widget for interactive visualization in a notebook cell.
81
+ - The `perspective.handlers` modules exports web frameworks handlers that
82
+ interface with a `perspective-client` in JavaScript.
83
+ - `perspective.handlers.tornado.PerspectiveTornadoHandler` for
84
+ [Tornado](https://www.tornadoweb.org/)
85
+ - `perspective.handlers.starlette.PerspectiveStarletteHandler` for
86
+ [Starlette](https://www.starlette.io/) and
87
+ [FastAPI](https://fastapi.tiangolo.com)
88
+ - `perspective.handlers.aiohttp.PerspectiveAIOHTTPHandler` for
89
+ [AIOHTTP](https://docs.aiohttp.org),
90
+
91
+ This user's guide provides an overview of the most common ways to use
92
+ Perspective in Python: the `Table` API, the JupyterLab widget, and the Tornado
93
+ handler.
94
+
95
+ [More Examples](https://github.com/perspective-dev/perspective/tree/master/examples) are
96
+ available on GitHub.
97
+
98
+ ## Installation
99
+
100
+ `perspective-python` contains full bindings to the Perspective API, a JupyterLab
101
+ widget, and a WebSocket handlers for several webserver libraries that allow you
102
+ to host Perspective using server-side Python.
103
+
104
+ `perspective-python` can be installed from [PyPI](https://pypi.org) via `pip`:
105
+
106
+ ```bash
107
+ pip install perspective-python
108
+ ```
109
+
110
+ ## Quick Start
111
+
112
+ A `Table` can be created from a dataset or a schema, the specifics of which are
113
+ [discussed](#loading-data-with-table) in the JavaScript section of the user's
114
+ guide. In Python, however, Perspective supports additional data types that are
115
+ commonly used when processing data:
116
+
117
+ - `pandas.DataFrame`
118
+ - `polars.DataFrame`
119
+ - `bytes` (encoding an Apache Arrow)
120
+ - `objects` (either extracting a repr or via reference)
121
+ - `str` (encoding as a CSV)
122
+
123
+ A `Table` is created in a similar fashion to its JavaScript equivalent:
124
+
125
+ ```python
126
+ from datetime import date, datetime
127
+ import numpy as np
128
+ import pandas as pd
129
+ import perspective
130
+
131
+ data = pd.DataFrame({
132
+ "int": np.arange(100),
133
+ "float": [i * 1.5 for i in range(100)],
134
+ "bool": [True for i in range(100)],
135
+ "date": [date.today() for i in range(100)],
136
+ "datetime": [datetime.now() for i in range(100)],
137
+ "string": [str(i) for i in range(100)]
138
+ })
139
+
140
+ table = perspective.table(data, index="float")
141
+ ```
142
+
143
+ Likewise, a `View` can be created via the `view()` method:
144
+
145
+ ```python
146
+ view = table.view(group_by=["float"], filter=[["bool", "==", True]])
147
+ column_data = view.to_columns()
148
+ row_data = view.to_json()
149
+ ```
150
+
151
+ #### Pandas and Polars Support
152
+
153
+ Perspective's `Table` can be constructed from `pandas.DataFrame` and
154
+ `polars.DataFrame` objects. Internally, this just uses
155
+ [`pyarrow::from_pandas`](https://arrow.apache.org/docs/python/pandas.html),
156
+ which dictates behavior of this feature including type support.
157
+
158
+ If the dataframe does not have an index set, an integer-typed column named
159
+ `"index"` is created. If you want to preserve the indexing behavior of the
160
+ dataframe passed into Perspective, simply create the `Table` with
161
+ `index="index"` as a keyword argument. This tells Perspective to once again
162
+ treat the index as a primary key:
163
+
164
+ ```python
165
+ data.set_index("datetime")
166
+ table = perspective.table(data, index="index")
167
+ ```
168
+
169
+ #### Time Zone Handling
170
+
171
+ When parsing `"datetime"` strings, times are assumed _local time_ unless an
172
+ explicit timezone offset is parsed. All `"datetime"` columns (regardless of
173
+ input time zone) are _output_ to the user as `datetime.datetime` objects in
174
+ _local time_ according to the Python runtime.
175
+
176
+ This behavior is consistent with Perspective's behavior in JavaScript. For more
177
+ details, see this in-depth
178
+ [explanation](https://github.com/perspective-dev/perspective/pull/867) of
179
+ `perspective-python` semantics around time zone handling.
180
+
181
+ #### Callbacks and Events
182
+
183
+ `perspective.Table` allows for `on_update` and `on_delete` callbacks to be
184
+ set—simply call `on_update` or `on_delete` with a reference to a function or a
185
+ lambda without any parameters:
186
+
187
+ ```python
188
+ def update_callback():
189
+ print("Updated!")
190
+
191
+ # set the update callback
192
+ on_update_id = view.on_update(update_callback)
193
+
194
+
195
+ def delete_callback():
196
+ print("Deleted!")
197
+
198
+ # set the delete callback
199
+ on_delete_id = view.on_delete(delete_callback)
200
+
201
+ # set a lambda as a callback
202
+ view.on_delete(lambda: print("Deleted x2!"))
203
+ ```
204
+
205
+ If the callback is a named reference to a function, it can be removed with
206
+ `remove_update` or `remove_delete`:
207
+
208
+ ```python
209
+ view.remove_update(on_update_id)
210
+ view.remove_delete(on_delete_id)
211
+ ```
212
+
213
+ Callbacks defined with a lambda function cannot be removed, as lambda functions
214
+ have no identifier.
215
+
216
+ ### Hosting `Table` and `View` instances
217
+
218
+ `Server` "hosts" all `perspective.Table` and `perspective.View` instances
219
+ created by its connected `Client`s. Hosted tables/views can have their methods
220
+ called from other sources than the Python server, i.e. by a `perspective-viewer`
221
+ running in a JavaScript client over the network, interfacing with
222
+ `perspective-python` through the websocket API.
223
+
224
+ The server has full control of all hosted `Table` and `View` instances, and can
225
+ call any public API method on hosted instances. This makes it extremely easy to
226
+ stream data to a hosted `Table` using `.update()`:
227
+
228
+ ```python
229
+ server = perspective.Server()
230
+ client = server.new_local_client()
231
+ table = client.table(data, name="data_source")
232
+
233
+ for i in range(10):
234
+ # updates continue to propagate automatically
235
+ table.update(new_data)
236
+ ```
237
+
238
+ The `name` provided is important, as it enables Perspective in JavaScript to
239
+ look up a `Table` and get a handle to it over the network. Otherwise, `name`
240
+ will be assigned randomlu and the `Client` must look this up with
241
+ `CLient.get_hosted_table_names()`
242
+
243
+ ### Client/Server Replicated Mode
244
+
245
+ Using Tornado and
246
+ [`PerspectiveTornadoHandler`](python.md#perspectivetornadohandler), as well as
247
+ `Perspective`'s JavaScript library, we can set up "distributed" Perspective
248
+ instances that allows multiple browser `perspective-viewer` clients to read from
249
+ a common `perspective-python` server, as in the
250
+ [Tornado Example Project](https://github.com/perspective-dev/perspective/tree/master/examples/python-tornado).
251
+
252
+ This architecture works by maintaining two `Tables`—one on the server, and one
253
+ on the client that mirrors the server's `Table` automatically using `on_update`.
254
+ All updates to the table on the server are automatically applied to each client,
255
+ which makes this architecture a natural fit for streaming dashboards and other
256
+ distributed use-cases. In conjunction with [multithreading](#multi-threading),
257
+ distributed Perspective offers consistently high performance over large numbers
258
+ of clients and large datasets.
259
+
260
+ _*server.py*_
261
+
262
+ ```python
263
+ from perspective import Server
264
+ from perspective.hadnlers.tornado import PerspectiveTornadoHandler
265
+
266
+ # Create an instance of Server, and host a Table
267
+ SERVER = Server()
268
+ CLIENT = SERVER.new_local_client()
269
+
270
+ # The Table is exposed at `localhost:8888/websocket` with the name `data_source`
271
+ client.table(data, name = "data_source")
272
+
273
+ app = tornado.web.Application([
274
+ # create a websocket endpoint that the client JavaScript can access
275
+ (r"/websocket", PerspectiveTornadoHandler, {"perspective_server": SERVER})
276
+ ])
277
+
278
+ # Start the Tornado server
279
+ app.listen(8888)
280
+ loop = tornado.ioloop.IOLoop.current()
281
+ loop.start()
282
+ ```
283
+
284
+ Instead of calling `load(server_table)`, create a `View` using `server_table`
285
+ and pass that into `viewer.load()`. This will automatically register an
286
+ `on_update` callback that synchronizes state between the server and the client.
287
+
288
+ _*index.html*_
289
+
290
+ ```html
291
+ <perspective-viewer id="viewer" editable></perspective-viewer>
292
+
293
+ <script type="module">
294
+ // Create a client that expects a Perspective server
295
+ // to accept connections at the specified URL.
296
+ const websocket = await perspective.websocket(
297
+ "ws://localhost:8888/websocket"
298
+ );
299
+
300
+ // Get a handle to the Table on the server
301
+ const server_table = await websocket.open_table("data_source_one");
302
+
303
+ // Create a new view
304
+ const server_view = await table.view();
305
+
306
+ // Create a Table on the client using `perspective.worker()`
307
+ const worker = await perspective.worker();
308
+ const client_table = await worker.table(view);
309
+
310
+ // Load the client table in the `<perspective-viewer>`.
311
+ document.getElementById("viewer").load(client_table);
312
+ </script>
313
+ ```
314
+
315
+ For a more complex example that offers distributed editing of the server
316
+ dataset, see
317
+ [client_server_editing.html](https://github.com/perspective-dev/perspective/blob/master/examples/python-tornado/client_server_editing.html).
318
+
319
+ We also provide examples for Starlette/FastAPI and AIOHTTP:
320
+
321
+ - [Starlette Example Project](https://github.com/perspective-dev/perspective/tree/master/examples/python-starlette).
322
+ - [AIOHTTP Example Project](https://github.com/perspective-dev/perspective/tree/master/examples/python-aiohttp).
323
+
324
+ ### Server-only Mode
325
+
326
+ The server setup is identical to [Distributed Mode](#distributed-mode) above,
327
+ but instead of creating a view, the client calls `load(server_table)`: In
328
+ Python, use `Server` and `PerspectiveTornadoHandler` to create a websocket
329
+ server that exposes a `Table`. In this example, `table` is a proxy for the
330
+ `Table` we created on the server. All API methods are available on _proxies_,
331
+ the.g.us calling `view()`, `schema()`, `update()` on `table` will pass those
332
+ operations to the Python `Table`, execute the commands, and return the result
333
+ back to Javascript.
334
+
335
+ ```html
336
+ <perspective-viewer id="viewer" editable></perspective-viewer>
337
+ ```
338
+
339
+ ```javascript
340
+ const websocket = perspective.websocket("ws://localhost:8888/websocket");
341
+ const table = websocket.open_table("data_source");
342
+ document.getElementById("viewer").load(table);
343
+ ```
344
+
345
+ """
346
+
347
+
348
+ import functools
349
+
350
+ from .perspective import (
351
+ Client,
352
+ PerspectiveError,
353
+ ProxySession,
354
+ Server,
355
+ AsyncServer,
356
+ AsyncClient,
357
+ VirtualServer,
358
+ VirtualDataSlice,
359
+ GenericSQLVirtualServerModel,
360
+ # NOTE: these are classes without constructors,
361
+ # so we import them just for type hinting
362
+ Table, # noqa: F401
363
+ View, # noqa: F401
364
+ num_cpus,
365
+ set_num_cpus,
366
+ )
367
+
368
+
369
+ GLOBAL_SERVER = Server()
370
+ GLOBAL_CLIENT = GLOBAL_SERVER.new_local_client()
371
+
372
+
373
+ @functools.wraps(Client.table)
374
+ def table(*args, **kwargs):
375
+ return GLOBAL_CLIENT.table(*args, **kwargs)
376
+
377
+
378
+ @functools.wraps(Client.open_table)
379
+ def open_table(*args, **kwargs):
380
+ return GLOBAL_CLIENT.table(*args, **kwargs)
381
+
382
+
383
+ @functools.wraps(Client.get_hosted_table_names)
384
+ def get_hosted_table_names(*args, **kwargs):
385
+ return GLOBAL_CLIENT.get_hosted_table_names(*args, **kwargs)
386
+
387
+
388
+ @functools.wraps(Client.join)
389
+ def join(*args, **kwargs):
390
+ return GLOBAL_CLIENT.join(*args, **kwargs)
391
+
392
+
393
+ @functools.wraps(Client.system_info)
394
+ def system_info(*args, **kwargs):
395
+ return GLOBAL_CLIENT.system_info(*args, **kwargs)
396
+
397
+
398
+ def _jupyter_labextension_paths():
399
+ """
400
+ Read by `jupyter labextension develop`
401
+ @private
402
+ """
403
+ return [{"src": "labextension", "dest": "@perspective-dev/jupyterlab"}]
@@ -0,0 +1,5 @@
1
+ {
2
+ "load_extensions": {
3
+ "@perspective-dev/jupyterlab/extension": true
4
+ }
5
+ }
@@ -0,0 +1,11 @@
1
+ # ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
2
+ # ┃ ██████ ██████ ██████ █ █ █ █ █ █▄ ▀███ █ ┃
3
+ # ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█ ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄ ▀█ █ ▀▀▀▀▀ ┃
4
+ # ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄ █ ▄▄▄▄▄ ┃
5
+ # ┃ █ ██████ █ ▀█▄ █ ██████ █ ███▌▐███ ███████▄ █ ┃
6
+ # ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫
7
+ # ┃ Copyright (c) 2017, the Perspective Authors. ┃
8
+ # ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃
9
+ # ┃ This file is part of the Perspective library, distributed under the terms ┃
10
+ # ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃
11
+ # ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
@@ -0,0 +1,69 @@
1
+ # ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
2
+ # ┃ ██████ ██████ ██████ █ █ █ █ █ █▄ ▀███ █ ┃
3
+ # ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█ ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄ ▀█ █ ▀▀▀▀▀ ┃
4
+ # ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄ █ ▄▄▄▄▄ ┃
5
+ # ┃ █ ██████ █ ▀█▄ █ ██████ █ ███▌▐███ ███████▄ █ ┃
6
+ # ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫
7
+ # ┃ Copyright (c) 2017, the Perspective Authors. ┃
8
+ # ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃
9
+ # ┃ This file is part of the Perspective library, distributed under the terms ┃
10
+ # ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃
11
+ # ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
12
+
13
+ from aiohttp import web, WSMsgType
14
+ import perspective
15
+ import asyncio
16
+
17
+
18
+ class PerspectiveAIOHTTPHandler(object):
19
+ """`PerspectiveAIOHTTPHandler` is a drop-in implementation of Perspective.
20
+
21
+ Use it inside AIOHTTP routing to create a server-side Perspective that is
22
+ ready to receive websocket messages from the front-end `perspective-viewer`.
23
+
24
+ The Perspective client and server will automatically keep the Websocket
25
+ alive without timing out.
26
+
27
+ # Security
28
+
29
+ `PerspectiveAIOHTTPHandler` is a reference integration with no
30
+ authentication, authorization, origin enforcement, or rate limiting,
31
+ and is not safe to expose to untrusted networks — see
32
+ [`SECURITY.md`](https://github.com/perspective-dev/perspective/blob/master/SECURITY.md)
33
+ for the full threat model.
34
+
35
+ # Examples
36
+
37
+ >>> server = Server()
38
+ >>> async def websocket_handler(request):
39
+ ... handler = PerspectiveAIOHTTPHandler(perspective_server=server, request=request)
40
+ ... await handler.run()
41
+
42
+ >>> app = web.Application()
43
+ >>> app.router.add_get("/websocket", websocket_handler)
44
+ """
45
+
46
+ def __init__(self, **kwargs):
47
+ self.server = kwargs.pop("perspective_server", perspective.GLOBAL_SERVER)
48
+ self._request = kwargs.pop("request")
49
+ self._executor = kwargs.pop("executor", None)
50
+ self._loop = kwargs.pop("loop", asyncio.get_event_loop())
51
+ super().__init__(**kwargs)
52
+
53
+ async def run(self) -> web.WebSocketResponse:
54
+ def inner(msg):
55
+ self._loop.create_task(self._ws.send_bytes(msg))
56
+
57
+ self.session = self.server.new_session(inner)
58
+ try:
59
+ self._ws = web.WebSocketResponse()
60
+ await self._ws.prepare(self._request)
61
+ async for msg in self._ws:
62
+ if msg.type == WSMsgType.BINARY:
63
+ if self._executor is not None:
64
+ self._executor.submit(self.session.handle_request, msg.data)
65
+ else:
66
+ self.session.handle_request(msg.data)
67
+ finally:
68
+ self.session.close()
69
+ return self._ws
@@ -0,0 +1,63 @@
1
+ # ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
2
+ # ┃ ██████ ██████ ██████ █ █ █ █ █ █▄ ▀███ █ ┃
3
+ # ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█ ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄ ▀█ █ ▀▀▀▀▀ ┃
4
+ # ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄ █ ▄▄▄▄▄ ┃
5
+ # ┃ █ ██████ █ ▀█▄ █ ██████ █ ███▌▐███ ███████▄ █ ┃
6
+ # ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫
7
+ # ┃ Copyright (c) 2017, the Perspective Authors. ┃
8
+ # ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃
9
+ # ┃ This file is part of the Perspective library, distributed under the terms ┃
10
+ # ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃
11
+ # ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
12
+
13
+ import asyncio
14
+ import perspective
15
+
16
+
17
+ class PerspectiveStarletteHandler(object):
18
+ """`PerspectiveStarletteHandler` is a drop-in implementation of Perspective.
19
+
20
+ # Security
21
+
22
+ `PerspectiveStarletteHandler` is a reference integration with no
23
+ authentication, authorization, origin enforcement, or rate limiting,
24
+ and is not safe to expose to untrusted networks — see
25
+ [`SECURITY.md`](https://github.com/perspective-dev/perspective/blob/master/SECURITY.md)
26
+ for the full threat model.
27
+
28
+ # Examples
29
+
30
+ >>> server = Server()
31
+ >>> client = server.client()
32
+ >>> client.table(pd.read_csv("superstore.csv"), name="data_source_one")
33
+ >>> app = FastAPI()
34
+ >>> async def endpoint(websocket: Websocket):
35
+ ... handler = PerspectiveStarletteHandler(server, websocket)
36
+ ... await handler.run()
37
+ ... app.add_api_websocket_route('/websocket', endpoint)
38
+ """
39
+
40
+ def __init__(self, **kwargs):
41
+ self._server = kwargs.pop("perspective_server", perspective.GLOBAL_SERVER)
42
+ self._websocket = kwargs.pop("websocket")
43
+ self._executor = kwargs.pop("executor", None)
44
+ self._loop = kwargs.pop("loop", asyncio.get_event_loop())
45
+ super().__init__(**kwargs)
46
+
47
+ async def run(self) -> None:
48
+ def inner(msg):
49
+ self._loop.create_task(self._websocket.send_bytes(msg))
50
+
51
+ self.session = self._server.new_session(inner)
52
+
53
+ try:
54
+ await self._websocket.accept()
55
+ while True:
56
+ message = await self._websocket.receive()
57
+ self._websocket._raise_on_disconnect(message)
58
+ if self._executor is not None:
59
+ self._executor.submit(self.session.handle_request, message["bytes"])
60
+ else:
61
+ self.session.handle_request(message["bytes"])
62
+ finally:
63
+ self.session.close()