### Install Solara Development Dependencies Source: https://solara.dev/documentation/advanced/development/setup Installs the necessary development dependencies for Solara from a requirements file. This is a prerequisite for contributing to the project. ```bash git clone git@github.com:widgetti/solara.git cd solara pip install -r requirements-dev.txt ``` -------------------------------- ### Create and Push a New Git Branch for Fixes Source: https://solara.dev/documentation/advanced/development/setup Demonstrates the process of creating a new Git branch, staging changes, committing them with a descriptive message, and pushing the branch to the remote repository to open a pull request. ```bash git checkout -b fix_some_thing git add -p git commit -m "fix: some thing" git push ``` -------------------------------- ### Install Solara Server Source: https://solara.dev/documentation/advanced/understanding/solara-server Instructions for installing the Solara server package. It includes installing the core package with Starlette support and optionally all Solara packages. ```bash $ pip install "solara-server[starlette]" $ # pip install solara # to get all solara packages ``` -------------------------------- ### Example: Displaying a Context Menu with Solara Source: https://solara.dev/documentation/components/lab/menu Demonstrates how to use the Solara ContextMenu component to display a menu when an image is interacted with. The menu contains a list of buttons. This example requires the 'solara' library to be installed. ```python import solara @solara.component def Page(): image_url = "/static/public/beach.jpeg" image = solara.Image(image=image_url) with solara.lab.ContextMenu(activator=image): with solara.Column(gap="0px"): [solara.Button(f"Click me {i}!", text=True) for i in range(5)] ``` -------------------------------- ### Install Pre-commit Hooks for Code Quality Source: https://solara.dev/documentation/advanced/development/setup Installs pre-commit hooks to ensure code quality by running linters and formatters before each commit. This helps maintain code consistency and catch potential issues early. ```bash pre-commit install ``` -------------------------------- ### Install Playwright for Integration Tests Source: https://solara.dev/documentation/advanced/development/setup Installs Playwright, a tool for end-to-end web testing. This is required for running integration tests that simulate real browser interactions. ```bash playwright install ``` -------------------------------- ### Interactive Sine Wave Example (Python) Source: https://solara.dev/documentation/api/hooks/use_exception This example demonstrates how to create an interactive sine wave visualization using Solara. It allows users to adjust parameters and see the wave update in real-time. No external dependencies are explicitly mentioned for this basic example. ```python from solara import * import numpy as np x = np.linspace(0, 2 * np.pi, 100) def sine_wave(amplitude, frequency, phase): return amplitude * np.sin(frequency * x + phase) @solara.component def SineWaveApp(): amplitude = solara.use_state(1.0) frequency = solara.use_state(1.0) phase = solara.use_state(0.0) return solara.Column( solara.Slider(label="Amplitude", value=amplitude[0], min=0.1, max=5.0, on_value=amplitude[1]), solara.Slider(label="Frequency", value=frequency[0], min=0.1, max=5.0, on_value=frequency[1]), solara.Slider(label="Phase", value=phase[0], min=0.0, max=2 * np.pi, on_value=phase[1]), solara.Plotly(figure={ 'data': [ { 'x': x, 'y': sine_wave(amplitude[0], frequency[0], phase[0]), 'type': 'line' } ], 'layout': {'title': 'Interactive Sine Wave'} }) ) __all__ = ['SineWaveApp'] ``` -------------------------------- ### Install Solara with Assets Source: https://solara.dev/documentation/getting_started/installing This command installs Solara along with its necessary assets (CSS, JavaScript, fonts), which are typically fetched from a CDN. This is useful for air-gapped or firewalled environments. ```bash pip install "solara[assets]" ``` -------------------------------- ### Run Solara Integration Tests Source: https://solara.dev/documentation/advanced/development/setup Runs the integration tests for Solara using Playwright. These tests interact with a live browser to ensure the application functions correctly in a realistic environment. ```bash py.test tests/integration --headed ``` -------------------------------- ### Install Solara using pip Source: https://solara.dev/documentation/getting_started/introduction This command installs the Solara package using pip. Ensure you have Python and pip installed. ```bash $ pip install solara ``` -------------------------------- ### Run Solara Unit Tests Source: https://solara.dev/documentation/advanced/development/setup Executes the unit tests for Solara. This is a quick way to verify code changes and is useful during development and test-driven development. ```bash py.test tests/unit ``` -------------------------------- ### Install Solara App Dependencies Source: https://solara.dev/documentation/getting_started Installs the necessary Python packages ('qtpy' and 'PySide6' or 'PyQt6') required to run Solara applications as standalone Qt-based apps. This is an experimental feature. ```bash $ pip install qtpy PySide6 ``` -------------------------------- ### Install Solara from Local Wheels Source: https://solara.dev/documentation/getting_started/installing This command installs Solara by providing the path to the directory containing the pre-built wheels. This is the final step for installing Solara in an air-gapped environment after transferring the tarball and extracting it. ```bash pip install solara-air-gapped/*.whl ``` -------------------------------- ### Install Solara with OAuth Support Source: https://solara.dev/documentation/advanced/enterprise/oauth This command installs Solara along with the necessary components for OAuth authentication and authorization. Ensure you have Solara Enterprise installed. ```bash pip install solara solara-enterprise[auth] ``` -------------------------------- ### Routing Example with generate_routes_directory (Python) Source: https://solara.dev/documentation/api/hooks/use_exception This example demonstrates using `generate_routes_directory` to automatically create application routes based on the file structure of a specified directory. This simplifies navigation setup for multi-page applications. ```python from solara import * from solara.routing import generate_routes_directory # Assume your page components are in a directory named 'pages' # Example structure: # pages/ # __init__.py # home.py # users/ # __init__.py # index.py # [id].py # Generate routes by scanning the 'pages' directory # The function will create routes based on file and folder names. # For example, pages/home.py -> /home, pages/users/[id].py -> /users/:id solara_routes = generate_routes_directory('pages') # Wrap routes with the router App = solara.App(routes=solara_routes) __all__ = ['App'] ``` -------------------------------- ### Solara Example: Interactive Markdown Style Source: https://solara.dev/documentation/getting_started/tutorials/dash A Solara application that replicates the Dash example. It uses `solara.reactive` to manage state and directly wires it to the Select and Markdown components. State transitions occur on the server. ```python import solara color = solara.reactive("red") @solara.component def Page(): solara.Select(label="Color", values=["red", "green", "blue", "orange"], value=color) solara.Markdown("## Hello World", style={"color": color.value}) ``` -------------------------------- ### Install solara-enterprise Package Source: https://solara.dev/documentation/advanced/reference/search Provides the command to install the 'solara-enterprise' package, which is a requirement for using advanced features like the Search component in Solara. ```bash pip install solara-enterprise ``` -------------------------------- ### Using ipyvuetify with Solara Components Source: https://solara.dev/documentation/advanced/understanding/ipyvuetify Demonstrates how to integrate ipyvuetify components within a Solara application. It shows how to use the `reacton-ipyvuetify` wrapper to create type-safe components and handle user interactions like button clicks. This example requires `solara` and `reacton.ipyvuetify` to be installed. ```python import solara # rv is the reacton-ipyvuetify wrapper for Reacton/Solara import reacton.ipyvuetify as rv @solara.component def Page(): clicks, set_clicks = solara.use_state(0) def my_click_handler(*ignore_args): # trigger a new render with a new value for clicks set_clicks(clicks+1) button = rv.Btn(children=[f"Clicked {clicks} times"]) rv.use_event(button, 'click', my_click_handler) return button ``` -------------------------------- ### Basic InputTime Example Source: https://solara.dev/documentation/components/lab/input_time A basic example demonstrating the usage of the Solara InputTime component. It initializes a reactive time variable and displays the selected time. ```python import solara import solara.lab import datetime as dt @solara.component def Page(): time = solara.use_reactive(dt.time(12, 0)) solara.lab.InputTime(time, allowed_minutes=[0, 15, 30, 45]) solara.Text(str(time.value)) ``` -------------------------------- ### Solara Authentication Example Source: https://solara.dev/documentation/components/enterprise/avatar An example demonstrating how to use Solara's authentication features, including displaying user information, login/logout buttons, and conditionally rendering content based on login status. ```python import solara from solara_enterprise import auth @solara.component def Page(): if not auth.user.value: solara.Info("Login to see your avatar") solara.Button("Login", icon_name="mdi-login", href=auth.get_login_url()) else: auth.Avatar() # this shows the user's picture solara.Button("Logout", icon_name="mdi-logout", href=auth.get_logout_url()) ``` -------------------------------- ### Build Solara Wheels for Air-gapped Installation Source: https://solara.dev/documentation/getting_started/installing This command builds all necessary wheels for Solara and its assets into a specified directory, intended for use in air-gapped environments. This is the first step in a manual offline installation process. ```bash pip wheel --wheel-dir solara-air-gapped "solara[assets]" ``` -------------------------------- ### Install Bleeding Edge Solara from Git Source: https://solara.dev/documentation/getting_started/installing This command installs the latest unreleased version of Solara directly from its GitHub repository. This is useful for testing new features or contributing to development. ```bash pip install "solara @ git+https://github.com/widgetti/solara" ``` -------------------------------- ### Login OAuth Example (Python) Source: https://solara.dev/documentation/api/hooks/use_exception This example demonstrates how to implement OAuth login functionality within a Solara application. It likely involves configuring authentication providers and handling the OAuth flow. Specific OAuth providers or libraries are not detailed. ```python from solara import * # Placeholder for OAuth configuration and logic # In a real application, this would involve libraries like 'requests-oauthlib' or similar @solara.component def LoginOAuth(): is_authenticated = solara.use_state(False) def handle_login(): # Simulate OAuth login process print("Initiating OAuth login...") # In a real app, redirect to OAuth provider or handle callback is_authenticated[1](True) # Set to True upon successful login def handle_logout(): print("Logging out...") is_authenticated[1](False) if is_authenticated[0]: return solara.Column( solara.Markdown("Welcome! You are logged in."), solara.Button("Logout", on_click=handle_logout) ) else: return solara.Column( solara.Markdown("Please log in to continue."), solara.Button("Login with OAuth", on_click=handle_login) ) __all__ = ['LoginOAuth'] ``` -------------------------------- ### Install Solara and Dependencies Source: https://solara.dev/documentation/getting_started/tutorials/jupyter-dashboard-part1 Installs the Solara framework along with necessary libraries like pandas, matplotlib, and folium. This can be done via pip in a shell environment or within a Jupyter notebook using %pip. ```bash $ pip install pandas matplotlib folium solara ``` ```python %pip install pandas matplotlib folium solara ``` -------------------------------- ### Routing Example with generate_routes (Python) Source: https://solara.dev/documentation/api/hooks/use_exception This example shows how to set up routing in a Solara application using the `generate_routes` function. This function likely scans a directory structure to automatically create routes for different pages or components. ```python from solara import * from solara.routing import generate_routes # Assume you have components defined in separate files, e.g., pages/home.py, pages/about.py # Example structure: # pages/ # __init__.py # home.py # about.py # For demonstration, let's define simple components inline: @solara.component def HomePage(): return solara.Markdown("# Welcome to the Home Page!") @solara.component def AboutPage(): return solara.Markdown("# About Us Page") # Create a dictionary of routes (replace with actual file scanning if needed) routes_data = { "/": HomePage, "/about": AboutPage } # Generate Solara routes # In a real scenario, generate_routes would scan a directory # For this example, we manually create routes. You might use generate_routes_directory('pages') solara_routes = [ Route(path, component) for path, component in routes_data.items() ] # Wrap routes with the router App = solara.App(routes=solara_routes) __all__ = ['App'] ``` -------------------------------- ### Authorization Example (Python) Source: https://solara.dev/documentation/examples/fullscreen/authorization Demonstrates how to implement authorization within a Solara application. This example shows a basic boolean check, implying a mechanism to control access to certain features or pages based on user roles or permissions. ```python True is not a component or element, but **This website runs onSolara** ``` -------------------------------- ### SQL Code Display Example (Python) Source: https://solara.dev/documentation/api/hooks/use_exception This example demonstrates how to display SQL code within a Solara application using the `SqlCode` component. It's useful for showcasing SQL queries or scripts. The component likely provides syntax highlighting. ```python from solara import * SQL_QUERY = """ SELECT customer_id, first_name, last_name, email FROM customers WHERE country = 'USA' ORDER BY last_name, first_name;""" @solara.component def SqlCodeDisplay(): return solara.Column( solara.Markdown("## SQL Query Example"), solara.SqlCode(SQL_QUERY) ) __all__ = ['SqlCodeDisplay'] ``` -------------------------------- ### Install Solara Enterprise with SSG and Playwright Source: https://solara.dev/documentation/advanced/reference/static-site-generation This command installs the Solara Enterprise package with Static Site Generation (SSG) support and the necessary Playwright dependencies. Playwright is required for the SSG feature to pre-render pages. ```bash $ pip solara-enterprise[ssg] $ playwright install ``` -------------------------------- ### Live Update Example (Python) Source: https://solara.dev/documentation/api/hooks/use_exception This example illustrates how to implement live updates in a Solara application. It likely uses a mechanism to periodically fetch or update data and refresh the UI. The specific update mechanism (e.g., polling, websockets) is not detailed. ```python from solara import * import datetime @solara.component def LiveUpdateApp(): current_time = solara.use_state(datetime.datetime.now()) def update_time(): current_time[1](datetime.datetime.now()) # Update time every second solara.use_interval(update_time, 1000) return solara.Column( solara.Markdown("# Live Time Update"), solara.Markdown(f"Current server time: {current_time[0].strftime('%Y-%m-%d %H:%M:%S')}") ) __all__ = ['LiveUpdateApp'] ``` -------------------------------- ### Markdown Editor Example (Python) Source: https://solara.dev/documentation/api/hooks/use_exception This example implements a Markdown editor using Solara's `MarkdownEditor` component. It allows users to input Markdown text, which is then rendered as HTML. It utilizes Solara's state management for the input text. ```python from solara import * @solara.component def MarkdownEditorApp(): markdown_text = solara.use_state("# Enter Markdown here") return solara.Column( solara.Markdown("## Markdown Editor"), solara.MarkdownEditor(value=markdown_text[0], on_value=markdown_text[1], show_preview=True), solara.Markdown("### Preview:"), solara.Markdown(markdown_text[0]) ) __all__ = ['MarkdownEditorApp'] ``` -------------------------------- ### Run ipywidget app with Solara Source: https://solara.dev/documentation/getting_started/tutorials/ipywidgets This snippet demonstrates how to define an ipywidget application and run it using the Solara server. It highlights how the script is executed at startup and for each page request, and how to specify the widget to render. ```python import ipywidgets as widgets clicks = 0 print("I get run at startup, and for every page request") def on_click(button): global clicks clicks += 1 button.description = f"Clicked {clicks} times" button = widgets.Button(description="Clicked 0 times") button.on_click(on_click) ``` -------------------------------- ### Run Solara Server with Auto-Restart Source: https://solara.dev/documentation/advanced/development/setup Starts the Solara server with the auto-restart flag enabled. This feature automatically restarts the server when source code changes, improving development workflow. ```bash solara run myscript.py -a ``` -------------------------------- ### Deploy Solara App to Cloud Source: https://solara.dev/documentation/getting_started/deploying/cloud-hosted Demonstrates the command-line interface for deploying a Solara application to a cloud-hosted environment. This process typically involves a single command and provides a live URL for the deployed app. ```bash solara deploy ... Your app is live on awesomeapp-mystartup-gh.solara.run ``` -------------------------------- ### Streamlit Example: Basic Slider and Markdown Source: https://solara.dev/documentation/getting_started/tutorials/streamlit This Streamlit code snippet illustrates a basic function 'square' that uses `st.slider` to get user input and `st.markdown` to display the result. It shows how to create multiple instances of this function, but highlights a potential issue when trying to rename the input variable, which might lead to errors in more complex scenarios. ```python import streamlit as st def square(name): with st.sidebar: x = st.slider(name) x_squared = x**2 st.markdown(f"{name}: {x} squared = {x_squared}") square("x") square("y") ``` -------------------------------- ### Configure Git Remotes for Contribution Source: https://solara.dev/documentation/advanced/development/setup Sets up Git remotes for contributing to the Solara repository. It renames the default 'origin' to 'upstream' and adds the user's fork as the new 'origin'. ```bash git remote rename origin upstream git remote add origin https://github.com/yourusername/solara.git ``` -------------------------------- ### Start Jupyter Notebook Server Source: https://solara.dev/documentation/getting_started Command to launch a classic Jupyter Notebook server. This is a prerequisite for running notebook-based code. It's a standard command-line utility. ```bash $ jupyter notebook ``` -------------------------------- ### Solara Quickstart: Basic Reactive App Source: https://solara.dev/documentation/getting_started This Python snippet demonstrates a basic Solara application. It uses reactive variables for text input and a slider, displaying feedback messages based on the word count relative to the word limit. Components re-execute when reactive variables change. This code can be run as a standalone script or within a Jupyter notebook. ```python import solara # Declare reactive variables at the top level. Components using these variables # will be re-executed when their values change. sentence = solara.reactive("Solara makes our team more productive.") word_limit = solara.reactive(10) @solara.component def Page(): # Calculate word_count within the component to ensure re-execution when reactive variables change. word_count = len(sentence.value.split()) solara.SliderInt("Word limit", value=word_limit, min=2, max=20) solara.InputText(label="Your sentence", value=sentence, continuous_update=True) # Display messages based on the current word count and word limit. if word_count >= int(word_limit.value): solara.Error(f"With {word_count} words, you passed the word limit of {word_limit.value}.") elif word_count >= int(0.8 * word_limit.value): solara.Warning(f"With {word_count} words, you are close to the word limit of {word_limit.value}.") else: solara.Success("Great short writing!") # The following line is required only when running the code in a Jupyter notebook: Page() ``` -------------------------------- ### Basic Solara Component for Production Source: https://solara.dev/documentation/getting_started/deploying/self-hosted A simple Solara component demonstrating reactive state management and a button that increments a counter. This is a minimal example of a `sol.py` file that can be run with `solara run`. ```python import solara clicks = solara.reactive(0) @solara.component def Page(): color = "green" if clicks.value >= 5: color = "red" def increment(): clicks.value += 1 print("clicks", clicks) # noqa solara.Button(label=f"Clicked: {clicks}", on_click=increment, color=color) ``` -------------------------------- ### Countdown Timer using use_thread Source: https://solara.dev/documentation/examples/utilities/countdown_timer This snippet demonstrates how to create a countdown timer using the `use_thread` hook in Solara. It includes UI elements for starting the timer and displaying the remaining time, showcasing conditional rendering based on the timer's state. No external dependencies are required beyond Solara itself. ```python import solara import asyncio @solara.component def countdown_timer(): seconds = 5 time_left = solara.use_state(seconds) is_running = solara.use_state(False) async def countdown(): is_running.set(True) while time_left.value > 0: await asyncio.sleep(1) time_left.set(time_left.value - 1) is_running.set(False) def start_timer(): if not is_running.value: time_left.set(seconds) solara.run_task(countdown()) return solara.ui( solara.div( solara.h2("Countdown Timer"), solara.p(f"Time left: {time_left.value} seconds"), solara.Button("Start", on_click=start_timer, disabled=is_running.value), solara.div( ("Timer finished!" if not is_running.value and time_left.value == 0 else "") ) ) ) # Example usage: # countdown_timer() ``` -------------------------------- ### Start Jupyter Lab Server Source: https://solara.dev/documentation/getting_started Command to launch the more modern Jupyter Lab interface. This serves a similar purpose to the classic notebook server but with an enhanced user experience. ```bash $ jupyter lab ``` -------------------------------- ### Run Solara Application Source: https://solara.dev/documentation/getting_started/tutorials/ipywidgets Illustrates the command-line instruction to run a Solara application from a Python script. This command starts the Solara development server. ```shell $ solara run sol-ipywidgets.py ``` -------------------------------- ### Scatter Plot using Plotly Example (Python) Source: https://solara.dev/documentation/api/hooks/use_exception This example demonstrates creating a scatter plot using Plotly within Solara. It requires the Plotly library and its integration with Solara. The example would typically involve generating or providing data for the scatter plot. ```python from solara import * import plotly.express as px import pandas as pd # Sample data data = { 'x': [1, 2, 3, 4, 5], 'y': [2, 3, 5, 4, 6], 'size': [10, 15, 20, 25, 30], 'color': ['A', 'B', 'A', 'C', 'B'] } df = pd.DataFrame(data) @solara.component def PlotlyScatterApp(): fig = px.scatter(df, x='x', y='y', size='size', color='color', title='Scatter Plot using Plotly') return solara.Column( solara.Markdown("# Scatter Plot Example"), solara.Plotly(figure=fig) ) __all__ = ['PlotlyScatterApp'] ``` -------------------------------- ### Dockerfile for Solara Application Source: https://solara.dev/documentation/getting_started/deploying/self-hosted A sample Dockerfile snippet for deploying a Solara application. It specifies the base image, includes application code, and sets the command to run the Solara application using the `solara run` command. The `--host=0.0.0.0` option ensures the application listens on all network interfaces, making it accessible from outside the container, and `--production` enables production optimizations. ```dockerfile FROM .... ... CMD ["solara", "run", "sol.py", "--host=0.0.0.0", "--production"] ``` -------------------------------- ### Running Uvicorn with Root Path and HTTPS for Solara Source: https://solara.dev/documentation/getting_started/deploying/self-hosted Demonstrates how to run the uvicorn server for Solara with specific configurations. The first example shows how to set the root path for Solara when it's not deployed at the application's root. The second example illustrates running uvicorn with SSL/TLS enabled for HTTPS, requiring key and certificate files. ```bash $ SOLARA_APP=sol.py uvicorn --workers 1 --root-path /solara -b 0.0.0.0:8765 solara.server.starlette:app ``` ```bash $ SOLARA_APP=sol.py uvicorn --host 0.0.0.0 --port 8765 solara.server.starlette:app --ssl-keyfile=./key.pem --ssl-certfile=./cert.pem ``` -------------------------------- ### Install pytest-ipywidgets and Playwright for Python Source: https://solara.dev/documentation/advanced/howto/testing Installs the `pytest-ipywidgets` plugin with Solara support and downloads the Chromium browser for Playwright. This enables browser-based testing of Solara applications. ```bash pip install "pytest-ipywidgets[solara]" # or "pytest-ipywidgets[all]" if you also want to test with Jupyter Lab, Jupyter Notebook and Voila. playwright install chromium ``` -------------------------------- ### Solara FileDownload Simple Usage Example Source: https://solara.dev/documentation/components/output/file_download Demonstrates the basic usage of the Solara FileDownload component. A file named 'solara-download.txt' is created with the content 'This is the content of the file', triggered by a button with the label 'Download file'. ```python import solara data = "This is the content of the file" @solara.component def Page(): solara.FileDownload(data, filename="solara-download.txt", label="Download file") ``` -------------------------------- ### Install Solara Package Source: https://solara.dev/documentation/advanced/howto/multipage Command to install a Solara application as an editable Python package. This is useful during development to ensure changes are reflected immediately without reinstallation. ```bash $ (cd solara-test-portal; pip install -e .) ``` -------------------------------- ### GridFixed Layout Example (Solara) Source: https://solara.dev/documentation/components/layout/gridfixed Demonstrates the usage of the GridFixed component to lay out children in a fixed grid. This example showcases basic styling and arrangement of elements within the grid. ```python import solara @solara.component def Page(): return solara.GridFixed( solara.Button("green", color="success"), solara.Button("red", color="danger"), solara.Button("orange", color="warning"), solara.Button("brown", color="secondary"), solara.Button("yellow", color="warning"), solara.Button("pink", color="primary") ) ``` -------------------------------- ### Install Solara using Pip Source: https://solara.dev/documentation/getting_started/installing This command installs the Solara package using pip. It assumes a virtual environment is already active. This is the standard method for adding Solara to your Python project. ```bash pip install solara ``` -------------------------------- ### Run Solara App from Command Line Source: https://solara.dev/documentation/getting_started Executes a Solara application script as a standalone app using the command line. This requires the script ('sol.py') to be in the current directory and the necessary Qt dependencies to be installed. ```bash $ solara run sol.py --qt ``` -------------------------------- ### use_router Hook Example (Python) Source: https://solara.dev/documentation/api/hooks/use_exception This example demonstrates the `use_router` hook, which provides access to the application's router instance. This allows programmatic navigation between routes, such as redirecting users after an action. ```python from solara import * from solara.routing import Route @solara.component def PageA(): router = use_router() def navigate_to_page_b(): router.push("/page-b") return solara.Column( solara.Markdown("# Page A"), solara.Button("Go to Page B", on_click=navigate_to_page_b) ) @solara.component def PageB(): router = use_router() def go_back(): router.back() return solara.Column( solara.Markdown("# Page B"), solara.Button("Go Back", on_click=go_back) ) solara_routes = [ Route("/page-a", PageA), Route("/page-b", PageB) ] App = solara.App(routes=solara_routes) __all__ = ['App'] ``` -------------------------------- ### use_route Hook Example (Python) Source: https://solara.dev/documentation/api/hooks/use_exception This example shows how to use the `use_route` hook to access information about the current route within a Solara component. This includes parameters, path, and other routing details. ```python from solara import * from solara.routing import Route @solara.component def UserProfile(): # Get the current route information route = use_route() # Extract user ID from route parameters (assuming a route like /users/:id) user_id = route.params.get('id', 'Unknown') return solara.Column( solara.Markdown(f"# User Profile for ID: {user_id}"), solara.Markdown(f"Current path: {route.path}") ) # Define routes, including one with a parameter solara_routes = [ Route("/users/:id", UserProfile) ] App = solara.App(routes=solara_routes) __all__ = ['App'] ``` -------------------------------- ### Solara Basic Layout with Columns and Sidebar Source: https://solara.dev/documentation/advanced/howto/layout Demonstrates the fundamental Solara layout components. It shows how to create a title, a sidebar with controls, main content, and nested columns with relative and responsive sizing. ```python import solara @solara.component def Page(): with solara.Column(): solara.Title("I'm in the browser tab and the toolbar") with solara.Sidebar(): solara.Markdown("## I am in the sidebar") solara.SliderInt(label="Ideal for placing controls") solara.Info("I'm in the main content area, put your main content here") with solara.Card("Use solara.Columns([1, 2]) to create relatively sized columns"): with solara.Columns([1, 2]): solara.Success("I'm in the first column") solara.Warning("I'm in the second column, I am twice as wide") solara.Info("I am like the first column") with solara.Card("Use solara.Column() to create a full width column"): with solara.Column(): solara.Success("I'm first in this full with column") solara.Warning("I'm second in this full with column") solara.Error("I'm third in this full with column") with solara.Card("Use solara.ColumnsResponsive(6, large=4) to response to screen size"): with solara.ColumnsResponsive(6, large=4): for i in range(6): solara.Info("two per column on small screens, three per column on large screens") ``` -------------------------------- ### Install Solara from Tarball (requirements.txt) Source: https://solara.dev/documentation/getting_started/installing This snippet shows how to specify the bleeding-edge version of Solara in a requirements.txt file, pointing to a master branch tarball from GitHub. This is an alternative method for installing development versions. ```ini solara @ https://github.com/widgetti/solara/package/archive/master.tar.gz ``` -------------------------------- ### use_cross_filter Hook Example (Python) Source: https://solara.dev/documentation/api/hooks/use_exception This example demonstrates the `use_cross_filter` hook, which is used for managing cross-filtering state between different Solara components. It helps in synchronizing selections across multiple interactive elements. ```python from solara import * import pandas as pd # Sample DataFrame data = { 'Category': ['A', 'B', 'A', 'C', 'B', 'A', 'C', 'B', 'A', 'C'], 'Value': [10, 15, 12, 20, 18, 11, 22, 16, 14, 25] } df = pd.DataFrame(data) @solara.component def CrossFilterHookApp(): # Initialize cross-filter state using the hook cross_filter_state = use_cross_filter("my_filter", df) return solara.Column( solara.Markdown("# use_cross_filter Hook Example"), # Component 1: Select widget linked to the cross-filter state solara.Select(label="Select Category", options=df.Category.unique(), value=cross_filter_state.Category), # Component 2: Display filtered data solara.DataFrame(cross_filter_state.df) ) __all__ = ['CrossFilterHookApp'] ``` -------------------------------- ### Serve Solara App with Panel Source: https://solara.dev/documentation/getting_started/deploying/self-hosted Starts the Panel server to serve an application that includes an embedded Solara component. This command is used for development and testing purposes, assuming the Panel application code is saved in 'solara_in_panel.py'. ```bash $ panel serve solara_in_panel.py ``` -------------------------------- ### Solara Basic Component Example Source: https://solara.dev/documentation/getting_started/introduction This Python code defines a simple Solara component with a reactive counter. It demonstrates how to use `solara.reactive` for state management and `solara.Button` for user interaction. This can be run in a Jupyter notebook or as a standalone Solara application. ```python import solara clicks = solara.reactive(0) @solara.component def Page(): def increase_clicks(): clicks.value += 1 solara.Button(label=f"Clicked {clicks} times", on_click=increase_clicks) # in the Jupyter notebook, uncomment the next line: # display(Page()) ``` -------------------------------- ### Solara Route Declaration Example Source: https://solara.dev/documentation/api/routing/use_route/fruit/apple This example demonstrates how to declare routes in a Solara application. Routes are defined as a list of solara.Route objects, specifying paths and child routes for navigation. ```python routes = [ solara.Route(path="/"), solara.Route( path="fruit", component=Fruit, children=[ solara.Route(path="/"), solara.Route(path="kiwi"), solara.Route(path="banana"), solara.Route(path="apple"), ], ), ] ``` -------------------------------- ### Run Solara Server Source: https://solara.dev/documentation/getting_started/introduction This command starts the Solara development server for a given Python file. It's used when not running within a Jupyter notebook. ```bash $ solara run myapp.py Solara server is starting at http://localhost:8765 ``` -------------------------------- ### Create and Activate Virtual Environment (Windows) Source: https://solara.dev/documentation/getting_started/installing This snippet shows how to create a Python virtual environment named 'solara-env' and activate it on Windows systems. This is essential for managing Solara project dependencies. ```batch py -m venv solara-env solara-env\Scripts\activate ``` -------------------------------- ### Install Plotly and Pandas for Data Science Tutorial Source: https://solara.dev/documentation/getting_started/tutorials/data-science Installs necessary Python packages, plotly and pandas, required for the data science tutorial. This is a prerequisite for using data manipulation and visualization libraries within Solara. ```bash $ pip install plotly pandas ``` -------------------------------- ### Create Solara Portal Project Source: https://solara.dev/documentation/advanced/howto/multipage Command to generate a new Solara project structure for a portal application. This command initializes a directory with a standard layout for components, pages, and other application assets. ```bash $ solara create portal solara-test-portal Wrote: /Users/maartenbreddels/github/widgetti/solara/solara-test-portal Install as: $ (cd solara-test-portal; pip install -e .) Run as: $ solara run solara_test_portal.pages ```