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