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