### Install JustPy in a Virtual Environment Source: https://github.com/justpy-org/justpy/blob/master/docs/tutorial/getting_started.md These shell commands set up a Python virtual environment named 'jp', activate it, and then install the JustPy library and its dependencies using pip. This ensures a clean and isolated environment for the project. ```shell mkdir jptutorial cd jptutorial python3 -m venv jp source jp/bin/activate pip install justpy ``` -------------------------------- ### Run JustPy Demo Browser (Local) Source: https://github.com/justpy-org/justpy/blob/master/docs/tutorial/getting_started.md This command sequence clones the JustPy repository, navigates into the directory, and starts the demo browser directly from the command line. This method requires Git and a local JustPy installation. ```shell git clone https://github.com/justpy-org/justpy cd justpy scripts/jpdemo ``` -------------------------------- ### Run JustPy Demo Browser (Docker) Source: https://github.com/justpy-org/justpy/blob/master/docs/tutorial/getting_started.md This command initiates the JustPy demo browser within a Docker environment. It's a convenient way to explore JustPy's features without direct system installation. ```shell scripts/rundocker example examples/demo_browser.py ``` -------------------------------- ### Run a JustPy Python Program Source: https://github.com/justpy-org/justpy/blob/master/docs/tutorial/getting_started.md This command executes a Python script that contains JustPy code. After running this, the JustPy web server will start, and the application will be accessible via a web browser. ```shell python3 test.py ``` -------------------------------- ### Running JustPy Examples with Docker Source: https://github.com/justpy-org/justpy/blob/master/README.md This snippet demonstrates how to use the provided Docker script to run JustPy examples and development environments. It includes commands for cloning the repository, running tests, executing specific examples, and starting a development server. ```bash git clone https://github.com/justpy-org/justpy scripts/rundocker -h scripts/rundocker test scripts/rundocker example examples/dogs.py scripts/rundocker dev scripts/rundocker example examples/demo_browser.py ``` -------------------------------- ### Create a Basic JustPy Web Page (Python) Source: https://github.com/justpy-org/justpy/blob/master/docs/tutorial/getting_started.md This Python code defines a simple 'Hello World' web page using JustPy. It imports the library, defines a function to create a web page with a 'Hello' component, and then registers this function with JustPy to run the web server. ```python import justpy as jp def hello_world(): wp = jp.WebPage() jp.Hello(a=wp) return wp jp.justpy(hello_world) ``` -------------------------------- ### Activate Virtual Environment (Windows) Source: https://github.com/justpy-org/justpy/blob/master/docs/tutorial/getting_started.md This is the command to activate the Python virtual environment named 'jp' on a Microsoft Windows system. It differs from the Unix-based 'source' command. ```shell jp\Scripts\activate ``` -------------------------------- ### Install Python and Pip on Linux Source: https://github.com/justpy-org/justpy/blob/master/docs/tutorial/deployment.md Installs Python 3 and pip, the package installer for Python, on a Linux system using apt. This is a prerequisite for running JustPy applications. ```bash apt update apt install python3-pip ``` -------------------------------- ### Minimal Load Transition Example Source: https://github.com/justpy-org/justpy/blob/master/docs/tutorial/transitions.md This Python code illustrates a minimal transition dictionary focused solely on the 'load' state. It defines classes for the initial transition, the starting state (opacity-0), and the ending state (opacity-100) when an element is first rendered. ```python transition_dict = { 'load': 'transition ease-out duration-1000', 'load_start': 'opacity-0 transform scale-0', 'load_end': 'opacity-100 transform scale-100' } ``` -------------------------------- ### Run QAjaxBar Methods (start/stop) with JustPy Source: https://github.com/justpy-org/justpy/blob/master/docs/quasar_tutorial/introduction.md This Python code demonstrates how to run the `start()` and `stop()` methods of a QAjaxBar component using JustPy's `run_method` function. It requires setting `temp=False` when creating the component to generate a necessary ID. The example includes button clicks to trigger these methods. ```python import justpy as jp async def start_bar(self, msg): wp = msg.page await wp.ajax_bar.run_method('start()', msg.websocket) async def stop_bar(self, msg): wp = msg.page await wp.ajax_bar.run_method('stop()', msg.websocket) def bar_example(): wp = jp.QuasarPage() d = jp.Div(classes='q-pa-md', a=wp) # temp=False is important because this generates an id for the element that is required for run_method to work wp.ajax_bar = jp.QAjaxBar(position='bottom', color='accent', size='10px', skip_hijack=True, a=d, temp=False) btn_start = jp.QBtn(color='primary', label='Start Bar', a=d, click=start_bar, style='margin-right: 20px') btn_stop = jp.QBtn(color='primary', label='Stop Bar', a=d, click=stop_bar) return wp jp.justpy(bar_example) ``` -------------------------------- ### JustPy Hello World Example Source: https://github.com/justpy-org/justpy/blob/master/docs/README.md A basic JustPy application that creates a web page displaying 'Hello world!'. It initializes a web server and serves a simple page. This example demonstrates the core functionality of JustPy for creating web interfaces with pure Python. ```python import justpy as jp def hello_world_readme(): wp = jp.WebPage() d = jp.Div(text='Hello world!') wp.add(d) return wp jp.justpy(hello_world_readme) ``` -------------------------------- ### Python JustPy Real-time Clock Source: https://github.com/justpy-org/justpy/blob/master/docs/tutorial/pushing_data.md This Python code uses JustPy to create a web page displaying a real-time clock. It defines asynchronous functions to continuously update the time and send those updates to connected clients. The `startup` parameter ensures the clock begins updating when the server starts. ```python import justpy as jp import time import asyncio wp = jp.WebPage(delete_flag=False) clock_div = jp.Span(text='Loading...', classes='text-5xl m-1 p-1 bg-gray-300 font-mono', a=wp) async def clock_counter(): while True: clock_div.text = time.strftime("%a, %d %b %Y, %H:%M:%S", time.localtime()) jp.run_task(wp.update()) await asyncio.sleep(1) async def clock_init(): jp.run_task(clock_counter()) async def clock_test(): return wp jp.justpy(clock_test, startup=clock_init) ``` -------------------------------- ### Bash Script to Clone JustPy Examples Source: https://github.com/justpy-org/justpy/blob/master/docs/blog/heroku.md A bash script designed to clone the JustPy GitHub repository and synchronize the `examples` directory to the current working directory. It ensures a fresh copy of examples and removes the `.git` directory from the cloned repository to avoid conflicts. ```bash #!/bin/bash # WF 2022-10-19 # get the justpy examples and tutorial files # remember the current directory pwd=$(pwd) # url of justpy repository giturl=https://github.com/justpy-org/justpy # get a temporary directory gitdir=$(mktemp -u) mkdir -p $gitdir # switch to the temporary directory cd $gitdir if [ ! -d justpy ] then echo "cloning to $gitdir" git clone --depth=1 $giturl fi rm -rf justpy/.git rsync -avz justpy/examples $pwd --delete ``` -------------------------------- ### QSplitter Example with JustPy Source: https://github.com/justpy-org/justpy/blob/master/docs/quasar_tutorial/quasar_components.md Demonstrates the QSplitter component for creating resizable panes. It includes nested divs for content and updates a QChip and QAvatar based on the splitter's value changes. ```python import justpy as jp lorem = 'Lorem ipsum dolor sit, amet consectetur adipisicing elit. Quis praesentium cumque magnam odio iure quidem, quod illum numquam possimus obcaefati commodi minima assumenda consectetur culpa fuga nulla ullam. In, libero.' def quasar_splitter_test(): wp = jp.QuasarPage() before = jp.Div(classes='q-pa-md') jp.Div(text='Before', classes='text-h4 q-mb-md', a=before) for i in range(20): jp.Div(text=f'{i}. {lorem}', a=before, classes='q-my-md') after = jp.Div(classes='q-pa-md') jp.Div(text='After', classes='text-h4 q-mb-md', a=after) for i in range(20): jp.Div(text=f'{i}. {lorem}', a=after, classes='q-my-md') s = jp.QSplitter(style='height: 400px', a=wp, classes='q-ma-lg') s.separator_class='bg-orange' s.separator_style='width: 3px' s.before_slot = before s.after_slot = after chip = jp.QChip(a=wp, classes='q-ma-lg') value_avatar = jp.QAvatar(text='50', color='red', text_color='white', a=chip) jp.Span(text='Splitter value', a=chip) s.value_avatar = value_avatar def splitter_input(self, msg): self.value_avatar.text = int(self.value) s.on('input', splitter_input) s.separator_slot = value_avatar return wp jp.justpy(quasar_splitter_test) ``` -------------------------------- ### Heroku Procfile for JustPy Source: https://github.com/justpy-org/justpy/blob/master/docs/blog/heroku.md Defines the command that Heroku will run to start your web application. This specific Procfile indicates that the application is a web process and should be started using `python` with the `demo_browser.py` script, including Heroku-specific flags. ```bash web: python examples/demo_browser.py --heroku -d ``` -------------------------------- ### JustPy: Create QExpansionItems in a Loop Source: https://github.com/justpy-org/justpy/blob/master/docs/quasar_tutorial/quasar_components.md This example demonstrates how to create multiple QExpansionItem components dynamically within a loop and add them to a QList. Each expansion item contains a QCard with text content. It utilizes the justpy library for web development. ```python import justpy as jp sample_text = """ Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quidem, eius reprehenderit eos corrupti commodi magni quaerat ex numquam, dolorum officiis modi facere maiores architecto suscipit iste eveniet doloribus ullam aliquid. """ def quasar_expansion_item1(): wp = jp.QuasarPage() d = jp.Div(classes="q-pa-md", style="max-width: 350px", a=wp) item_list = jp.QList(classes="rounded-borders", padding=True, bordered=True, a=d) for info in [("perm_identity", "Account settings"), ("signal_wifi_off", "Wifi settings"), ("drafts", "Drafts")]: expansion_item = jp.QExpansionItem(icon=info[0], label=info[1], a=item_list, header_class='text-purple', dense=True, dense_toggle=True, expand_separator=True) card= jp.QCard(a=expansion_item) jp.QCardSection(text=sample_text, a=card) return wp jp.justpy(quasar_expansion_item1) ``` -------------------------------- ### Expose JustPy App for Uvicorn Source: https://github.com/justpy-org/justpy/blob/master/docs/tutorial/deployment.md Exposes the JustPy application instance as a Starlette app, making it compatible with uvicorn for more complex deployments. This code should be added to your main JustPy program file after importing the justpy library. ```python import justpy as jp app = jp.app ``` -------------------------------- ### Python Configuration Settings for JustPy Source: https://github.com/justpy-org/justpy/blob/master/docs/tutorial/configuration.md Example Python code snippet demonstrating configuration settings for the JustPy framework. These settings control various aspects of the framework's behavior, such as enabling charting libraries, logging, and network simulation. ```python HIGHCHARTS = True AGGRID = True LOGGING_LEVEL = DEBUG LATENCY = 50 SECRET_KEY = '$$$my_secret_string$$$' QUASAR_VERSION = '1.9.4' ``` -------------------------------- ### Set Default Route and Specific Route with jp.Route Source: https://github.com/justpy-org/justpy/blob/master/docs/tutorial/routes.md This example sets a specific route '/hello' and also defines a default route handled by `bye_function1`. Requests to '/hello' will execute `hello_function2`, while all other paths will be handled by `bye_function1`, displaying 'Goodbye!'. ```python import justpy as jp def hello_function2(): wp = jp.WebPage() wp.add(jp.P(text='Hello there!', classes='text-5xl m-2')) return wp def bye_function1(): wp = jp.WebPage() wp.add(jp.P(text='Goodbye!', classes='text-5xl m-2')) return wp jp.Route('/hello', hello_function2) jp.justpy(bye_function1) ``` -------------------------------- ### JustPy Template Options Configuration Source: https://github.com/justpy-org/justpy/blob/master/docs/reference/justpy.md This example shows how to configure template options for JustPy, such as enabling or disabling libraries like Tailwind, Quasar, Highcharts, AG Grid, or specifying a static file name. These options can be passed as keyword arguments. ```python template_options = {'tailwind': TAILWIND, 'quasar': QUASAR, 'highcharts': HIGHCHARTS, 'aggrid': AGGRID, 'static_name': STATIC_NAME} # Example: Disable Highcharts jp.justpy(highcharts=False) ``` -------------------------------- ### Integrate QDate and QTime with QInput using JustPy Function Source: https://github.com/justpy-org/justpy/blob/master/docs/quasar_tutorial/quasar_components.md This example demonstrates integrating QDate and QTime as slots within a QInput component in JustPy. It uses `jp.parse_html` to create the slot elements and links them to a model for date and time updates. ```python import justpy as jp # https://quasar.dev/vue-components/date#With-QInput def input_test3(): wp = jp.QuasarPage(data={'date': '2019-02-01 12:44'}) in1 = jp.QInput(filled=True, style='width: 400px', a=wp, model=[wp, 'date'], classes="q-pa-md") date_slot = jp.parse_html( """ """) time_slot = jp.parse_html( """ """) date_slot.name_dict['date'].model = [wp, 'date'] time_slot.name_dict['time'].model = [wp, 'date'] in1.prepend_slot = date_slot in1.append_slot = time_slot return wp jp.justpy(input_test3) ``` -------------------------------- ### Basic 'Hello World' Web Page with JustPy Source: https://github.com/justpy-org/justpy/blob/master/README.md This Python code snippet demonstrates the basic setup of a JustPy web server. It creates a simple web page with the text 'Hello world!'. The function `hello_world` constructs the page, and `jp.justpy(hello_world)` activates the server. No external libraries beyond 'justpy' are required. ```python import justpy as jp def hello_world(): wp = jp.WebPage() d = jp.Div(text='Hello world!') wp.add(d) return wp jp.justpy(hello_world) ``` -------------------------------- ### JustPy: QInput with Input Mask Source: https://github.com/justpy-org/justpy/blob/master/docs/quasar_tutorial/quasar_components.md Illustrates how to use the `mask` property of QInput to enforce a specific input format, such as a phone number. This simplifies data entry by guiding the user and ensuring data consistency. The example defines a phone number mask. ```python import justpy as jp def input_test9(request): wp = jp.QuasarPage(data={'text': ''}) c1 = jp.Div(classes='q-pa-md', a=wp) c2 = jp.Div(classes='q-gutter-md', style='max-width: 300px', a=c1) jp.QInput(filled=True, label='Phone', mask='(###) ### - ####', hint="Mask: (###) ### - ####", a=c2) return wp jp.justpy(input_test9) ``` -------------------------------- ### JustPy QBtn Component Example with Click Handler Source: https://github.com/justpy-org/justpy/blob/master/docs/quasar_tutorial/introduction.md Demonstrates the usage of the JustPy QBtn component, a wrapper for Quasar's QBtn. It shows how to set button properties like color, icon, and label, and how to attach a click event handler that dynamically changes the button's appearance and toggles dark mode on the page. ```python import justpy as jp import random async def my_click(self, msg): self.color = random.choice(['primary', 'secondary', 'accent', 'dark', 'positive', 'negative','info', 'warning']) self.label = self.color msg.page.dark = not msg.page.dark await msg.page.set_dark_mode(msg.page.dark) def quasar_example1(): wp = jp.QuasarPage(dark=True) # Load page in dark mode d = jp.Div(classes='q-pa-md q-gutter-sm', a=wp) jp.QBtn(color='primary', icon='mail', label='On Left', a=d, click=my_click) jp.QBtn(color='secondary', icon_right='mail', label='On Right', a=d, click=my_click) jp.QBtn(color='red', icon='mail', icon_right='send', label='On Left and Right', a=d, click=my_click) jp.Br(a=d) jp.QBtn(icon='phone', label='Stacked', stack=True, glossy=True, color='purple', a=d, click=my_click) return wp jp.justpy(quasar_example1) ``` -------------------------------- ### Filter List with QList and QOptionGroup in Python Source: https://github.com/justpy-org/justpy/blob/master/docs/quasar_tutorial/quasar_components.md This example demonstrates how to dynamically filter a list displayed using QList based on checkbox selections from QOptionGroup. The `check_box_clicked` function filters the list items that start with any of the selected checkboxes' values. It updates the visibility of list items in real-time. ```python import justpy as jp def check_box_clicked(self, msg): wp = msg.page def my_filter(var): for letter in self.value: if var.startswith(letter): return True return False filtered_list = list(filter(my_filter, wp.list_item_text)) for c in wp.q_list.components: if c.components[0].text not in filtered_list: c.show = False else: c.show = True def reactive_list_test(): wp = jp.QuasarPage() d = jp.Div(classes="q-pa-md", style="max-width: 400px", a=wp) wp.list_item_text = ['apple', 'ad', 'aardvark', 'again', 'bean', 'bath', 'beauty', 'can', 'corner', 'capital'] wp.q_list = jp.QList(dense=True, bordered=True, padding=True, classes="rounded-borders", a=d) for word in wp.list_item_text: q_item = jp.QItem(clickable=True, v_ripple=True, a=wp.q_list) jp.QItemSection(text=word, a=q_item) option_group = jp.QOptionGroup(type='checkbox', color='green', a=d, input=check_box_clicked, value=['a', 'b', 'c'], inline=True, classes='q-ma-lg', options=[{'label': 'A words', 'value': 'a'}, {'label': 'B words', 'value': 'b'}, {'label': 'C words', 'value': 'c'}]) return wp jp.justpy(reactive_list_test) ``` -------------------------------- ### JustPy QBtn Component Initialization with Props Source: https://github.com/justpy-org/justpy/blob/master/docs/quasar_tutorial/introduction.md Illustrates how to initialize a JustPy QBtn component, which wraps a Quasar QBtn. This example shows setting the 'round' prop to True and defining other properties like 'color' and 'icon'. It highlights the conversion of Quasar's kebab-case props (e.g., 'icon-right') to JustPy's snake_case attributes (e.g., 'icon_right'). ```python import justpy as jp jp.QBtn(round=True, color='primary', icon='shopping_cart') ``` -------------------------------- ### Creating a Basic WebPage Instance (Python) Source: https://github.com/justpy-org/justpy/blob/master/docs/reference/webpage.md A fundamental example showing the instantiation of a WebPage object using the 'justpy' library. This creates a basic web page instance that can then be further configured or used as a base for more complex pages. Requires 'import justpy as jp'. ```python import justpy as jp wp = jp.WebPage() ``` -------------------------------- ### Pandas Extension: Customize AgGrid with Pagination and Styling Source: https://github.com/justpy-org/justpy/blob/master/docs/grids_tutorial/pandas.md Demonstrates advanced customization of an AgGrid created via the pandas extension. This example enables pagination, sets auto page size, and applies conditional styling to cells based on their values. It requires pandas and JustPy to be installed. ```python import justpy as jp import pandas as pd wm_df = pd.read_csv('https://elimintz.github.io/women_majors.csv').round(2) def grid_test18(): wp = jp.WebPage() grid = wm_df.jp.ag_grid(a=wp) grid.options.pagination = True grid.options.paginationAutoPageSize = True grid.options.columnDefs[0].cellClass = ['text-white', 'bg-blue-500', 'hover:bg-blue-200'] for col_def in grid.options.columnDefs[1:]: col_def.cellClassRules = { 'font-bold': 'x < 20', 'bg-red-300': 'x < 20', 'bg-yellow-300': 'x >= 20 && x < 50', 'bg-green-300': 'x >= 50' } return wp jp.justpy(grid_test18) ``` -------------------------------- ### JustPy: Demonstrate Various QInput Component Styles Source: https://github.com/justpy-org/justpy/blob/master/docs/quasar_tutorial/quasar_components.md This example showcases multiple QInput components with different styling options like 'filled', 'outlined', 'standout', 'borderless', 'rounded', and 'square'. All input fields are linked to a common 'text' model, allowing them to share and update the same data. ```python import justpy as jp def input_test5(request): wp = jp.QuasarPage(data={'text': ''}) c1 = jp.Div(classes='q-pa-md', a=wp) c2 = jp.Div(classes='q-gutter-md', style='max-width: 300px', a=c1) c3 = jp.QInput(label='Standard', a=c2, model=[wp, 'text']) c4 = jp.QInput(filled=True, label='Filled', a=c2, model=[wp, 'text']) c5 = jp.QInput(outlined=True, label='Outlined', a=c2, model=[wp, 'text']) c6 = jp.QInput(standout=True, label='Standout', a=c2, model=[wp, 'text']) c7 = jp.QInput(standout='bg-teal text-white', label='Custom standout', a=c2, model=[wp, 'text']) c8 = jp.QInput(borderless=True, label='Borderless', a=c2, model=[wp, 'text']) c9 = jp.QInput(rounded=True, filled=True, label='Rounded filled', a=c2, model=[wp, 'text']) c10 = jp.QInput(rounded=True, outlined=True, label='Rounded outlined', a=c2, model=[wp, 'text']) c11 = jp.QInput(rounded=True, standout=True, label='Rounded standout', a=c2, model=[wp, 'text']) c12 = jp.QInput(square=True, filled=True, label='Square filled', hint='This is a hint', a=c2, model=[wp, 'text']) c13 = jp.QInput(square=True, outlined=True, label='Square outlined', a=c2, model=[wp, 'text']) c14 = jp.QInput(square=True, standout=True, label='Square standout', a=c2, model=[wp, 'text']) return wp jp.justpy(input_test5) ``` -------------------------------- ### Monitor User Inactivity with JustPy and asyncio Source: https://github.com/justpy-org/justpy/blob/master/docs/how_to/monitor_idle.md This Python snippet shows how to monitor user inactivity on a JustPy web page. It records the start time when the page loads and updates it on mouse movement. An `asyncio` task periodically checks the elapsed time and updates a div to display the idle duration if it exceeds a threshold. Dependencies include 'justpy', 'time', and 'asyncio'. ```python import justpy as jp import time import asyncio def mouse_moved(self, msg): print('mouse moved') msg.page.start_time = time.perf_counter() return True async def idle_test(): wp = jp.WebPage() wp.start_time = time.perf_counter() d = jp.Div(style='height: 100vh', a=wp) d.add_event('mousemove') d.on('mousemove', mouse_moved) wp.idle_div = jp.Div(text='Idle time', classes='m-4 text-lg', a=d) # Has to be in request handler so can be specific per page async def monitor_timer(): keep_monitoring = True idle_threshold = 5 while keep_monitoring: try: await asyncio.sleep(5) idle_time = time.perf_counter() - wp.start_time if idle_time > idle_threshold: wp.idle_div.text = f'Idle for {idle_time} seconds' jp.run_task(wp.update()) except: # When page is closed, it will be erased, the exception will occur and the task will terminate keep_monitoring = False jp.run_task(monitor_timer()) return wp jp.justpy(idle_test) ``` -------------------------------- ### Python JustPy Countdown with Async Updates Source: https://github.com/justpy-org/justpy/blob/master/docs/tutorial/pushing_data.md This Python snippet implements a real-time countdown functionality using the JustPy framework. It defines an asynchronous event handler to update the UI every second, allowing for a dynamic countdown display. The code also demonstrates how to manage component visibility and integrate CSS animations for visual feedback. Dependencies include 'justpy' and 'asyncio'. It takes optional query parameters 'num' for the starting number and 'animation' for the CSS animation effect. ```python import justpy as jp import asyncio button_classes = 'm-2 p-2 text-red-700 bg-white hover:bg-red-200 hover:text-red-500 border focus:border-red-500 focus:outline-none' async def count_down(self, msg): self.show = False if hasattr(msg.page, 'd'): msg.page.remove(msg.page.d) bomb_icon = jp.Icon(icon='bomb', classes='inline-block text-5xl ml-1 mt-1', a=msg.page) d = jp.Div(classes='text-center m-4 p-4 text-6xl text-red-600 bg-blue-500 faster', a=msg.page, animation=self.count_animation) msg.page.d = d for i in range(self.start_num, 0 , -1): d.text = str(i) await msg.page.update() await asyncio.sleep(1) d.text = 'Boom!' d.animation = 'zoomIn' d.set_classes('text-red-500 bg-white') bomb_icon.set_class('text-red-700') self.show = True def count_test(request): start_num = int(request.query_params.get('num', 10)) animation = request.query_params.get('animation', 'flip') wp = jp.WebPage() count_button = jp.Button(text='Start Countdown', classes=button_classes, a=wp, click=count_down) count_button.start_num = start_num count_button.count_animation = animation return wp jp.justpy(count_test) ``` -------------------------------- ### Install Heroku CLI Source: https://github.com/justpy-org/justpy/blob/master/docs/blog/heroku.md Installs the Heroku Command Line Interface (CLI) globally using npm. This tool is necessary for interacting with Heroku services from your local machine. ```bash npm install -g heroku ``` -------------------------------- ### JustPy QInput Component with Slot Usage Source: https://github.com/justpy-org/justpy/blob/master/docs/quasar_tutorial/introduction.md Demonstrates how to use slots within JustPy Quasar components, specifically the QInput component. It shows how to insert elements (like QIcon) into predefined slots such as 'append', 'prepend', and 'before' using attribute assignment with the '_slot' suffix. ```python import justpy as jp def input_test1(request): wp = jp.QuasarPage() c1 = jp.Div(classes='q-pa-md', a=wp) c2 = jp.Div(classes='q-gutter-md', style='max-width: 300px', a=c1) icon1 = jp.QIcon(name='event', color='blue') icon2 = jp.QIcon(name='place', color='red') for slot in ['append', 'prepend', 'before']: in1 = jp.QInput(label=slot, filled=True, hint=f'Icon is in slot "{slot}" and "after"', a=c2, after_slot=icon2) setattr(in1, slot + '_slot', icon1) return wp jp.justpy(input_test1) ``` -------------------------------- ### Combine QDate and QTime Pickers with QBadge in JustPy Source: https://github.com/justpy-org/justpy/blob/master/docs/quasar_tutorial/quasar_components.md This example showcases the integration of QDate and QTime components in JustPy, allowing users to select a date and time. Both components are configured with a 'YYYY-MM-DD HH:mm' mask and share a common model binding with a QBadge. The QBadge displays the selected date and time, demonstrating the synchronization between the date/time pickers and the badge. ```python import justpy as jp html_string = """
Mask: YYYY-MM-DD HH:mm
" def date_time_test(): wp = jp.QuasarPage(data={'date': '2020-01-01 07:00'}) d = jp.parse_html(html_string, a=wp) for c in ['badge', 'date', 'time']: d.name_dict[c].model = [wp, 'date'] return wp jp.justpy(date_time_test) ``` -------------------------------- ### Install Heroku Build Plugin Source: https://github.com/justpy-org/justpy/blob/master/docs/blog/heroku.md Installs the `heroku-builds` plugin, which extends the Heroku CLI's capabilities related to build management. This plugin is often used for advanced build control, such as cancelling builds. ```bash heroku plugins:install heroku-builds ``` -------------------------------- ### Create and Control QAjaxBar with JustPy Source: https://github.com/justpy-org/justpy/blob/master/docs/quasar_tutorial/quasar_components.md This snippet demonstrates how to use the QAjaxBar component in JustPy to display a progress bar. It includes functions to start and stop the bar, and initializes it with specific properties like position, color, and size. The `temp=False` argument is crucial for enabling `run_method`. ```python import justpy as jp async def start_bar(self, msg): wp = msg.page await wp.ajax_bar.run_method('start()', msg.websocket) async def stop_bar(self, msg): wp = msg.page await wp.ajax_bar.run_method('stop()', msg.websocket) def ajax_bar_example(): wp = jp.QuasarPage() d = jp.Div(classes='q-pa-md', a=wp) # temp=False is important because this generates an id for the element that is required for run_method to work wp.ajax_bar = jp.QAjaxBar(position='bottom', color='accent', size='10px', skip_hijack=True, a=d, temp=False) btn_start = jp.QBtn(color='primary', label='Start Bar', a=d, click=start_bar, style='margin-right: 20px') btn_stop = jp.QBtn(color='primary', label='Stop Bar', a=d, click=stop_bar) return wp jp.justpy(ajax_bar_example) ``` -------------------------------- ### Configure QDiv Directives with Dictionaries in JustPy Source: https://github.com/justpy-org/justpy/blob/master/docs/quasar_tutorial/introduction.md Shows how to configure Quasar directives on a `QDiv` component using a dictionary for more advanced options. This example demonstrates configuring the `v-ripple` directive with specific properties like `center` and `color` for a customized ripple effect. ```python import justpy as jp # https://quasar.dev/vue-directives/material-ripple#Ripple-API def ripple_test(): """ show the Quasar ripple effect """ wp = jp.QuasarPage() d = jp.QDiv(classes="q-pa-md q-gutter-md row justify-center", a=wp) d1 = jp.QDiv( v_ripple={'center': True, 'color': 'orange-5'}, classes="relative-position container bg-grey-3 text-black inline flex flex-center", text='center', style='border-radius: 50%; cursor: pointer; width: 150px; height: 150px', a=d) return wp jp.justpy(ripple_test) ``` -------------------------------- ### Get Number of Direct Children Elements Source: https://github.com/justpy-org/justpy/blob/master/docs/reference/htmlcomponent.md The `__len__` method allows using the built-in `len()` function on an element to get the count of its direct child elements. This provides a quick way to ascertain the size of an element's content. ```python def __len__(self): "" ``` -------------------------------- ### JustPy: Create Custom QExpansionItem Component with Image Source: https://github.com/justpy-org/justpy/blob/master/docs/quasar_tutorial/quasar_components.md This example shows how to create a custom component, `My_expansion`, that inherits from `jp.QExpansionItem`. This custom component includes an image from Lorem Picsum and custom styling. It also demonstrates adding, closing, and opening multiple instances dynamically. ```python import justpy as jp class My_expansion(jp.QExpansionItem): image_num = 10 # Start from image 10, previous are boring to my taste def __init__(self, **kwargs): super().__init__(**kwargs) outer_div = jp.Div(classes="q-pa-md", a=self) jp.QImg(src=f'https://picsum.photos/400/300/?image={My_expansion.image_num}', a=outer_div) self.icon = "photo" self.label = f'Image {My_expansion.image_num}' self.value = True self.expand_separator = True self.header_class = "bg-teal text-white text-overline" My_expansion.image_num += 1 def quasar_expansion_item2(request): wp = jp.QuasarPage(dark=False) d = jp.Div(classes="q-pa-md ", style="max-width: 500px", a=wp) jp.Link(href='https://quasar.dev/vue-components/expansion-item', text='Quasar Expansion Item Example', target='_blank', classes="text-h5 q-mb-md", a=d, style='display: block;') add_btn = jp.QBtn(label='Add Image', classes="q-mb-md", color='primary', a=d) close_btn = jp.QBtn(label='Close All', classes="q-ml-md q-mb-md", color='negative', a=d) open_btn = jp.QBtn(label='Open All', classes="q-ml-md q-mb-md", color='positive', a=d) l = jp.QList(bordered=True, a=d) wp.list = l l.add_component(My_expansion(), 0) def add_pic(self, msg): msg.page.list.add_component(My_expansion(), 0) add_btn.on('click', add_pic) def close_pics(self, msg): for c in msg.page.list.components: c.value = False close_btn.on('click', close_pics) def open_pics(self, msg): for c in msg.page.list.components: c.value = True open_btn.on('click', open_pics) return wp jp.justpy(quasar_expansion_item2) ``` -------------------------------- ### JustPy Python Element Visibility Example Source: https://github.com/justpy-org/justpy/blob/master/docs/tutorial/html_components.md Illustrates how to control the visibility of HTML elements in JustPy using the 'show' attribute and Tailwind CSS classes 'invisible' and 'visible'. The example includes buttons to toggle the display and visibility of different div elements. ```python import justpy as jp button_classes='m-2 bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded' def show_demo(): wp = jp.WebPage() b = jp.Button(text='Click to toggle show', a=wp, classes=button_classes) d = jp.Div(text='Toggled by show', classes='m-2 p-2 text-2xl border w-48', a=wp) b.d = d jp.Div(text='Will always show', classes='m-2', a=wp) def toggle_show(self, msg): self.d.show = not self.d.show b.on('click', toggle_show) b = jp.Button(text='Click to toggle visibility', a=wp, classes=button_classes) d = jp.Div(text='Toggled by visible', classes='m-2 p-2 text-2xl border w-48', a=wp) d.visibility_state = 'visible' b.d = d jp.Div(text='Will always show', classes='m-2', a=wp) def toggle_visible(self, msg): if self.d.visibility_state == 'visible': self.d.set_class('invisible') self.d.visibility_state = 'invisible' else: self.d.set_class('visible') self.d.visibility_state = 'visible' b.on('click', toggle_visible) return wp jp.justpy(show_demo) ``` -------------------------------- ### JustPy Session Management Example Source: https://github.com/justpy-org/justpy/blob/master/docs/tutorial/sessions.md This Python code provides a simple JustPy web application example that utilizes sessions. It tracks the number of visits and click events for each user session using a dictionary. The session ID is accessed via `request.session_id` and within event handlers via `msg.session_id`. ```python import justpy as jp session_dict = {} def session_test(request): wp = jp.WebPage() if request.session_id not in session_dict: session_dict[request.session_id] = {'visits': 0, 'events': 0} session_data = session_dict[request.session_id] session_data['visits'] += 1 jp.Div(text=f'My session id: {request.session_id}', classes='m-2 p-1 text-xl', a=wp) visits_div = jp.Div(text=f'Number of visits: {session_data["visits"]}', classes='m-2 p-1 text-xl', a=wp) b = jp.Button(text=f'Number of Click Events: {session_data["events"]}', classes='m-1 bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-full', a=wp) b.visits_div = visits_div def my_click(self, msg): session_data = session_dict[msg.session_id] session_data['events'] += 1 self.text =f'Number of Click Events: {session_data["events"]}' self.visits_div.text = f'Number of visits: {session_data["visits"]}' b.on('click', my_click) return wp jp.justpy(session_test) ``` -------------------------------- ### Instantiate and Run JustPy Web Page Source: https://github.com/justpy-org/justpy/blob/master/docs/tutorial/custom_components.md Provides an example function `alert_test1` that creates a JustPy web page and adds an instance of the custom `MyAlert` component to it. It also demonstrates how to set attributes on the component instance and the potential issue with updating attributes after creation. ```python import justpy as jp # (MyAlert class definition would be here) def alert_test1(): wp = jp.WebPage() d = MyAlert(a=wp, classes='m-2 w-1/4', title_text='hello', body_text='How is everybody?') d.title_text = 'Shalom' return wp jp.justpy(alert_test1) ``` -------------------------------- ### Parse Quasar HTML Tags with JustPy Source: https://github.com/justpy-org/justpy/blob/master/docs/quasar_tutorial/introduction.md Demonstrates how to use JustPy's `parse_html` function to process HTML strings containing Quasar tags. It also shows how to access and print the generated JustPy commands for HTML construction. This is useful for directly using Quasar documentation examples. ```python import justpy as jp html_string = """
Icon as avatar Avatar-type icon Rounded avatar-type icon R Letter avatar-type Image avatar Image square avatar Image rounded avatar List item List item
""" def quasar_example2(): """ Show parsing and command generation """ wp = jp.QuasarPage() div_root_component = jp.parse_html(html_string, a=wp) # print out all commands on console for i in div_root_component.commands: print(i) return wp jp.justpy(quasar_example2) ``` -------------------------------- ### JustPy Todo List Manager Source: https://github.com/justpy-org/justpy/blob/master/docs/blog/vue_examples.md This Python example implements a simple Todo list manager using JustPy. It allows users to add new tasks to a list, which are then displayed as ordered list items. The component manages the list of todos and provides an input field and button for adding new tasks. ```python import justpy as jp class TodoList(jp.Div): def __init__(self, **kwargs): self.todos = [] super().__init__(**kwargs) self.ol = jp.Ol(a=self) self.task = jp.Input(placeholder='Enter task', a=self) jp.Button(text='Add Task', a=self, click=self.add_task, style='margin-left: 10px') def add_task(self, msg): self.todos.append(self.task.value) self.task.value = '' def react(self, data): self.ol.delete_components() for todo in self.todos: jp.Li(text=todo, a=self.ol) def todo_app_vue1(): wp = jp.WebPage(tailwind=False) TodoList(a=wp, todos=['Buy groceries', 'Learn JustPy', 'Do errands']) return wp jp.justpy(todo_app_vue1) ```