ANI

Creating Pure Pure Web Apps with Reflex

Creating Pure Pure Web Apps with ReflexPhoto by the writer

When we talk about Python, we often think about using the data analysis or forming a machine learning model. It is familiar to create a web full apps with Python without simple prototypes using libraries such as Support either Taiphety.

However, the library was called Moderate It provides features of the development of a web app that competes with those in other planning languages. Completely in Python, open library is helping users to build anything from small scientific apps on large websites, with many pages. According to a strong agreement, however, the correct Python code, we can easily improve web development to suit our needs with Reflex needs.

In this article, we will read the foundations to build a purethon's pure web system with reflex.

To Create Web Settings with Reflex

In this lesson, we will update the building of the Web system with Reflex. With very good habits, it would be good to use a physical area to avoid disturbing the perfect environment.

With this in mind, we will begin to improve our Reflex Web program by installing Reflex Library using the Code below:

We will then evaluate the reflex by creating a new project and starts a new application. Use the following code, but change test_app The folder name is your site.

mkdir test_app
cd test_app
reflex init

The above code moves you with the questions that you want to create a project through the previously created template.

Creating Pure Pure Web Apps with ReflexCreating Pure Pure Web Apps with Reflex

In this lesson, select the application of the Blank Reflex, and you will see the new project structure made, such as the below.

Creating Pure Pure Web Apps with ReflexCreating Pure Pure Web Apps with Reflex

Run the following command to see if your Reflex app works well:

Visit the operating local URL. If it works well, you will see something like the picture below:

Creating Pure Pure Web Apps with ReflexCreating Pure Pure Web Apps with Reflex

This is the basic web system produced by reflex. We will build something very complex later, but we will start on basic basis.

Let's first understand nutrients used to create a web system in the Reflex brochure. First, open

test_app.py Then place the following content of the following code:

import reflex as rx

class State(rx.State):
    count: int = 0

    def increment(self):
        self.count += 1

    def decrement(self):
        self.count -= 1

def index():
    return rx.hstack(
        rx.button(
            "Decrement",
            color_scheme="ruby",
            on_click=State.decrement,
        ),
        rx.heading(State.count, font_size="2em"),
        rx.button(
            "Increment",
            color_scheme="grass",
            on_click=State.increment,
        ),
        spacing="4",
    )

app = rx.App()
app.add_page(index)

This will show a website similar to that below.

Creating Pure Pure Web Apps with ReflexCreating Pure Pure Web Apps with Reflex

Let's break what is happening in the code above.

First, we explain the situation, containing changes (called vars) and activities (called event handlers) That can change the status of the app.

For example, we describe one flexion called count that holds the number of number with the first value of 0.

class State(rx.State):
    count: int = 0

Then we have occasion management – tasks within a variable shape change in user actions. In the code above, it describes the event managers as follows:

def increment(self):
    self.count += 1

def decrement(self):
    self.count -= 1

Next, defines the web app as follows:

def index():
    return rx.hstack(
        rx.button(
            "Decrement",
            color_scheme="ruby",
            on_click=State.decrement,
        ),
        rx.heading(State.count, font_size="2em"),
        rx.button(
            "Increment",
            color_scheme="grass",
            on_click=State.increment,
        ),
        spacing="4",
    )

The following functions describe the web app interface and use the following elements to create an UI:

  • rx.hstack: It is used to put horizontal things
  • rx.button: It is used to indicate the fuel button when you click
  • rx.heading: It is used to show text in different size

As you can see in the above code, target titles count Variably in the Kingdom, and each Button runs a work in a position when you are clicked.

There are many many components that you can use to build a web system; See Reflex nutrients.

Finally, we define the app and add parts to the basic method with the following code:

app = rx.App()
app.add_page(index)

That is a simple definition of important nutrients used by Reflex to build a web system.

With the above meaning, let's build a very advanced web app with Reflex. In the example below, we will improve the listing app to complete and remove items from.

import uuid
import reflex as rx
from typing import Any, Dict, List

class TodoState(rx.State):
    todos: List[Dict[str, Any]] = []
    new_text: str = ""
    current_filter: str = "all"   # Select between "all", "active", "done"

    # Derived values (computed from state)
    @rx.var
    def items_left(self) -> int:
        return sum(1 for t in self.todos if not t["done"])

    @rx.var
    def items_left_label(self) -> str:
        return "1 item left" if self.items_left == 1 else f"{self.items_left} items left"

    @rx.var
    def filtered_todos(self) -> List[Dict[str, Any]]:
        if self.current_filter == "active":
            return [t for t in self.todos if not t["done"]]
        if self.current_filter == "done":
            return [t for t in self.todos if t["done"]]
        return self.todos

    # Events (mutate state)
    @rx.event
    def set_new_text(self, value: str):
        self.new_text = (value or "").strip()

    @rx.event
    def add_todo(self):
        text = (self.new_text or "").strip()
        if not text:
            return
        self.todos.append({"id": str(uuid.uuid4()), "text": text, "done": False})
        self.new_text = ""

    @rx.event
    def toggle(self, todo_id: str):
        for t in self.todos:
            if t["id"] == todo_id:
                t["done"] = not t["done"]
                break

    @rx.event
    def remove(self, todo_id: str):
        self.todos = [t for t in self.todos if t["id"] != todo_id]

    @rx.event
    def clear_completed(self):
        self.todos = [t for t in self.todos if not t["done"]]

    @rx.event
    def set_filter(self, name: str):
        if name in {"all", "active", "done"}:
            self.current_filter = name

