Repository: ideonate/streamlit-launchpad
Branch: master
Commit: e31eef0bf84d
Files: 19
Total size: 33.6 KB
Directory structure:
gitextract_q6iqrcs8/
├── .gitignore
├── CONTRIBUTING.md
├── LICENSE
├── MANIFEST.in
├── README.md
├── RELEASE.md
├── examples/
│ ├── csvfiles/
│ │ └── testboxes.csv
│ ├── fileuploader.py
│ ├── intro.py
│ └── plot_example.py
├── launchpad/
│ ├── __init__.py
│ ├── dynamicapplication.py
│ ├── handlers.py
│ ├── main.py
│ └── templates/
│ ├── error.html
│ ├── loading.html
│ └── main.html
├── requirements.txt
└── setup.py
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
.idea
*.iml
__pycache__
build/
dist/
*.egg-info
.vscode
================================================
FILE: CONTRIBUTING.md
================================================
Contributing to Ideonate / ContainDS Projects
=============================================
We welcome contributions to our [open source projects on Github](https://github.com/ideonate).
Issues
------
Feel free to submit issues and enhancement requests via GitHub Issues.
Please also [get in touch](https://cdsdashboards.readthedocs.io/en/stable/chapters/contact.html) with any questions or feedback, or for help in working with the software. These
actions are valuable contributions in their own right.
Contributing
------------
In general, the projects follow the "fork and pull request" Git workflow.
1. **Fork** the repo on GitHub
2. **Clone** the project to your own machine
3. **Commit** changes to your own branch
4. **Push** your work back up to your fork
5. Submit a **Pull request** so that we can review your changes
NB: Make sure you merge the latest from "upstream" before making a pull request!
Copyright and Licensing
-----------------------
Most Ideonate open source projects are licensed under the BSD 3-Clause License, Apache 2.0 license, or MIT license.
Contributions to the Git repos will be assumed to be on the same copyright basis as existing files in that repo.
================================================
FILE: LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: MANIFEST.in
================================================
# js
recursive-include launchpad/templates *.*
# Misc
include requirements.txt
include LICENSE
include README.md
global-exclude *.py[co]
================================================
FILE: README.md
================================================
# Streamlit Launchpad
Web launchpad to browse a folder containing multiple Streamlit applications (py files), with a central launchpad listing available apps so you can run them (if not already running) and view each in its own tab.
This is a very basic alpha version. Windows is now supported. For Windows, torando >= 6.1 is required
## Install and Run
Install using pip.
```
pip install streamlit-launchpad
```
Serves *.py as separate Streamlit applications from the folder supplied on the command line:
```
streamlit-launchpad ./examples
```
Then go to http://localhost:8888/ in your browser:

To run on a different port use:
```
streamlit-launchpad --port 8000 ./examples
```
To provide a title (default is "Streamlit Apps"):
```
streamlit-launchpad --title="My Title" ./examples
```
## Development install
```
git clone https://github.com/ideonate/streamlit-launchpad.git
cd streamlit-launchpad
pip install -e .
streamlit-launchpad ./examples
```
To run directly in python: `python -m launchpad.main ./examples/`
================================================
FILE: RELEASE.md
================================================
- To release a new version of streamlit-launchpad on PyPI:
Update setup.py to the new version
delete dist folder
`python setup.py sdist bdist_wheel`
`twine upload dist/*`
git add and git commit
`git tag -a X.X.X -m 'comment'`
`git push`
`git push --tags`
================================================
FILE: examples/csvfiles/testboxes.csv
================================================
ID,x,y,w,h
1,0,0,10,20
2,129,66,191,103
3,0,0,0,0
4,0,0,0,0
5,50,10,780,130
6,0,0,0,0
================================================
FILE: examples/fileuploader.py
================================================
import streamlit as st
import glob
from os import path
import pandas as pd
st.markdown('# Based on subfolder path')
path_input_data = st.sidebar.text_input("Provide the name to the subfolder in which your csv files are "
"stored.")
st.write("Input path:", path_input_data)
docker_search_path = path.join('.', path_input_data)
st.write("Search path:", docker_search_path)
if path_input_data:
excel_files = glob.glob(docker_search_path + '/**/*.csv', recursive=True)
st.write(excel_files)
st.markdown('# Now try uploading')
uploaded_file = st.file_uploader("Choose a CSV file", type="csv")
if uploaded_file is not None:
st.write('Uploaded file: ', uploaded_file)
data = pd.read_csv(uploaded_file)
st.write(data)
st.write('Streamlit version: ', st.version._get_installed_streamlit_version())
================================================
FILE: examples/intro.py
================================================
import pandas
import numpy
import streamlit as st
st.title("Streamlit intro")
st.write("Examples below were taken from: https://streamlit.io/docs/getting_started.html#get-started")
st.subheader("Here's our first attempt at using data to create a table:")
st.code("""
df = pandas.DataFrame({
'first column': [1, 2, 3, 4],
'second column': [10, 20, 30, 40]
})
""", language='python')
df = pandas.DataFrame({
'first column': [1, 2, 3, 4],
'second column': [10, 20, 30, 40]
})
# here we use 'magic',
# any time that Streamlit sees a variable or a literal value on its own line,
# it automatically writes that to your app using st.write()
df
st.subheader("Draw a line hart:")
st.code("""
chart_data = pandas.DataFrame(
numpy.random.randn(20, 3),
columns=['a', 'b', 'c'])
st.line_chart(chart_data)
""", language='python')
chart_data = pandas.DataFrame(
numpy.random.randn(20, 3),
columns=['a', 'b', 'c'])
st.line_chart(chart_data)
st.subheader("Let’s use Numpy to generate some sample data and plot it on a map of San Francisco:")
st.code("""
map_data = pandas.DataFrame(
numpy.random.randn(1000, 2) / [50, 50] + [37.76, -122.4],
columns=['lat', 'lon'])
st.map(map_data)
""", language='python')
map_data = pandas.DataFrame(
numpy.random.randn(1000, 2) / [50, 50] + [37.76, -122.4],
columns=['lat', 'lon'])
st.map(map_data)
st.title("Add interactivity with widgets")
st.subheader("Use checkboxes to show/hide data")
st.code("""
if st.checkbox('Show dataframe'):
chart_data = pandas.DataFrame(
numpy.random.randn(20, 3),
columns=['a', 'b', 'c'])
st.line_chart(chart_data)
""", language='python')
if st.checkbox('Show dataframe'):
chart_data = pandas.DataFrame(
numpy.random.randn(20, 3),
columns=['a', 'b', 'c'])
st.line_chart(chart_data)
st.subheader("Put widgets in a sidebar")
st.code("""
if st.checkbox('Show in sidebar'):
option = st.sidebar.selectbox(
'Which number do you like best?',
["a", "b","c"])
'You selected:', option
""", language='python')
if st.checkbox('Show in sidebar'):
option = st.sidebar.selectbox(
'Which number do you like best?',
["a", "b","c"])
'You selected:', option
st.subheader("Show progress")
st.code("""
import time
# Add a placeholder
latest_iteration = st.empty()
bar = st.progress(0)
for i in range(100):
# Update the progress bar with each iteration.
latest_iteration.text(f'Iteration {i+1}')
bar.progress(i + 1)
time.sleep(0.1)
'...and now we\'re done!'
""", language='python')
import time
# Add a placeholder
latest_iteration = st.empty()
bar = st.progress(0)
for i in range(100):
# Update the progress bar with each iteration.
latest_iteration.text(f'Iteration {i+1}')
bar.progress(i + 1)
time.sleep(0.1)
'...and now we\'re done!'
================================================
FILE: examples/plot_example.py
================================================
import time
import numpy as np
import streamlit as st
st.code("""
progress_bar = st.sidebar.progress(0)
status_text = st.sidebar.empty()
last_rows = np.random.randn(1, 1)
chart = st.line_chart(last_rows)
for i in range(1, 101):
new_rows = last_rows[-1, :] + np.random.randn(5, 1).cumsum(axis=0)
status_text.text("%i%% Complete" % i)
chart.add_rows(new_rows)
progress_bar.progress(i)
last_rows = new_rows
time.sleep(0.05)
progress_bar.empty()
# Streamlit widgets automatically run the script from top to bottom. Since
# this button is not connected to any other logic, it just causes a plain
# rerun.
st.button("Re-run")
""", language='python')
progress_bar = st.sidebar.progress(0)
status_text = st.sidebar.empty()
last_rows = np.random.randn(1, 1)
chart = st.line_chart(last_rows)
for i in range(1, 101):
new_rows = last_rows[-1, :] + np.random.randn(5, 1).cumsum(axis=0)
status_text.text("%i%% Complete" % i)
chart.add_rows(new_rows)
progress_bar.progress(i)
last_rows = new_rows
time.sleep(0.05)
progress_bar.empty()
# Streamlit widgets automatically run the script from top to bottom. Since
# this button is not connected to any other logic, it just causes a plain
# rerun.
st.button("Re-run")
================================================
FILE: launchpad/__init__.py
================================================
================================================
FILE: launchpad/dynamicapplication.py
================================================
import tornado.web
class DynamicApplication(tornado.web.Application):
def remove_handlers(self, appname):
remove_rules_index = -1
for i, rule in enumerate(self.default_router.rules):
print(rule)
print(rule.matcher)
if isinstance(rule.target, tornado.web.ReversibleRouter):
print(rule.target.named_rules)
if appname+ 'ws' in rule.target.named_rules or appname+ 'http' in rule.target.named_rules:
remove_rules_index = i
if remove_rules_index >= 0:
print("Remove rules {}".format(remove_rules_index))
del self.default_router.rules[remove_rules_index]
================================================
FILE: launchpad/handlers.py
================================================
import tornado
import tornado.web
import tornado.websocket
import tornado.httpclient
import tornado.gen
tornado.httpclient.AsyncHTTPClient.configure(None, defaults={'decompress_response': False})
MAX_RETRIES = 100
class ProxyHandler(tornado.web.RequestHandler):
def initialize(self, proxy_url='/', **kwargs):
super(ProxyHandler, self).initialize(**kwargs)
self.proxy_url = proxy_url
async def post(self, url=None):
return await self.handle_req(url)
async def get(self, url=None):
return await self.handle_req(url)
async def handle_req(self, url=None):
print("INCOMING URL: "+url)
#url = url or self.proxy_url
if url is None:
if self.request.uri.startswith('/'):
url = self.request.uri[1:]
else:
url = self.request.uri
debug = True
if url[:6] == 'static' or url[:7] == 'favicon':
debug = False
url = self.proxy_url+url
if debug:
print("{} : {}".format(self.request.method, url))
incoming_headers = {}
for k,v in self.request.headers.items():
if not k.lower() in ['host', 'pragma', 'upgrade-insecure-requests',
'sec-fetch-user', 'sec-fetch-site', 'sec-fetch-mode', 'accept-encoding']:
# 'accept-encoding', 'accept-language', 'accept', 'cache-control',
incoming_headers[k] = v
body = None
if self.request.method == 'POST':
body = self.request.body
req = tornado.httpclient.HTTPRequest(url, headers=incoming_headers, method=self.request.method, body=body)
client = tornado.httpclient.AsyncHTTPClient()
response = None
retries = 0
while not response and retries < MAX_RETRIES:
response = await client.fetch(req, raise_error=False)
if response.error:
print(" **** response.error")
print(response.error)
if response.code == 599: # Maybe server wasn't yet ready
print(" **** response.error 599 ***")
response = None
retries += 1
await tornado.gen.sleep(0.1)
if not response:
self.set_status(404)
self.finish()
return
if debug:
print(incoming_headers)
print(response)
print(response.headers)
print(response.code)
self.set_status(response.code)
if response.code != 200:
self.finish()
else:
if response.body:
if debug:
print("response body")
for header, v in response.headers.get_all():
if header.lower() == 'content-length':
self.set_header(header, str(max(len(response.body), int(v))))
else:
self.set_header(header, v)
self.write(response.body)
self.finish()
class ProxyWSHandler(tornado.websocket.WebSocketHandler):
def initialize(self, proxy_url='/', **kwargs):
super(ProxyWSHandler, self).initialize(**kwargs)
self.proxy_url = proxy_url
self.ws = None
self.closed = True
async def open(self, url=None):
self.closed = False
#url = url or self.proxy_url
if url is None:
if self.request.uri.startswith('/'):
url = self.request.uri[1:]
else:
url = self.request.uri
url = self.proxy_url+url
def write(msg):
if self.closed or msg is None:
if self.ws:
self.ws.close()
self.ws = None
else:
if self.ws:
self.write_message(msg, binary=isinstance(msg, bytes))
if url[:4] == 'http':
url = 'ws' + url[4:]
print("WEBSOCKET OPENING ON "+url)
self.ws = await tornado.websocket.websocket_connect(url,
on_message_callback=write)
async def on_message(self, message):
if self.ws:
await self.ws.write_message(message, binary=isinstance(message, bytes))
def on_close(self):
if self.ws:
self.ws.close()
self.ws = None
self.closed = True
================================================
FILE: launchpad/main.py
================================================
import tornado.ioloop
import tornado.web
import tornado.template
import os, signal, platform
import tornado.process
import subprocess
import threading
import re
import click
from collections import namedtuple
from .dynamicapplication import DynamicApplication
from .handlers import ProxyWSHandler, ProxyHandler
AppInfo = namedtuple('AppInfo', 'name url')
# py file name to port number
proxymap = {}
port = 8500
template_loader = tornado.template.Loader(os.path.join(os.path.dirname(os.path.realpath(__file__)),"templates"))
scan_folder_path = '../examples'
def popenAndCall(onExit, *popenArgs, **popenKWArgs):
"""
Runs a subprocess.Popen, and then calls the function onExit when the
subprocess completes. This replicates the tornado.process.Suprocess for Windows
This code from:
https://stackoverflow.com/questions/2581817/python-subprocess-callback-when-cmd-exits
Use it exactly the way you'd normally use subprocess.Popen, except include a
callable to execute as the first argument. onExit is a callable object, and
*popenArgs and **popenKWArgs are simply passed up to subprocess.Popen.
"""
def runInThread(onExit, popenArgs, popenKWArgs):
proc = subprocess.Popen(*popenArgs, **popenKWArgs)
proc.wait()
onExit()
return
thread = threading.Thread(target=runInThread,
args=(onExit, popenArgs, popenKWArgs))
thread.start()
return thread # returns immediately after the thread starts
class MainHandler(tornado.web.RequestHandler):
def get(self):
apps = []
for f in os.scandir(scan_folder_path):
if f.name[-3:] == '.py':
apps.append(AppInfo(name=f.name, url="/{}/".format(f.name)))
self.write(template_loader.load('main.html').generate(apps=apps, cwd=scan_folder_path, title=page_title))
self.finish()
class DefaultProxyHandler(tornado.web.RequestHandler):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
print("INIT PROXYHANDLER ***")
async def get(self):
match = re.search(r"^/(.+\.py)/(.*)$", self.request.path)
appname, path = None, None
if match:
appname, path = match[1], match[2]
print(match)
else:
print("NO MATCH: "+self.request.path)
self.set_status(404)
self.finish()
return
print("appname {}, path {}".format(appname, path))
global proxymap
my_port = 0
if not appname in proxymap:
global port
def exit_callback(*args, **kwargs):
print("exit callback {} {}".format(args, kwargs))
self.application.remove_handlers(appname)
proxymap[appname]['stopped'] = True
proc = proxymap[appname]['proc']
if proc:
if proc.stderr:
proxymap[appname]['stderr'] = proc.stderr
if proc.stdout:
proxymap[appname]['stdout'] = proc.stdout
if platform.system() == "Windows": # tornado.process.Subprocess does not work on Windows
proc = popenAndCall(exit_callback, ['streamlit', 'run', os.path.join(scan_folder_path, appname),
'--server.port', str(port),
'--server.headless', 'true',
'--server.runOnSave', 'true',
'--server.enableCORS', 'false',
'--server.enableXsrfProtection', 'false'],
cwd=scan_folder_path)
else: # for Linux use standard tornado.process.Subprocess
proc = tornado.process.Subprocess(['streamlit', 'run', os.path.join(scan_folder_path, appname),
'--server.port', str(port),
'--server.headless', 'true',
'--server.runOnSave', 'true',
'--server.enableCORS', 'false',
'--server.enableXsrfProtection', 'false'],
stdout=tornado.process.Subprocess.STREAM, stderr=tornado.process.Subprocess.STREAM,
cwd=scan_folder_path)
proc.set_exit_callback(exit_callback)
proxymap[appname] = {'proc': proc, 'port': port, 'stopped': False, 'stdout': None, 'stderr': None}
url = 'http://localhost:{}/'.format(port)
self.application.add_handlers(
r".*",
[
(rf"^/{appname}/stream(.*)", ProxyWSHandler, {'proxy_url': url + 'stream'}, appname + 'ws'),
(rf"^/{appname}/(.*)", ProxyHandler, {'proxy_url': url}, appname + 'http')
])
print("Started {}: {}".format(appname, port))
my_port = port
port += 1
else:
# We should only reach this point if remove_handlers was called on the app's underlying handlers,
# so most likely the server has stopped
my_port = proxymap[appname]['port']
print("Already running {}: {}".format(appname, my_port))
async def empty_and_close_stream(stream):
if stream:
lines = await stream.read_until_close()
stream.close()
return lines
return None
stdout = await empty_and_close_stream(proxymap[appname]['stdout'])
stderr = await empty_and_close_stream(proxymap[appname]['stderr'])
del proxymap[appname]
self.write(template_loader.load('error.html').generate(app=AppInfo(name=appname, url="/{}/".format(appname)),
stdout=stdout, stderr=stderr, port=my_port))
self.finish()
return
self.write(template_loader.load('loading.html').generate(app=AppInfo(name=appname, url="/{}/".format(appname)),
port=my_port))
self.finish()
def make_app():
return DynamicApplication([
(r"^/$", MainHandler),
],
debug=True,
default_handler_class=DefaultProxyHandler)
@click.command()
@click.option('--port', default=8888, help='port for the launchpad server')
@click.option('--title', default="Streamlit Apps", help='title for the streamlit web page')
@click.argument('folder')
def run(port, title, folder):
global scan_folder_path, page_title
scan_folder_path = os.path.abspath(folder)
page_title = title
app = make_app()
async def shutdown():
tornado.ioloop.IOLoop.current().stop()
for (appname, appval) in proxymap.items():
if not appval['stopped']:
proc = appval['proc']
if proc:
print('Stopping proc for app {}'.format(appname))
proc.proc.terminate()
def exit_handler(sig, frame):
tornado.ioloop.IOLoop.current().add_callback_from_signal(shutdown)
signal.signal(signal.SIGTERM, exit_handler)
signal.signal(signal.SIGINT, exit_handler)
app.listen(port)
print("Starting streamlit launchpad server of folder {} on port {}".format(scan_folder_path, port))
tornado.ioloop.IOLoop.current().start()
if __name__ == '__main__':
run()
================================================
FILE: launchpad/templates/error.html
================================================
<html>
<head>
<title>Streamlit Launchpad - app status</title>
</head>
<body>
<h2>Streamlit App Status</h2>
<p>Status of <a href="{{ app.url }}" target="_slaunch_{{ escape(app.name) }}">{{ escape(app.name) }}</a> on port {{ port }}.</p>
<p>App appears to have stopped. Removing so you can refresh your browser to try again.</p>
{% if stderr %}
<pre>
{{ escape(stderr) }}
</pre>
{% end %}
{% if stdout %}
<pre>
{{ escape(stdout) }}
</pre>
{% end %}
</body>
</html>
================================================
FILE: launchpad/templates/loading.html
================================================
<html>
<meta http-equiv="refresh" content="1" />
<head>
<title>Streamlit Launchpad - app status</title>
</head>
<body>
<p>Starting app {{ escape(app.name) }} on port {{ port }}.</p>
<p>Will reload automatically in 1 sec. Click <a href="#" onclick="javascript:window.location.reload()">here</a> to reload manually.</p>
</body>
</html>
================================================
FILE: launchpad/templates/main.html
================================================
<html>
<head>
<title>Streamlit Launchpad</title>
</head>
<body>
<h2>{{title}}</h2>
<p>Reading from {{ cwd }}</p>
<ul>
{% for app in sorted(apps) %}
{% block appitem %}
<li><a href="{{ app.url }}" target="_slaunch_{{ escape(app.name) }}">{{ escape(app.name) }}</a></li>
{% end %}
{% end %}
</ul>
</body>
</html>
================================================
FILE: requirements.txt
================================================
streamlit>=0.62.0
tornado>=5.0
Click>=7.0
================================================
FILE: setup.py
================================================
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
# read requirements.txt
with open('requirements.txt', 'r') as f:
content = f.read()
li_req = content.split('\n')
install_requires = [e.strip() for e in li_req if len(e)]
setuptools.setup(
name="streamlit-launchpad",
version="0.0.11",
author="Dan Lester",
author_email="dan@ideonate.com",
description="Web launchpad to browse a folder containing multiple Streamlit applications",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/ideonate/streamlit-launchpad",
packages=setuptools.find_packages(),
install_requires=install_requires,
include_package_data=True,
zip_safe=False,
entry_points={"console_scripts": ["streamlit-launchpad = launchpad.main:run"]},
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
python_requires='>=3.6',
)
gitextract_q6iqrcs8/ ├── .gitignore ├── CONTRIBUTING.md ├── LICENSE ├── MANIFEST.in ├── README.md ├── RELEASE.md ├── examples/ │ ├── csvfiles/ │ │ └── testboxes.csv │ ├── fileuploader.py │ ├── intro.py │ └── plot_example.py ├── launchpad/ │ ├── __init__.py │ ├── dynamicapplication.py │ ├── handlers.py │ ├── main.py │ └── templates/ │ ├── error.html │ ├── loading.html │ └── main.html ├── requirements.txt └── setup.py
SYMBOL INDEX (20 symbols across 3 files)
FILE: launchpad/dynamicapplication.py
class DynamicApplication (line 4) | class DynamicApplication(tornado.web.Application):
method remove_handlers (line 6) | def remove_handlers(self, appname):
FILE: launchpad/handlers.py
class ProxyHandler (line 12) | class ProxyHandler(tornado.web.RequestHandler):
method initialize (line 13) | def initialize(self, proxy_url='/', **kwargs):
method post (line 17) | async def post(self, url=None):
method get (line 20) | async def get(self, url=None):
method handle_req (line 23) | async def handle_req(self, url=None):
class ProxyWSHandler (line 102) | class ProxyWSHandler(tornado.websocket.WebSocketHandler):
method initialize (line 103) | def initialize(self, proxy_url='/', **kwargs):
method open (line 109) | async def open(self, url=None):
method on_message (line 135) | async def on_message(self, message):
method on_close (line 139) | def on_close(self):
FILE: launchpad/main.py
function popenAndCall (line 26) | def popenAndCall(onExit, *popenArgs, **popenKWArgs):
class MainHandler (line 49) | class MainHandler(tornado.web.RequestHandler):
method get (line 50) | def get(self):
class DefaultProxyHandler (line 60) | class DefaultProxyHandler(tornado.web.RequestHandler):
method __init__ (line 62) | def __init__(self, *args, **kwargs):
method get (line 66) | async def get(self):
function make_app (line 165) | def make_app():
function run (line 177) | def run(port, title, folder):
Condensed preview — 19 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (37K chars).
[
{
"path": ".gitignore",
"chars": 56,
"preview": ".idea\n*.iml\n__pycache__\nbuild/\ndist/\n*.egg-info\n.vscode\n"
},
{
"path": "CONTRIBUTING.md",
"chars": 1203,
"preview": "Contributing to Ideonate / ContainDS Projects\n=============================================\n\nWe welcome contributions to"
},
{
"path": "LICENSE",
"chars": 11358,
"preview": " Apache License\n Version 2.0, January 2004\n "
},
{
"path": "MANIFEST.in",
"chars": 139,
"preview": "\n# js\nrecursive-include launchpad/templates *.*\n\n# Misc\ninclude requirements.txt\ninclude LICENSE\ninclude README.md\ngloba"
},
{
"path": "README.md",
"chars": 1086,
"preview": "# Streamlit Launchpad\n\nWeb launchpad to browse a folder containing multiple Streamlit applications (py files), with a ce"
},
{
"path": "RELEASE.md",
"chars": 264,
"preview": "- To release a new version of streamlit-launchpad on PyPI:\n\nUpdate setup.py to the new version\n\ndelete dist folder\n\n`pyt"
},
{
"path": "examples/csvfiles/testboxes.csv",
"chars": 86,
"preview": "ID,x,y,w,h\n1,0,0,10,20\n2,129,66,191,103\n3,0,0,0,0\n4,0,0,0,0\n5,50,10,780,130\n6,0,0,0,0\n"
},
{
"path": "examples/fileuploader.py",
"chars": 870,
"preview": "import streamlit as st\nimport glob\nfrom os import path\nimport pandas as pd\n\nst.markdown('# Based on subfolder path')\n\npa"
},
{
"path": "examples/intro.py",
"chars": 2861,
"preview": "import pandas\nimport numpy\nimport streamlit as st\n\nst.title(\"Streamlit intro\")\nst.write(\"Examples below were taken from:"
},
{
"path": "examples/plot_example.py",
"chars": 1257,
"preview": "import time\nimport numpy as np\nimport streamlit as st\n\n\nst.code(\"\"\"\nprogress_bar = st.sidebar.progress(0)\nstatus_text = "
},
{
"path": "launchpad/__init__.py",
"chars": 0,
"preview": ""
},
{
"path": "launchpad/dynamicapplication.py",
"chars": 695,
"preview": "import tornado.web\n\n\nclass DynamicApplication(tornado.web.Application):\n\n def remove_handlers(self, appname):\n\n "
},
{
"path": "launchpad/handlers.py",
"chars": 4469,
"preview": "import tornado\nimport tornado.web\nimport tornado.websocket\nimport tornado.httpclient\nimport tornado.gen\n\ntornado.httpcli"
},
{
"path": "launchpad/main.py",
"chars": 7769,
"preview": "import tornado.ioloop\nimport tornado.web\nimport tornado.template\nimport os, signal, platform\nimport tornado.process\nimpo"
},
{
"path": "launchpad/templates/error.html",
"chars": 473,
"preview": "<html>\n<head>\n <title>Streamlit Launchpad - app status</title>\n</head>\n<body>\n\n<h2>Streamlit App Status</h2>\n<p>Statu"
},
{
"path": "launchpad/templates/loading.html",
"chars": 342,
"preview": "<html>\n<meta http-equiv=\"refresh\" content=\"1\" />\n\n<head>\n <title>Streamlit Launchpad - app status</title>\n</head>\n<bo"
},
{
"path": "launchpad/templates/main.html",
"chars": 337,
"preview": "<html>\n<head>\n <title>Streamlit Launchpad</title>\n</head>\n<body>\n\n<h2>{{title}}</h2>\n<p>Reading from {{ cwd }}</p>\n\n<"
},
{
"path": "requirements.txt",
"chars": 42,
"preview": "streamlit>=0.62.0\ntornado>=5.0\nClick>=7.0\n"
},
{
"path": "setup.py",
"chars": 1058,
"preview": "import setuptools\n\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\n# read requirements.txt\nwith op"
}
]
About this extraction
This page contains the full source code of the ideonate/streamlit-launchpad GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 19 files (33.6 KB), approximately 7.9k tokens, and a symbol index with 20 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.