├── .github └── workflows │ └── main.yml ├── .gitignore ├── LICENSE ├── README.md ├── setup.py └── streamlit └── callbacks ├── __init__.py ├── base_connection.py ├── callbacks.py ├── inter_session.py ├── redis.py ├── socket.py └── websocket.py /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | # This is a basic workflow to help you get started with Actions 2 | 3 | # Controls when the action will run. Triggers the workflow on push or pull request 4 | # events but only for the master branchon: push: tags: - '*' 5 | on: 6 | push: 7 | tags: -'*' 8 | create: 9 | tags: -'*' 10 | 11 | # A workflow run is made up of one or more jobs that can run sequentially or in parallel 12 | jobs: 13 | # This workflow contains a single job called "build" 14 | build: 15 | # The type of runner that the job will run on 16 | runs-on: ubuntu-latest 17 | strategy: 18 | matrix: 19 | python-version: [3.6] 20 | 21 | 22 | # Steps represent a sequence of tasks that will be executed as part of the job 23 | steps: 24 | # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it 25 | - uses: actions/checkout@v2 26 | 27 | - name: Set up Python ${{ matrix.python-version }} 28 | uses: actions/setup-python@v2 29 | with: 30 | python-version: ${{ matrix.python-version }} 31 | - name: Install dependencies 32 | run: | 33 | python -m pip install --upgrade pip 34 | pip install setuptools 35 | if [ -f requirements.txt ]; then pip install -r requirements.txt; fi 36 | 37 | - name: Build and package python 38 | run: | 39 | python setup.py sdist bdist_wheel 40 | zip -r build-artifacts.zip dist 41 | - name: Create Release 42 | id: create 43 | uses: actions/create-release@v1 44 | env: 45 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 46 | with: 47 | tag_name: ${{ github.ref }} 48 | release_name: Release ${{ github.ref }} 49 | draft: false 50 | prerelease: false 51 | - name: Upload Release Asset 52 | id: upload-release-asset 53 | uses: actions/upload-release-asset@v1 54 | env: 55 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 56 | with: 57 | upload_url: ${{ steps.create.outputs.upload_url }} # This pulls from the CREATE RELEASE step above, referencing it's ID to get its outputs object, which include a `upload_url`. See this blog post for more info: https://jasonet.co/posts/new-features-of-github-actions/#passing-data-to-future-steps 58 | asset_path: ./build-artifacts.zip 59 | asset_name: release.zip 60 | asset_content_type: application/zip% -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # streamlit_callbacks 2 | 3 | The interface delay times are always in seconds. 4 | 5 | Basic usages 6 | --- 7 | 8 | **Callback later:** 9 | 10 | example of rerun: 11 | ``` 12 | from streamlit.callbacks.callbacks import later, rerun 13 | import streamlit as st 14 | from datetime import datetime 15 | 16 | st.write(datetime.now()) 17 | 18 | later(2.0, rerun) # After 2 sec calls a rerun 19 | ``` 20 | 21 | **Periodically:** 22 | ``` 23 | from streamlit.callbacks.callbacks import periodic 24 | import streamlit as st 25 | 26 | st.button('rerun') 27 | em = st.empty() 28 | 29 | sec = -1 30 | def call(): 31 | global sec 32 | sec += 1 33 | em.write(f'~{sec} sec without rerun') 34 | 35 | call() 36 | 37 | periodic(1.0, call) 38 | ``` 39 | 40 | rerun/stop periodic callback 41 | ``` 42 | from streamlit.callbacks.callbacks import periodic 43 | import streamlit as st 44 | 45 | em = st.empty() 46 | 47 | sec = -1 48 | def call(): 49 | global sec 50 | sec += 1 51 | em.write(f'~{sec} sec without rerun') 52 | if sec > 10: 53 | st.experimental_rerun() 54 | # to stop periodic call, simply call st.stop() 55 | 56 | call() 57 | 58 | periodic(1.0, call) 59 | ``` 60 | 61 | 62 | Websocket 63 | --- 64 | 65 | **Websocket client connection (receive/send):** 66 | ``` 67 | import streamlit.callbacks.websocket as ws 68 | import streamlit as st 69 | 70 | ws_conn = 'ws://localhost:10000' 71 | 72 | print_message = st.empty() 73 | print_message.write("websocket message placeholder") 74 | 75 | def msg_handler(msg): 76 | print_message.write(f"Arrived message from ws: {msg}") 77 | ws.send_message(ws_conn, 'Thanks for the message!') 78 | 79 | ws.on_message(ws_conn, msg_handler) 80 | ``` 81 | 82 | **Websocket client buffered message:** 83 | 84 | Sometimes when websocket send messages frequently, it need to handled buffered way, with accepted some delay 85 | 86 | ``` 87 | import streamlit.callbacks.websocket as ws 88 | import streamlit as st 89 | 90 | ws_conn = 'ws://localhost:10000' 91 | 92 | print_message = st.empty() 93 | print_message.write("websocket message placeholder") 94 | 95 | def msg_handler(msgs): 96 | endline = ' \n -> ' 97 | print_message.write(f"Arrived messages from ws:{endline}{endline.join(msgs)}") 98 | ws.send_message(ws_conn, 'Thanks for the messages!') 99 | 100 | ws.on_message_buffered(ws_conn, msg_handler, buffer_time=0.5) 101 | ``` 102 | 103 | Redis 104 | --- 105 | 106 | **Redis sub-pub channels** 107 | 108 | basic, with one channel 109 | ``` 110 | import streamlit.callbacks.redis as redis 111 | import streamlit as st 112 | 113 | print_message = st.empty() 114 | print_message.write("Redis channel message placeholder") 115 | 116 | def msg_handler(channel, message): 117 | print_message.write(f"Arrived message from channel '{channel}': {message}") 118 | 119 | redis.on_message('cat', msg_handler) 120 | ``` 121 | 122 | multiple channel with regex (only '.?' and '.*' supported, and transformed as redis psubscribe '?' and '\*') 123 | ``` 124 | import streamlit.callbacks.redis as redis 125 | import streamlit as st 126 | import re 127 | 128 | print_message = st.empty() 129 | print_message.write("Redis channel message placeholder") 130 | 131 | def msg_handler(channel, message): 132 | print_message.write(f"Arrived message from channel '{channel}': {message}") 133 | 134 | redis.on_message(re.compile('.*'), msg_handler) 135 | ``` 136 | 137 | **Redis pub-sub buffered messages and publish (send):** 138 | 139 | ``` 140 | import streamlit.callbacks.redis as redis 141 | import streamlit as st 142 | import re 143 | 144 | redis_addr = ('localhost', 6379) 145 | 146 | print_message = st.empty() 147 | print_message.write("Redis channel message placeholder") 148 | 149 | def msg_handler(msgs): 150 | endline = ' \n' 151 | to_print = f'Arrived messages from redis:{endline}' 152 | for channel, message in msgs: 153 | to_print += f'"{channel}" -> {message}{endline}' 154 | print_message.write(to_print) 155 | redis.send_message('out_streamlit', 'Thanks for the messages!') 156 | 157 | redis.on_message_buffered(re.compile('in_.*'), msg_handler, buffer_time=0.5) 158 | ``` 159 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import setuptools 2 | 3 | setuptools.setup( 4 | name="streamlit_callbacks", 5 | version="0.0.5", 6 | author="", 7 | author_email="", 8 | description="", 9 | long_description="", 10 | long_description_content_type="text/plain", 11 | url="", 12 | packages=setuptools.find_namespace_packages(include=['streamlit.*']), 13 | include_package_data=True, 14 | setup_requires=['wheel'], 15 | classifiers=[], 16 | python_requires=">=3.6", 17 | install_requires=[ 18 | "streamlit >= 0.76.0", 19 | ], 20 | ) 21 | 22 | -------------------------------------------------------------------------------- /streamlit/callbacks/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018-2021 Streamlit Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | -------------------------------------------------------------------------------- /streamlit/callbacks/base_connection.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from abc import ABC, abstractmethod 3 | from asyncio import Future 4 | from typing import Awaitable, Tuple, Union, List, Optional, Dict, Any, Callable 5 | 6 | from streamlit import StopException 7 | from .callbacks import _get_loop 8 | 9 | 10 | class _BaseConnection(ABC): 11 | def __init__(self, address): 12 | ABC.__init__(self) 13 | self.address = address 14 | self.callbacks = [] 15 | self.callbacks_empty = asyncio.Event(loop=_get_loop()) 16 | self.output_msg = [] 17 | self.output_msg_has_element = asyncio.Event(loop=_get_loop()) 18 | self.task = None 19 | self.alive = False 20 | 21 | @staticmethod 22 | @abstractmethod 23 | def get_reconnect_time_seconds() -> Union[float, int]: 24 | return 1.0 25 | 26 | @abstractmethod 27 | def _get_event(self, connection) -> Awaitable: 28 | raise NotImplementedError('get_event') 29 | 30 | @abstractmethod 31 | def _handle_event(self, connection, event_result): 32 | raise NotImplementedError('handle_event') 33 | 34 | @abstractmethod 35 | def _connect(self) -> Awaitable: 36 | raise NotImplementedError('connect') 37 | 38 | @abstractmethod 39 | def _send_messages(self, connection: Optional, messages: List): 40 | raise NotImplementedError('send messages') 41 | 42 | @abstractmethod 43 | def _call_callback(self, callback_struct, end_connection: bool, args: Optional = None) -> bool: 44 | raise NotImplementedError('call callback') 45 | 46 | @abstractmethod 47 | def _at_disconnect(self): 48 | raise NotImplementedError('disconnect callback') 49 | 50 | @abstractmethod 51 | def _callback_remove(self, connection: Optional, callback_struct): 52 | raise NotImplementedError('callback remove') 53 | 54 | def _call_all_callback(self, connection: Optional, args=None): 55 | index = 0 56 | while index < len(self.callbacks): 57 | if not self._call_callback(self.callbacks[index], connection is None, args): 58 | self._callback_remove(connection, self.callbacks[index]) 59 | del self.callbacks[index] 60 | else: 61 | index += 1 62 | if len(self.callbacks) == 0: 63 | self.callbacks_empty.set() 64 | 65 | async def _async_connect(self): 66 | empty = asyncio.ensure_future(self.callbacks_empty.wait()) 67 | out_msg = asyncio.ensure_future(self.output_msg_has_element.wait()) 68 | while len(self.callbacks) or len(self.output_msg): 69 | connection = None 70 | try: 71 | connection = await self._connect() 72 | self.alive = True 73 | event = asyncio.ensure_future(self._get_event(connection)) 74 | print(f"Connected to '{self.address}' successfully") 75 | while len(self.callbacks) or len(self.output_msg): 76 | done, pend = await asyncio.wait([event, out_msg, empty], return_when=asyncio.FIRST_COMPLETED) 77 | for task in done: 78 | if task is event: 79 | self._handle_event(connection, task.result()) 80 | event = asyncio.ensure_future(self._get_event(connection)) 81 | if task is out_msg: 82 | msgs, self.output_msg = self.output_msg, [] 83 | self._send_messages(connection, msgs) 84 | self.output_msg_has_element.clear() 85 | out_msg = asyncio.ensure_future(self.output_msg_has_element.wait()) 86 | if task is empty: 87 | if len(self.callbacks) > 0: 88 | self.callbacks_empty.clear() 89 | empty = asyncio.ensure_future(self.callbacks_empty.wait()) 90 | self._call_all_callback(connection) 91 | connection.close() 92 | except BaseException as e: 93 | if connection is not None: 94 | connection.close() 95 | if len(self.callbacks) or len(self.output_msg): 96 | print(f"Connection '{self.address}' ends: {e.__class__.__name__} {e}, try to reconnect after " 97 | f"{self.__class__.get_reconnect_time_seconds()} sec") 98 | else: 99 | if len(self.callbacks) or len(self.output_msg): 100 | print(f"Connection '{self.address}' ends peacefully, try to reconnect after " 101 | f"{self.__class__.get_reconnect_time_seconds()} sec") 102 | finally: 103 | self.alive = False 104 | self._call_all_callback(None) 105 | msgs, self.output_msg = self.output_msg, [] 106 | self._send_messages(None, msgs) 107 | self.output_msg_has_element.clear() 108 | 109 | if len(self.callbacks) or len(self.output_msg): 110 | await asyncio.sleep(self.__class__.get_reconnect_time_seconds()) 111 | 112 | print(f"Connection '{self.address}' ended") 113 | self.callbacks_empty.clear() 114 | self.output_msg_has_element.clear() 115 | 116 | if not empty.done(): 117 | empty.cancel() 118 | if not out_msg.done(): 119 | out_msg.cancel() 120 | 121 | self._at_disconnect() 122 | 123 | self.task = None 124 | 125 | def _add_callback(self, args): 126 | if not self._call_callback(args, False): 127 | return 128 | 129 | self.callbacks.append(args) 130 | if self.task is None: 131 | self.task = asyncio.ensure_future(self._async_connect()) 132 | 133 | def _add_message(self, args): 134 | self.output_msg.append(args) 135 | self.output_msg_has_element.set() 136 | if self.task is None: 137 | self.task = asyncio.ensure_future(self._async_connect()) 138 | 139 | def at_end(self): 140 | self.callbacks_empty.set() 141 | 142 | def threadsafe_at_end(self): 143 | _get_loop().call_soon_threadsafe(self.at_end) 144 | 145 | 146 | class _TimeBuffering: 147 | def __init__(self, 148 | callback: Callable[..., None], 149 | buffer_time: Union[float, int], 150 | is_null: Callable[[Tuple[Optional[List[Any]], Optional[Dict[str, Any]]]], bool], 151 | merge: Callable[[List[Tuple[Optional[List[Any]], Optional[Dict[str, Any]]]]], 152 | Tuple[Optional[List[Any]], Optional[Dict[str, Any]]]], 153 | at_exception: Callable[[], None]): 154 | self.callback = callback 155 | self.buffer_time = buffer_time 156 | self.is_null = is_null 157 | self.merge = merge 158 | self.at_exception = at_exception 159 | self.arguments: List[Tuple[Optional[List[Any]], Optional[Dict[str, Any]]]] = [] 160 | self.prev_future: Optional["Future[None]"] = None 161 | 162 | def __call__(self, args=None, kwargs=None, *vargs, **vkwargs): 163 | if self.prev_future is not None and self.prev_future.done(): 164 | self.prev_future.result() 165 | 166 | if self.is_null((args, kwargs)): 167 | self.callback(args=args, kwargs=kwargs, *vargs, **vkwargs) 168 | else: 169 | self.arguments.append((args, kwargs)) 170 | if len(self.arguments) == 1: 171 | prev_future = asyncio.Future() 172 | 173 | async def after(fut, v_args, v_kwargs): 174 | await asyncio.sleep(self.buffer_time) 175 | plist, self.arguments = self.arguments, [] 176 | try: 177 | merged_args, merged_kwargs = self.merge(plist) 178 | self.callback(args=merged_args, kwargs=merged_kwargs, *v_args, **v_kwargs) 179 | fut.set_result(None) 180 | except StopException as e: 181 | self.at_exception() 182 | 183 | _get_loop().create_task(after(prev_future, vargs, vkwargs)) 184 | -------------------------------------------------------------------------------- /streamlit/callbacks/callbacks.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import functools 3 | import threading 4 | import weakref 5 | from _weakref import ReferenceType 6 | from concurrent.futures import Future 7 | from typing import Optional, Callable, Any, Tuple, List, Union, Dict 8 | 9 | from streamlit import StopException, experimental_rerun 10 | from streamlit.report_session import ReportSession, ReportSessionState 11 | from streamlit.report_thread import get_report_ctx, add_report_ctx, ReportContext, REPORT_CONTEXT_ATTR_NAME 12 | from streamlit.script_runner import RerunException 13 | from tornado.ioloop import PeriodicCallback, IOLoop 14 | 15 | _loop: Optional[asyncio.AbstractEventLoop] = None 16 | _loop_lock = threading.Lock() 17 | _thread: Optional[threading.Thread] = None 18 | 19 | 20 | class _RerunAndStopException(StopException, RerunException): 21 | def __init__(self, rerun_data): 22 | StopException.__init__(self) 23 | RerunException.__init__(self, rerun_data=rerun_data) 24 | 25 | 26 | def _run(fut: Future): 27 | global _loop 28 | asyncio.set_event_loop(asyncio.new_event_loop()) 29 | try: 30 | _loop = asyncio.get_event_loop() 31 | loop = IOLoop.current() 32 | fut.set_result(_loop) 33 | except BaseException as e: 34 | fut.set_exception(e) 35 | else: 36 | loop.start() 37 | finally: 38 | _loop = None 39 | 40 | 41 | def _get_loop() -> asyncio.AbstractEventLoop: 42 | global _loop 43 | if _loop is None: 44 | with _loop_lock: 45 | if _loop is None: 46 | global _thread 47 | fut = Future() 48 | _thread = threading.Thread(daemon=True, target=functools.partial(_run, fut=fut), name="callback thread") 49 | _thread.start() 50 | return fut.result() 51 | return _loop 52 | 53 | 54 | def _getattrs(obj: object, *attrs: str, default: Optional[Any] = None): 55 | for attr in attrs: 56 | obj = getattr(obj, attr, None) 57 | return default if obj is None else obj 58 | 59 | 60 | class _SessionState: 61 | @staticmethod 62 | def get_report_session_from_ctx(report_ctx: ReportContext): 63 | return _getattrs(report_ctx, '_enqueue', '__self__') 64 | 65 | @staticmethod 66 | def get_report_thread(rsession: ReportSession): 67 | return _getattrs(rsession, '_scriptrunner', '_script_thread') 68 | 69 | @staticmethod 70 | def set_state(rsession: ReportSession, state: ReportSessionState): 71 | setattr(rsession, '_state', state) 72 | getattr(rsession, '_enqueue_session_state_changed_message')() 73 | 74 | def __init__(self, report_session: ReportSession): 75 | self._session = report_session 76 | self._ctx: ReportContext = _SessionState.get_report_thread(self._session).streamlit_report_ctx 77 | self.callbacks = {} 78 | self.at_end = {} 79 | 80 | def refresh_ctx(self): 81 | ctx: ReportContext = getattr(_SessionState.get_report_thread(self._session), 'streamlit_report_ctx', None) 82 | if ctx is not None: 83 | self._ctx = ctx 84 | 85 | def get_ctx(self): 86 | self.refresh_ctx() 87 | return self._ctx 88 | 89 | def get_session_state(self) -> ReportSessionState: 90 | state: ReportSessionState = getattr(self._session, '_state') 91 | if state == ReportSessionState.SHUTDOWN_REQUESTED: 92 | raise StopException("Report session shutdown") 93 | return state 94 | 95 | def get_session(self) -> ReportSession: 96 | return self._session 97 | 98 | def regist_at_end(self, at_end: Callable[[], None], session: bool = True): 99 | self.at_end = {k: v for k, v in self.at_end.items() if v.alive} 100 | if at_end is None: 101 | return 102 | fun_repr = f"{repr(at_end)} - {session}" 103 | pre_finalize = self.at_end.get(fun_repr) 104 | if pre_finalize is not None: 105 | pre_finalize() 106 | 107 | self.at_end[fun_repr] = weakref.finalize(self._session if session else self._ctx, at_end) 108 | 109 | 110 | def _wrapped(session_state_ref: 'ReferenceType[_SessionState]', 111 | cb_ref: Union[str, List[Tuple[Callable[..., Any], 'ReferenceType[_SessionState]']]], 112 | need_report: bool = False, 113 | delegate_stop: bool = True, 114 | args: Optional[List[Any]] = None, 115 | kwargs: Optional[Dict[Any, Any]] = None): 116 | if args is None: 117 | args = [] 118 | if kwargs is None: 119 | kwargs = {} 120 | 121 | session_state = session_state_ref() 122 | if session_state is None: 123 | if delegate_stop: 124 | raise StopException("No session state") 125 | return 126 | 127 | fun, function_ctx_ref = None, None 128 | if isinstance(cb_ref, str): 129 | fun, function_ctx_ref = session_state.callbacks.get(cb_ref, (None, None)) 130 | elif len(cb_ref): 131 | fun, function_ctx_ref = cb_ref[0] if len(cb_ref) else (None, None) 132 | if fun is None: 133 | raise StopException("Deleted function, probably not delegated stop, or not handled") 134 | function_ctx = function_ctx_ref() 135 | 136 | thread = threading.current_thread() 137 | orig_ctx = getattr(thread, REPORT_CONTEXT_ATTR_NAME, None) 138 | set_other_ctx = False 139 | rsession = session_state.get_session() 140 | rerun = None 141 | try: 142 | if function_ctx is None: 143 | raise StopException("No function context") 144 | 145 | rstate = session_state.get_session_state() 146 | current_ctx = session_state.get_ctx() 147 | if current_ctx != function_ctx: 148 | raise StopException("Other context") 149 | 150 | add_report_ctx(thread=thread, ctx=current_ctx) 151 | set_other_ctx = True 152 | need_report_not_running = False 153 | try: 154 | if need_report: 155 | if rstate == ReportSessionState.REPORT_NOT_RUNNING: 156 | need_report_not_running = True 157 | _SessionState.set_state(rsession, ReportSessionState.REPORT_IS_RUNNING) 158 | fun(*args, **kwargs) 159 | finally: 160 | if need_report_not_running and _SessionState.get_report_thread(rsession) is None: 161 | _SessionState.set_state(rsession, ReportSessionState.REPORT_NOT_RUNNING) 162 | except StopException as e: 163 | if isinstance(e, _RerunAndStopException): 164 | rerun = e.rerun_data 165 | 166 | if isinstance(cb_ref, str): 167 | del session_state.callbacks[cb_ref] 168 | else: 169 | del cb_ref[0] 170 | if delegate_stop: 171 | raise 172 | except RerunException as e: 173 | rerun = e.rerun_data 174 | except BaseException: 175 | import traceback 176 | traceback.print_exc() 177 | raise 178 | finally: 179 | if rerun: 180 | rsession.request_rerun(rerun) 181 | 182 | if set_other_ctx: 183 | if orig_ctx is None: 184 | delattr(thread, REPORT_CONTEXT_ATTR_NAME) 185 | else: 186 | add_report_ctx(thread=thread, ctx=orig_ctx) 187 | 188 | 189 | def _wrapper(callback: Optional[Callable[..., None]], 190 | uniq_id: Optional[str] = None, 191 | need_report: bool = True, 192 | delegate_stop: bool = True, 193 | at_end: Optional[Callable[[], None]] = None, 194 | out_wrapper: Callable[[Callable[..., None]], Callable[..., None]] = lambda i: i): 195 | if callback is None: 196 | return functools.partial(_wrapper, uniq_id=uniq_id, need_report=need_report, delegate_stop=delegate_stop, 197 | at_end=at_end, out_wrapper=out_wrapper) 198 | 199 | report_ctx = get_report_ctx() 200 | report_session: ReportSession = _SessionState.get_report_session_from_ctx(report_ctx) 201 | if report_session is None: 202 | raise StopException("No report session") 203 | 204 | callback_session_state = getattr(report_session, '_callback_session_state', None) 205 | if callback_session_state is None: 206 | callback_session_state = _SessionState(report_session) 207 | setattr(report_session, '_callback_session_state', callback_session_state) 208 | else: 209 | callback_session_state.refresh_ctx() 210 | 211 | if uniq_id is not None: 212 | pre_callback = callback_session_state.callbacks.get(uniq_id) 213 | callback_session_state.callbacks[uniq_id] = (callback, weakref.ref(report_ctx)) 214 | if pre_callback is None: 215 | callback_session_state.regist_at_end(at_end, session=True) 216 | return out_wrapper(functools.partial(_wrapped, 217 | session_state_ref=weakref.ref(callback_session_state), 218 | cb_ref=uniq_id, 219 | need_report=need_report, 220 | delegate_stop=delegate_stop)) 221 | else: 222 | def raise_(*args, **kwargs): 223 | if delegate_stop: 224 | raise StopException("Already running") 225 | 226 | return raise_ 227 | callback_session_state.regist_at_end(at_end, session=False) 228 | return out_wrapper(functools.partial(_wrapped, 229 | session_state_ref=weakref.ref(callback_session_state), 230 | cb_ref=[(callback, weakref.ref(report_ctx))], 231 | need_report=need_report, 232 | delegate_stop=delegate_stop)) 233 | 234 | 235 | def rerun(*args, **kwargs): 236 | """ 237 | Throws a RerunException 238 | :return: None 239 | 240 | Usage: 241 | 242 | ``` 243 | from streamlit.callbacks.callbacks import later, rerun 244 | later(5.0, rerun) 245 | ``` 246 | """ 247 | 248 | raise experimental_rerun() 249 | 250 | 251 | def call(cb: Callable[..., None] = rerun, *args, key: Optional[str] = None, reinvokable: Optional[bool] = None, **kwargs): 252 | """ 253 | Schedule the callback to be called with args arguments at the next iteration of the event loop. 254 | :param cb: callback will be called exactly once. 255 | :param key: An unique string, which tells that this callable is unique through the whole session 256 | :param reinvokable: If this parameter is true, when this call ends, the key is released 257 | :return: None 258 | """ 259 | if key is not None: 260 | key = "call_" + key 261 | 262 | cb = functools.partial(cb, *args, **kwargs) 263 | if reinvokable is True: 264 | if key is None: 265 | raise RuntimeError("Reinvokable can be used only with key") 266 | orig_cb = cb 267 | 268 | def stopped_callback(): 269 | try: 270 | orig_cb() 271 | except RerunException as re: 272 | raise _RerunAndStopException(re.rerun_data) 273 | else: 274 | raise StopException("Reinvoke") 275 | 276 | cb = stopped_callback 277 | 278 | _get_loop().call_soon_threadsafe(_wrapper(cb, key, delegate_stop=False)) 279 | 280 | 281 | def later(delay: Union[int, float], cb: Callable[..., None] = rerun, *args, key: Optional[str] = None, 282 | reinvokable: Optional[bool] = None, **kwargs): 283 | """ 284 | Schedule callback to be called after the given delay number of seconds (can be either an int or a float). 285 | :param delay: seconds 286 | :param cb: callback will be called exactly once. 287 | :param key: An unique string, which tells that this callable is unique through the whole session 288 | :param reinvokable: If this parameter is true, when this call ends, the key is released 289 | :return: None 290 | """ 291 | if key is not None: 292 | key = "later_" + key 293 | 294 | cb = functools.partial(cb, *args, **kwargs) 295 | if reinvokable is True: 296 | if key is None: 297 | raise RuntimeError("Reinvokable can be used only with key") 298 | orig_cb = cb 299 | 300 | def stopped_callback(): 301 | try: 302 | orig_cb() 303 | except RerunException as re: 304 | raise _RerunAndStopException(re.rerun_data) 305 | else: 306 | raise StopException("Reinvoke") 307 | 308 | cb = stopped_callback 309 | 310 | _get_loop().call_soon_threadsafe(functools.partial(_get_loop().call_later, delay, _wrapper(cb, key, 311 | delegate_stop=False))) 312 | 313 | 314 | def at(when: Union[int, float], cb: Callable[[], None] = rerun, 315 | *args, key: Optional[str] = None, reinvokable: Optional[bool] = None, **kwargs): 316 | """ 317 | Schedule callback to be called at the given absolute timestamp when (an int or a float), 318 | using the same time reference as callbacks.time(). 319 | :param when: absolute timestamp with, same time reference as callbacks.time() 320 | :param cb: callback will be called exactly once. 321 | :param key: An unique string, which tells that this callable is unique through the whole session 322 | :param reinvokable: If this parameter is true, when this call ends, the key is released 323 | :return: None 324 | """ 325 | if key is not None: 326 | key = "at_" + key 327 | 328 | cb = functools.partial(cb, *args, **kwargs) 329 | if reinvokable is True: 330 | if key is None: 331 | raise RuntimeError("Reinvokable can be used only with key") 332 | orig_cb = cb 333 | 334 | def stopped_callback(): 335 | try: 336 | orig_cb() 337 | except RerunException as re: 338 | raise _RerunAndStopException(re.rerun_data) 339 | else: 340 | raise StopException("Reinvoke") 341 | 342 | cb = stopped_callback 343 | 344 | _get_loop().call_soon_threadsafe(functools.partial(_get_loop().call_at, when, _wrapper(cb, key, 345 | delegate_stop=False))) 346 | 347 | 348 | def periodic(callback_time: Union[int, float], cb: Callable[..., None] = rerun, *args, key: Optional[str] = None, 349 | delay: Union[int, float] = 0, **kwargs): 350 | """ 351 | Schedules the given callback to be called periodically. 352 | 353 | The callback is called every ``callback_time`` seconds. 354 | 355 | If the callback runs for longer than ``callback_time`` seconds, 356 | subsequent invocations will be skipped to get back on schedule. 357 | 358 | :param callback_time: seconds 359 | :param cb: callback will be called periodically 360 | :param key: An unique string, which tells that this callable is unique through the whole session 361 | :param delay: seconds which tells that first run need to be delayed with this amount of seconds 362 | :return: None 363 | """ 364 | if key is not None: 365 | key = "periodic_" + key 366 | 367 | class PeriodicCallbackHandler: 368 | def __init__(self, callback_time_millis: float): 369 | periodic_cb = PeriodicCallback(self.wrapped(_wrapper(functools.partial(cb, *args, **kwargs), key, 370 | at_end=self.stop)), callback_time_millis) 371 | self._stop = periodic_cb.stop 372 | self.start = periodic_cb.start 373 | 374 | def stop(self): 375 | self._stop() 376 | 377 | def wrapped(self, callback: Callable[[], None]): 378 | def res(): 379 | try: 380 | callback() 381 | except StopException: 382 | self._stop() 383 | 384 | return res 385 | 386 | _get_loop().call_soon_threadsafe(functools.partial(_get_loop().call_later, delay, 387 | PeriodicCallbackHandler(callback_time * 1000).start)) 388 | 389 | 390 | def clear(): 391 | """ 392 | Register this run to the callback thread. This call is important, when it may no other callback 393 | register function call happens this run 394 | :return: None 395 | """ 396 | refresh_ctx = _getattrs(get_report_ctx(), '_enqueue', '__self__', '_callback_session_state', 'refresh_ctx') 397 | if callable(refresh_ctx): 398 | refresh_ctx() 399 | 400 | 401 | def time() -> float: 402 | """ 403 | Return the current time, as a float value, according to the event loop’s internal monotonic clock. 404 | :return: the event loop’s internal monotonic clock current time 405 | """ 406 | return _get_loop().time() 407 | -------------------------------------------------------------------------------- /streamlit/callbacks/inter_session.py: -------------------------------------------------------------------------------- 1 | from typing import Callable 2 | 3 | import streamlit 4 | from .callbacks import _wrapper 5 | from streamlit.report_thread import get_report_ctx 6 | 7 | sessions = {} 8 | 9 | 10 | def _check_sessions(): 11 | for k, v in list(sessions.items()): 12 | try: 13 | v(args=[None, None], need_report=False) 14 | except: 15 | del sessions[k] 16 | 17 | 18 | def on_message(callback: Callable[[str, str], None]): 19 | def cb(session, data): 20 | if session is not None: 21 | callback(session, data) 22 | 23 | sessions[get_report_ctx().session_id] = _wrapper(cb) 24 | 25 | _check_sessions() 26 | 27 | 28 | def is_listening(session_id: str) -> bool: 29 | _check_sessions() 30 | return sessions.get(session_id, None) is not None 31 | 32 | 33 | def send_message(session_id: str, message: str): 34 | try: 35 | sessions[session_id](args=[get_report_ctx().session_id, message]) 36 | except: 37 | streamlit.error(f"Session id {session_id} is not in listening state") 38 | 39 | _check_sessions() 40 | -------------------------------------------------------------------------------- /streamlit/callbacks/redis.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import functools 3 | import operator 4 | import threading 5 | from typing import Tuple, Callable, Union, Optional, List, Awaitable, Pattern 6 | from weakref import WeakValueDictionary 7 | 8 | import aioredis 9 | from aioredis import Redis, RedisError 10 | from streamlit import StopException 11 | from streamlit.script_runner import RerunException 12 | 13 | from .base_connection import _BaseConnection, _TimeBuffering 14 | from .callbacks import _wrapper, _get_loop 15 | 16 | _redis_connections = WeakValueDictionary() 17 | _redis_connections_lock = threading.Lock() 18 | reconnect_time_seconds = 1.0 19 | 20 | 21 | class _RedisConnection(_BaseConnection): 22 | def __init__(self, address: Tuple[str, int]): 23 | super().__init__(address) 24 | self.closed_event_wait = None 25 | self.add_callback_event = asyncio.Future(loop=_get_loop()) 26 | self.add_event_wait = None 27 | 28 | @staticmethod 29 | def get_reconnect_time_seconds() -> Union[float, int]: 30 | return reconnect_time_seconds 31 | 32 | def _get_event(self, connection: Redis) -> Awaitable: 33 | if self.closed_event_wait is None: 34 | self.closed_event_wait = asyncio.ensure_future(connection.wait_closed()) 35 | if self.add_event_wait is None: 36 | self.add_callback_event = asyncio.Future() 37 | self.add_event_wait = asyncio.ensure_future(self.add_callback_event) 38 | if len(self.callbacks): 39 | self.add_callback_event.set_result(self.callbacks[0]) 40 | return asyncio.wait([self.add_event_wait, self.closed_event_wait], return_when=asyncio.FIRST_COMPLETED) 41 | 42 | def _handle_event(self, connection: Redis, event_result): 43 | done, pending = event_result 44 | for task in done: 45 | if task is self.closed_event_wait: 46 | self.closed_event_wait = None 47 | raise StopException("Closed event") 48 | if task is self.add_event_wait: 49 | self.add_callback_event = asyncio.Future() 50 | self.add_event_wait = asyncio.ensure_future(self.add_callback_event) 51 | tup = task.result() 52 | 53 | ix = next((i for i, v in enumerate(self.callbacks) if v is tup), None) 54 | if ix is None: 55 | continue 56 | 57 | asyncio.ensure_future( 58 | asyncio.gather(*(connection.psubscribe(i) if i.is_pattern else connection.subscribe(i) 59 | for i in map(operator.itemgetter(1), self.callbacks[ix:])))) 60 | 61 | def _connect(self) -> Awaitable: 62 | return aioredis.create_redis_pool(self.address) 63 | 64 | def _send_messages(self, connection: Optional[Redis], messages: List): 65 | if connection is None: 66 | for channel, message, callback in messages: 67 | try: 68 | callback(args=[False]) 69 | except StopException or RerunException: 70 | pass 71 | return 72 | 73 | for channel, message, callback in messages: 74 | async def write_data(c, d, cb): 75 | try: 76 | await connection.publish(c, d) 77 | except RedisError: 78 | if cb is not None: 79 | cb(args=[False]) 80 | self.at_end() 81 | else: 82 | if cb is not None: 83 | cb(args=[True]) 84 | 85 | asyncio.ensure_future(write_data(channel, message, callback)) 86 | 87 | def _call_callback(self, callback_struct, end_connection: bool, args: Optional = None) -> bool: 88 | channel, channel_obj, callback, reconnect = callback_struct 89 | if not reconnect and end_connection: 90 | return False 91 | 92 | try: 93 | if args is None: 94 | callback(args=[None, ''], need_report=False) 95 | else: 96 | callback(args=args) 97 | except StopException: 98 | return False 99 | else: 100 | return True 101 | 102 | def _callback_remove(self, connection: Optional[Redis], callback_struct): 103 | callback_struct[1].close() 104 | 105 | def _at_disconnect(self): 106 | self.add_callback_event.cancel() 107 | if self.closed_event_wait is not None and not self.closed_event_wait.done(): 108 | self.closed_event_wait.cancel() 109 | if self.add_event_wait is not None and not self.add_event_wait.done(): 110 | self.add_event_wait.cancel() 111 | self.add_event_wait = None 112 | 113 | def on_message(self, 114 | channel: Union[str, Pattern], 115 | callback: Callable[..., None], 116 | reconnect: bool): 117 | pattern = not isinstance(channel, str) 118 | channel_obj = aioredis.Channel(channel.pattern.replace('.*', '*').replace('.?', '?') if pattern else channel, 119 | is_pattern=pattern) 120 | tup = channel, channel_obj, callback, reconnect 121 | 122 | async def message_handling(): 123 | try: 124 | async for message in channel_obj.iter(decoder=lambda m: m.decode()): 125 | if pattern: 126 | if not self._call_callback(tup, False, [message[0].decode(), message[1]]): 127 | break 128 | else: 129 | if not self._call_callback(tup, False, [channel, message]): 130 | break 131 | finally: 132 | channel_obj.close() 133 | self.at_end() 134 | 135 | asyncio.ensure_future(message_handling()) 136 | 137 | if self.add_event_wait is None: 138 | self.add_callback_event = asyncio.Future() 139 | self.add_event_wait = asyncio.ensure_future(self.add_callback_event) 140 | if not self.add_callback_event.done(): 141 | self.add_callback_event.set_result(tup) 142 | self._add_callback(tup) 143 | 144 | def add_message(self, 145 | channel: str, 146 | message: str, 147 | callback: Optional[Callable[[bool], None]] = None): 148 | self._add_message((channel, message, callback)) 149 | 150 | def get_buffer_wrapper(self, buffer_time): 151 | return functools.partial(_TimeBuffering, 152 | buffer_time=buffer_time, 153 | is_null=lambda kv: kv[0][0] is None, 154 | merge=lambda l: ([list(map(tuple, 155 | map(operator.itemgetter(0), l)))], None), 156 | at_exception=self.at_end) 157 | 158 | 159 | def _get_redis_connection(address: Tuple[str, int]): 160 | _connection = _redis_connections.get(address) 161 | if _connection is None: 162 | with _redis_connections_lock: 163 | _connection = _redis_connections.get(address) 164 | if _connection is None: 165 | _connection = _RedisConnection(address) 166 | _redis_connections[address] = _connection 167 | return _connection 168 | 169 | 170 | def on_message(channel: Union[str, Pattern], 171 | callback: Callable[[str, str], None], 172 | key: Optional[str] = None, 173 | address: Tuple[str, int] = ('localhost', 6379), 174 | reconnect: bool = True): 175 | if key is not None: 176 | key = 'redis.on_message_' + key 177 | 178 | def callback_with_empty(from_channel: Optional[str], message: str): 179 | if from_channel is not None: 180 | callback(from_channel, message) 181 | 182 | _get_loop().call_soon_threadsafe(_get_redis_connection(address).on_message, 183 | channel, 184 | _wrapper(callback_with_empty, key, 185 | at_end=_get_redis_connection(address).threadsafe_at_end), 186 | reconnect) 187 | 188 | 189 | def on_message_buffered(channel: Union[str, Pattern], 190 | callback: Callable[[List[Tuple[str, str]]], None], 191 | buffer_time: Union[float, int], 192 | key: Optional[str] = None, 193 | address: Tuple[str, int] = ('localhost', 6379), 194 | reconnect: bool = True): 195 | if key is not None: 196 | key = 'redis.on_message_buffered_' + key 197 | 198 | def callback_with_empty(from_channel: Optional[List[Tuple[str, str]]], unused_data: Optional[str] = None): 199 | if from_channel is not None: 200 | callback(from_channel) 201 | 202 | redis = _get_redis_connection(address) 203 | 204 | wrapped_fun = _wrapper(callback_with_empty, key, 205 | out_wrapper=redis.get_buffer_wrapper(buffer_time), 206 | at_end=redis.threadsafe_at_end) 207 | 208 | _get_loop().call_soon_threadsafe(redis.on_message, channel, wrapped_fun, reconnect) 209 | 210 | 211 | def send_message(channel: str, 212 | message: str, 213 | callback: Optional[Callable[[bool], None]] = None, 214 | address: Tuple[str, int] = ('localhost', 6379)): 215 | if callback is None: 216 | def cb(*args): 217 | pass 218 | callback = cb 219 | _get_loop().call_soon_threadsafe(_get_redis_connection(address).add_message, channel, message, 220 | _wrapper(callback, delegate_stop=False)) 221 | -------------------------------------------------------------------------------- /streamlit/callbacks/socket.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import functools 3 | import operator 4 | import threading 5 | from asyncio import StreamReader, StreamWriter 6 | from typing import Callable, Union, Optional, List, Awaitable, Tuple 7 | from weakref import WeakValueDictionary 8 | 9 | from streamlit import StopException 10 | from .base_connection import _BaseConnection, _TimeBuffering 11 | from .callbacks import _get_loop, _wrapper 12 | from streamlit.script_runner import RerunException 13 | 14 | _s_connections = WeakValueDictionary() 15 | _s_connections_lock = threading.Lock() 16 | reconnect_time_seconds = 1.0 17 | 18 | 19 | class _SocketConnection(_BaseConnection): 20 | @staticmethod 21 | def get_reconnect_time_seconds(): 22 | return reconnect_time_seconds 23 | 24 | def _get_event(self, connection: Tuple[StreamReader, StreamWriter]) -> Awaitable: 25 | return connection[0].read(1024) 26 | 27 | def _handle_event(self, connection: Tuple[StreamReader, StreamWriter], data): 28 | if data is None: 29 | raise ConnectionError("Socket sent EOF") 30 | 31 | self._call_all_callback(connection, data) 32 | 33 | def _connect(self) -> Awaitable: 34 | return asyncio.open_connection(*self.address) 35 | 36 | def _send_messages(self, connection: Optional[Tuple[StreamReader, StreamWriter]], messages): 37 | if connection is None: 38 | for data, callback in messages: 39 | try: 40 | callback(args=[False]) 41 | except StopException or RerunException: 42 | pass 43 | return 44 | 45 | for data, callback in messages: 46 | async def write_data(d, cb): 47 | try: 48 | if not connection[0].at_eof(): 49 | connection[1].write(d if isinstance(d, bytes) else d.encode()) 50 | await connection[1].drain() 51 | if cb is not None: 52 | cb(args=[True]) 53 | else: 54 | self.add_message(d, cb) 55 | except IOError: 56 | if cb is not None: 57 | cb(args=[False]) 58 | self.at_end() 59 | 60 | asyncio.ensure_future(write_data(data, callback)) 61 | 62 | def _call_callback(self, callback_struct: Tuple, end_connection: bool, args=None) -> bool: 63 | callback, reconnect = callback_struct 64 | if not reconnect and end_connection: 65 | return False 66 | 67 | try: 68 | if args is None: 69 | callback(args=[args], need_report=False) 70 | else: 71 | callback(args=[args]) 72 | except StopException: 73 | return False 74 | else: 75 | return True 76 | 77 | def _at_disconnect(self): 78 | pass 79 | 80 | def _callback_remove(self, connection: Optional, callback_struct): 81 | pass 82 | 83 | def add_callback(self, callback: Callable[..., None], reconnect: bool): 84 | self._add_callback((callback, reconnect)) 85 | 86 | def add_message(self, data: Union[str, bytes], callback: Optional[Callable[[bool], None]] = None): 87 | self._add_message((data, callback)) 88 | 89 | def get_buffer_wrapper(self, buffer_time): 90 | return functools.partial(_TimeBuffering, 91 | buffer_time=buffer_time, 92 | is_null=lambda kv: kv[0][0] is None, 93 | merge=lambda l: ([list(map(operator.itemgetter(0), 94 | map(operator.itemgetter(0), l)))], None), 95 | at_exception=self.at_end) 96 | 97 | 98 | def _get_s_connection(address: Tuple[str, int]): 99 | _connection = _s_connections.get(address) 100 | if _connection is None: 101 | with _s_connections_lock: 102 | _connection = _s_connections.get(address) 103 | if _connection is None: 104 | _connection = _SocketConnection(address) 105 | _s_connections[address] = _connection 106 | return _connection 107 | 108 | 109 | def is_alive(address: Tuple[str, int]) -> bool: 110 | return _get_s_connection(address).alive 111 | 112 | 113 | def on_message(address: Tuple[str, int], 114 | callback: Callable[[bytes], None], 115 | key: Optional[str] = None, 116 | reconnect: bool = True): 117 | if key is not None: 118 | key = 's.on_message_' + key 119 | 120 | def callback_with_empty(data: Union[None, bytes]): 121 | if data is not None: 122 | callback(data) 123 | 124 | _get_loop().call_soon_threadsafe(_get_s_connection(address).add_callback, 125 | _wrapper(callback_with_empty, key, 126 | at_end=_get_s_connection(address).threadsafe_at_end), 127 | reconnect) 128 | 129 | 130 | def on_message_buffered(address: Tuple[str, int], 131 | callback: Callable[[List[bytes]], None], 132 | buffer_time: Union[float, int], key: Optional[str] = None, 133 | reconnect: bool = True): 134 | if key is not None: 135 | key = 's.on_message_buffered_' + key 136 | 137 | def callback_with_empty(data: Optional[List[bytes]]): 138 | if data is not None: 139 | callback(data) 140 | 141 | sconn = _get_s_connection(address) 142 | 143 | wrapped_fun = _wrapper(callback_with_empty, key, 144 | out_wrapper=sconn.get_buffer_wrapper(buffer_time), 145 | at_end=sconn.threadsafe_at_end) 146 | 147 | _get_loop().call_soon_threadsafe(_get_s_connection(address).add_callback, wrapped_fun, reconnect) 148 | 149 | 150 | def send_message(address: Tuple[str, int], message: Union[str, bytes], callback: Optional[Callable[[bool], None]] = None): 151 | if callback is None: 152 | def cb(*args): 153 | pass 154 | callback = cb 155 | _get_loop().call_soon_threadsafe(_get_s_connection(address).add_message, message, _wrapper(callback, 156 | delegate_stop=False)) 157 | -------------------------------------------------------------------------------- /streamlit/callbacks/websocket.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import functools 3 | import operator 4 | import threading 5 | from typing import Callable, Union, Optional, List, Awaitable, Tuple 6 | from weakref import WeakValueDictionary 7 | 8 | from streamlit import StopException 9 | from .base_connection import _BaseConnection, _TimeBuffering 10 | from .callbacks import _get_loop, _wrapper 11 | from streamlit.script_runner import RerunException 12 | from tornado.websocket import websocket_connect, WebSocketClosedError, WebSocketClientConnection 13 | 14 | _ws_connections = WeakValueDictionary() 15 | _ws_connections_lock = threading.Lock() 16 | reconnect_time_seconds = 1.0 17 | 18 | 19 | class _WebsocketConnection(_BaseConnection): 20 | @staticmethod 21 | def get_reconnect_time_seconds(): 22 | return reconnect_time_seconds 23 | 24 | def _get_event(self, connection) -> Awaitable: 25 | return connection.read_message() 26 | 27 | def _handle_event(self, connection, data): 28 | if data is None: 29 | raise ConnectionError("Websocket sent EOF") 30 | 31 | self._call_all_callback(connection, data) 32 | 33 | def _connect(self) -> Awaitable: 34 | return websocket_connect(url=self.address) 35 | 36 | def _send_messages(self, connection: WebSocketClientConnection, messages): 37 | if connection is None: 38 | for data, callback in messages: 39 | try: 40 | callback(args=[False]) 41 | except StopException or RerunException: 42 | pass 43 | return 44 | 45 | for data, callback in messages: 46 | async def write_data(d, cb): 47 | try: 48 | if connection.protocol is not None: 49 | await connection.write_message(d, isinstance(d, bytes)) 50 | if cb is not None: 51 | cb(args=[True]) 52 | else: 53 | self.add_message(d, cb) 54 | except WebSocketClosedError: 55 | if cb is not None: 56 | cb(args=[False]) 57 | self.at_end() 58 | 59 | asyncio.ensure_future(write_data(data, callback)) 60 | 61 | def _call_callback(self, callback_struct: Tuple, end_connection: bool, args=None) -> bool: 62 | callback, reconnect = callback_struct 63 | if not reconnect and end_connection: 64 | return False 65 | 66 | try: 67 | if args is None: 68 | callback(args=[args], need_report=False) 69 | else: 70 | callback(args=[args]) 71 | except StopException: 72 | return False 73 | else: 74 | return True 75 | 76 | def _at_disconnect(self): 77 | pass 78 | 79 | def _callback_remove(self, connection: Optional, callback_struct): 80 | pass 81 | 82 | def add_callback(self, callback: Callable[..., None], reconnect: bool): 83 | self._add_callback((callback, reconnect)) 84 | 85 | def add_message(self, data: Union[str, bytes], callback: Optional[Callable[[bool], None]] = None): 86 | self._add_message((data, callback)) 87 | 88 | def get_buffer_wrapper(self, buffer_time): 89 | return functools.partial(_TimeBuffering, 90 | buffer_time=buffer_time, 91 | is_null=lambda kv: kv[0][0] is None, 92 | merge=lambda l: ([list(map(operator.itemgetter(0), 93 | map(operator.itemgetter(0), l)))], None), 94 | at_exception=self.at_end) 95 | 96 | 97 | def _get_ws_connection(url: str): 98 | _connection = _ws_connections.get(url) 99 | if _connection is None: 100 | with _ws_connections_lock: 101 | _connection = _ws_connections.get(url) 102 | if _connection is None: 103 | _connection = _WebsocketConnection(url) 104 | _ws_connections[url] = _connection 105 | return _connection 106 | 107 | 108 | def is_alive(url: str) -> bool: 109 | return _get_ws_connection(url).alive 110 | 111 | 112 | def on_message(url: str, callback: Callable[[Union[str, bytes]], None], key: Optional[str] = None, 113 | reconnect: bool = True): 114 | if key is not None: 115 | key = 'ws.on_message_' + key 116 | 117 | def callback_with_empty(data: Union[None, str, bytes]): 118 | if data is not None: 119 | callback(data) 120 | 121 | _get_loop().call_soon_threadsafe(_get_ws_connection(url).add_callback, 122 | _wrapper(callback_with_empty, key, 123 | at_end=_get_ws_connection(url).threadsafe_at_end), 124 | reconnect) 125 | 126 | 127 | def on_message_buffered(url: str, callback: Callable[[List[Union[str, bytes]]], None], 128 | buffer_time: Union[float, int], key: Optional[str] = None, 129 | reconnect: bool = True): 130 | if key is not None: 131 | key = 'ws.on_message_buffered_' + key 132 | 133 | def callback_with_empty(data: Optional[List[Union[str, bytes]]]): 134 | if data is not None: 135 | callback(data) 136 | 137 | wsconn = _get_ws_connection(url) 138 | 139 | wrapped_fun = _wrapper(callback_with_empty, key, 140 | out_wrapper=wsconn.get_buffer_wrapper(buffer_time), 141 | at_end=wsconn.threadsafe_at_end) 142 | 143 | _get_loop().call_soon_threadsafe(_get_ws_connection(url).add_callback, wrapped_fun, reconnect) 144 | 145 | 146 | def send_message(url: str, message: Union[str, bytes], callback: Optional[Callable[[bool], None]] = None): 147 | if callback is None: 148 | def cb(*args): 149 | pass 150 | callback = cb 151 | _get_loop().call_soon_threadsafe(_get_ws_connection(url).add_message, message, _wrapper(callback, 152 | delegate_stop=False)) 153 | --------------------------------------------------------------------------------