def filter_button(name: str, label: str) -> rx.Component:
    return rx.button(
        label,
        size="2",
        variant=rx.cond(TodoState.current_filter == name, "solid", "soft"),
        background_color=rx.cond(
            TodoState.current_filter == name, "blue.600", "gray.700"
        ),
        color="white",
        _hover={"background_color": "blue.500"},
        on_click=lambda: TodoState.set_filter(name),
    )

def render_todo_item(todo: rx.Var[dict]) -> rx.Component:
    return rx.hstack(
        rx.checkbox(
            is_checked=todo["done"],
            on_change=lambda _: TodoState.toggle(todo["id"]),
            size="2",
            color_scheme="blue",
        ),
        rx.text(
            todo["text"],
            flex="1",
            color=rx.cond(todo["done"], "gray.500", "white"),
            text_decoration=rx.cond(todo["done"], "line-through", "none"),
        ),
        rx.icon_button(
            "trash",
            color_scheme="red",
            variant="soft",
            on_click=lambda: TodoState.remove(todo["id"]),
        ),
        align="center",
        spacing="3",
        width="100%",
    )

def todo_input_bar() -> rx.Component:
    return rx.hstack(
        rx.input(
            placeholder="What needs to be done?",
            value=TodoState.new_text,
            on_change=TodoState.set_new_text,
            flex="1",
            size="3",
            background_color="gray.800",
            color="white",
            border_color="gray.600",
            _placeholder={"color": "gray.400"},
        ),
        rx.button(
            "Add",
            size="3",
            background_color="blue.600",
            color="white",
            _hover={"background_color": "blue.500"},
            on_click=TodoState.add_todo,
        ),
        spacing="3",
        width="100%",
    )

def todo_list_panel() -> rx.Component:
    return rx.vstack(
        rx.foreach(TodoState.filtered_todos, render_todo_item),
        spacing="2",
        width="100%",
    )

def footer_bar() -> rx.Component:
    return rx.hstack(
        rx.text(TodoState.items_left_label, size="2", color="gray.300"),
        rx.hstack(
            filter_button("all", "All"),
            filter_button("active", "Active"),
            filter_button("done", "Done"),
            spacing="2",
        ),
        rx.button(
            "Clear Completed",
            variant="soft",
            background_color="gray.700",
            color="white",
            _hover={"background_color": "gray.600"},
            on_click=TodoState.clear_completed,
        ),
        justify="between",
        align="center",
        width="100%",
    )

def index() -> rx.Component:
    return rx.center(
        rx.card(
            rx.vstack(
                rx.heading("Reflex To-Do", size="6", color="white"),
                todo_input_bar(),
                rx.separator(border_color="gray.700"),
                todo_list_panel(),
                rx.separator(margin_y="2", border_color="gray.700"),
                footer_bar(),
                width="min(720px, 92vw)",
                spacing="4",
            ),
            size="4",
            width="min(760px, 96vw)",
            shadow="lg",
            background_color="gray.900",
        ),
        min_h="100vh",
        padding_y="8",
        background_color="black",
    )

app = rx.App()
app.add_page(index, route=" title="Reflex To-Do")

The operating effect will look like a picture below.

Creating Pure Pure Web Apps with ReflexCreating Pure Pure Web Apps with Reflex

In the code above, the flow is actually valid as follows:

  1. The app keeps a small memory: Your works, typing, and any selected filter.
  2. Type in the box and the text is stored as you type.
  3. You press “Enter” and the work is saved (with ID) and the box is clean.
  4. The list updates quickly to show what is in memory.
  5. Each work line has a checkbox and a trash icon. Checking the completion of toggles; Garbage removes work.
  6. Three-filter buttons (all / applicable / made) Change what visible activities.
  7. Footer shows how many activities are made and allows you to 'wash out'.

Fewer Separation of Important – across the basic things covered at the beginning – including:

  1. Decorate with @rx.event to declare events within the state.
  2. Decorate with @rx.var creating variables from government.
  3. Work rx.Component Signatures in which UI helps are re-activated with your Reflex application.

That is the basic meaning and example of how to reflex. Try yourself and create a web app you need through pure Python.

Store

Reflex is an open source library that allows web applications to Pyntly pure pattern with an accurate yet accurate code pattern. Its straight setup and a simple understanding code allows users to keep logic and UI in one place. It is a useful table of developers and trained developers alike want to create an app with Python.

I hope this has helped!

Cornellius Yudha Wijaya It is a scientific science manager and the database author. While working full-time in Allianz Indonesia, she likes to share the python and data advice with social media and media writing. Cornellius writes to a variety of AI and a study machine.

Source link

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button