

Once we speak about Python, we frequently consider using it to carry out knowledge evaluation or construct a machine studying mannequin. It’s much less frequent to debate creating full net functions with Python outdoors of easy prototypes utilizing libraries akin to Streamlit or Taipy.
Nevertheless, a library referred to as Reflex affords net software improvement options that compete with these of different programming languages. Completely in Python, this open-source library helps customers construct something from small knowledge science apps to giant, multi-page web sites. With sturdy flexibility but intuitive Python code, we will simply scale net improvement to go well with our wants with Reflex.
On this article, we’ll be taught the fundamentals of constructing a pure Python net software with Reflex.
Constructing Internet Apps with Reflex
On this tutorial, we’ll evaluate the requirements for constructing an internet software with Reflex. For greatest practices, it’s advisable to make use of a digital setting to keep away from disrupting the general setting.
With this in thoughts, we’ll start growing our Reflex net software by putting in the Reflex library utilizing the code beneath:
We are going to then check Reflex by creating a brand new venture and initiating a brand new software. Use the next code, however change the test_app
folder title to your individual.
mkdir test_app
cd test_app
reflex init
The code above prompts you with questions on whether or not you wish to create the venture with a pre-made template or not.
For this tutorial, choose the clean Reflex app, and you will note the brand new venture construction created, just like the one beneath.
Run the next command to see in case your Reflex software runs correctly:
Go to the native URL serving the applying. If it really works properly, you will note one thing just like the picture beneath:
That is the fundamental net software scaffold generated by Reflex. We are going to construct one thing extra subtle later, however we’ll begin with the basics.
Let’s begin by understanding the elements used to construct the net software within the Reflex library. First, open
test_app.py
and exchange its contents with the next code:
import reflex as rx
class State(rx.State):
depend: int = 0
def increment(self):
self.depend += 1
def decrement(self):
self.depend -= 1
def index():
return rx.hstack(
rx.button(
"Decrement",
color_scheme="ruby",
on_click=State.decrement,
),
rx.heading(State.depend, font_size="2em"),
rx.button(
"Increment",
color_scheme="grass",
on_click=State.increment,
),
spacing="4",
)
app = rx.App()
app.add_page(index)
This may present a web site just like the one beneath.
Let’s break down what’s occurring within the code above.
First, we outline the state, which comprises variables (referred to as vars
) and capabilities (referred to as occasion handlers
) that may change the state of the applying.
For instance, we outline a single variable referred to as depend
that holds an integer with an preliminary worth of 0.
class State(rx.State):
depend: int = 0
Then we now have occasion handlers—capabilities inside the state that modify variables in response to consumer actions. Within the code above, we outline the occasion handlers as follows:
def increment(self):
self.depend += 1
def decrement(self):
self.depend -= 1
Subsequent, we outline the net software UI as follows:
def index():
return rx.hstack(
rx.button(
"Decrement",
color_scheme="ruby",
on_click=State.decrement,
),
rx.heading(State.depend, font_size="2em"),
rx.button(
"Increment",
color_scheme="grass",
on_click=State.increment,
),
spacing="4",
)
The capabilities above outline the net software interface and use the next elements to construct the UI:
rx.hstack
: used to stack components horizontallyrx.button
: used to point out a button that triggers an occasion when clickedrx.heading
: used to point out textual content in varied sizes
As you possibly can see within the code above, the heading part references the depend
variable within the state, and every button triggers a operate within the state when clicked.
There are a lot of extra elements you need to use to construct the net software; see the Reflex elements documentation.
Lastly, we outline the applying and add the elements to the bottom route with the next code:
app = rx.App()
app.add_page(index)
That could be a easy rationalization of the essential elements that Reflex makes use of to construct an internet software.
With the reason above performed, let’s construct a barely extra superior net software with Reflex. Within the instance beneath, we’ll develop a to-do listing software that we will fill and take away objects from.
import uuid
import reflex as rx
from typing import Any, Dict, Checklist
class TodoState(rx.State):
todos: Checklist[Dict[str, Any]] = []
new_text: str = ""
current_filter: str = "all" # Choose between "all", "energetic", "performed"
# 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 merchandise left" if self.items_left == 1 else f"{self.items_left} objects left"
@rx.var
def filtered_todos(self) -> Checklist[Dict[str, Any]]:
if self.current_filter == "energetic":
return [t for t in self.todos if not t["done"]]
if self.current_filter == "performed":
return [t for t in self.todos if t["done"]]
return self.todos
# Occasions (mutate state)
@rx.occasion
def set_new_text(self, worth: str):
self.new_text = (worth or "").strip()
@rx.occasion
def add_todo(self):
textual content = (self.new_text or "").strip()
if not textual content:
return
self.todos.append({"id": str(uuid.uuid4()), "textual content": textual content, "performed": False})
self.new_text = ""
@rx.occasion
def toggle(self, todo_id: str):
for t in self.todos:
if t["id"] == todo_id:
t["done"] = not t["done"]
break
@rx.occasion
def take away(self, todo_id: str):
self.todos = [t for t in self.todos if t["id"] != todo_id]
@rx.occasion
def clear_completed(self):
self.todos = [t for t in self.todos if not t["done"]]
@rx.occasion
def set_filter(self, title: str):
if title in {"all", "energetic", "performed"}:
self.current_filter = title
def filter_button(title: str, label: str) -> rx.Part:
return rx.button(
label,
dimension="2",
variant=rx.cond(TodoState.current_filter == title, "strong", "delicate"),
background_color=rx.cond(
TodoState.current_filter == title, "blue.600", "grey.700"
),
coloration="white",
_hover={"background_color": "blue.500"},
on_click=lambda: TodoState.set_filter(title),
)
def render_todo_item(todo: rx.Var[dict]) -> rx.Part:
return rx.hstack(
rx.checkbox(
is_checked=todo["done"],
on_change=lambda _: TodoState.toggle(todo["id"]),
dimension="2",
color_scheme="blue",
),
rx.textual content(
todo["text"],
flex="1",
coloration=rx.cond(todo["done"], "grey.500", "white"),
text_decoration=rx.cond(todo["done"], "line-through", "none"),
),
rx.icon_button(
"trash",
color_scheme="purple",
variant="delicate",
on_click=lambda: TodoState.take away(todo["id"]),
),
align="middle",
spacing="3",
width="100%",
)
def todo_input_bar() -> rx.Part:
return rx.hstack(
rx.enter(
placeholder="What must be performed?",
worth=TodoState.new_text,
on_change=TodoState.set_new_text,
flex="1",
dimension="3",
background_color="grey.800",
coloration="white",
border_color="grey.600",
_placeholder={"coloration": "grey.400"},
),
rx.button(
"Add",
dimension="3",
background_color="blue.600",
coloration="white",
_hover={"background_color": "blue.500"},
on_click=TodoState.add_todo,
),
spacing="3",
width="100%",
)
def todo_list_panel() -> rx.Part:
return rx.vstack(
rx.foreach(TodoState.filtered_todos, render_todo_item),
spacing="2",
width="100%",
)
def footer_bar() -> rx.Part:
return rx.hstack(
rx.textual content(TodoState.items_left_label, dimension="2", coloration="grey.300"),
rx.hstack(
filter_button("all", "All"),
filter_button("energetic", "Energetic"),
filter_button("performed", "Performed"),
spacing="2",
),
rx.button(
"Clear Accomplished",
variant="delicate",
background_color="grey.700",
coloration="white",
_hover={"background_color": "grey.600"},
on_click=TodoState.clear_completed,
),
justify="between",
align="middle",
width="100%",
)
def index() -> rx.Part:
return rx.middle(
rx.card(
rx.vstack(
rx.heading("Reflex To-Do", dimension="6", coloration="white"),
todo_input_bar(),
rx.separator(border_color="grey.700"),
todo_list_panel(),
rx.separator(margin_y="2", border_color="grey.700"),
footer_bar(),
width="min(720px, 92vw)",
spacing="4",
),
dimension="4",
width="min(760px, 96vw)",
shadow="lg",
background_color="grey.900",
),
min_h="100vh",
padding_y="8",
background_color="black",
)
app = rx.App()
app.add_page(index, route="https://www.kdnuggets.com/", title="Reflex To-Do")
The results of the applying will seem like the picture beneath.
Within the code above, the movement basically works as follows:
- The app retains a small reminiscence: your duties, what you’re typing, and which filter is chosen.
- You kind within the field and that textual content is saved as you kind.
- You press “Add” and the duty is saved (with an id) and the field clears.
- The listing immediately refreshes to point out what’s in reminiscence.
- Every job row has a checkbox and a trash icon. Checking toggles completion; the trash removes the duty.
- The three filter buttons (All / Energetic / Performed) change which duties are seen.
- The footer exhibits what number of duties will not be performed and allows you to “Clear Accomplished”.
A number of essential distinctions—past the fundamental elements lined earlier—embrace:
- Enhance with
@rx.occasion
to declare occasions inside the state. - Enhance with
@rx.var
to create derived variables within the state. - Use
rx.Part
signatures when constructing reusable UI helpers on your Reflex software.
That’s the primary rationalization and instance of how Reflex works. Strive it your self and construct the net software you want with pure Python.
Conclusion
Reflex is an open-source library that enables us to construct net functions in pure Python with a easy but intuitive code sample. Its simple setup and easy-to-understand code enable customers to maintain the logic and UI in a single place. It’s a helpful library for newcomers {and professional} builders alike who wish to construct an software with Python.
I hope this has helped!
Cornellius Yudha Wijaya is a knowledge science assistant supervisor and knowledge author. Whereas working full-time at Allianz Indonesia, he likes to share Python and knowledge ideas by way of social media and writing media. Cornellius writes on quite a lot of AI and machine studying matters.


Once we speak about Python, we frequently consider using it to carry out knowledge evaluation or construct a machine studying mannequin. It’s much less frequent to debate creating full net functions with Python outdoors of easy prototypes utilizing libraries akin to Streamlit or Taipy.
Nevertheless, a library referred to as Reflex affords net software improvement options that compete with these of different programming languages. Completely in Python, this open-source library helps customers construct something from small knowledge science apps to giant, multi-page web sites. With sturdy flexibility but intuitive Python code, we will simply scale net improvement to go well with our wants with Reflex.
On this article, we’ll be taught the fundamentals of constructing a pure Python net software with Reflex.
Constructing Internet Apps with Reflex
On this tutorial, we’ll evaluate the requirements for constructing an internet software with Reflex. For greatest practices, it’s advisable to make use of a digital setting to keep away from disrupting the general setting.
With this in thoughts, we’ll start growing our Reflex net software by putting in the Reflex library utilizing the code beneath:
We are going to then check Reflex by creating a brand new venture and initiating a brand new software. Use the next code, however change the test_app
folder title to your individual.
mkdir test_app
cd test_app
reflex init
The code above prompts you with questions on whether or not you wish to create the venture with a pre-made template or not.
For this tutorial, choose the clean Reflex app, and you will note the brand new venture construction created, just like the one beneath.
Run the next command to see in case your Reflex software runs correctly:
Go to the native URL serving the applying. If it really works properly, you will note one thing just like the picture beneath:
That is the fundamental net software scaffold generated by Reflex. We are going to construct one thing extra subtle later, however we’ll begin with the basics.
Let’s begin by understanding the elements used to construct the net software within the Reflex library. First, open
test_app.py
and exchange its contents with the next code:
import reflex as rx
class State(rx.State):
depend: int = 0
def increment(self):
self.depend += 1
def decrement(self):
self.depend -= 1
def index():
return rx.hstack(
rx.button(
"Decrement",
color_scheme="ruby",
on_click=State.decrement,
),
rx.heading(State.depend, font_size="2em"),
rx.button(
"Increment",
color_scheme="grass",
on_click=State.increment,
),
spacing="4",
)
app = rx.App()
app.add_page(index)
This may present a web site just like the one beneath.
Let’s break down what’s occurring within the code above.
First, we outline the state, which comprises variables (referred to as vars
) and capabilities (referred to as occasion handlers
) that may change the state of the applying.
For instance, we outline a single variable referred to as depend
that holds an integer with an preliminary worth of 0.
class State(rx.State):
depend: int = 0
Then we now have occasion handlers—capabilities inside the state that modify variables in response to consumer actions. Within the code above, we outline the occasion handlers as follows:
def increment(self):
self.depend += 1
def decrement(self):
self.depend -= 1
Subsequent, we outline the net software UI as follows:
def index():
return rx.hstack(
rx.button(
"Decrement",
color_scheme="ruby",
on_click=State.decrement,
),
rx.heading(State.depend, font_size="2em"),
rx.button(
"Increment",
color_scheme="grass",
on_click=State.increment,
),
spacing="4",
)
The capabilities above outline the net software interface and use the next elements to construct the UI:
rx.hstack
: used to stack components horizontallyrx.button
: used to point out a button that triggers an occasion when clickedrx.heading
: used to point out textual content in varied sizes
As you possibly can see within the code above, the heading part references the depend
variable within the state, and every button triggers a operate within the state when clicked.
There are a lot of extra elements you need to use to construct the net software; see the Reflex elements documentation.
Lastly, we outline the applying and add the elements to the bottom route with the next code:
app = rx.App()
app.add_page(index)
That could be a easy rationalization of the essential elements that Reflex makes use of to construct an internet software.
With the reason above performed, let’s construct a barely extra superior net software with Reflex. Within the instance beneath, we’ll develop a to-do listing software that we will fill and take away objects from.
import uuid
import reflex as rx
from typing import Any, Dict, Checklist
class TodoState(rx.State):
todos: Checklist[Dict[str, Any]] = []
new_text: str = ""
current_filter: str = "all" # Choose between "all", "energetic", "performed"
# 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 merchandise left" if self.items_left == 1 else f"{self.items_left} objects left"
@rx.var
def filtered_todos(self) -> Checklist[Dict[str, Any]]:
if self.current_filter == "energetic":
return [t for t in self.todos if not t["done"]]
if self.current_filter == "performed":
return [t for t in self.todos if t["done"]]
return self.todos
# Occasions (mutate state)
@rx.occasion
def set_new_text(self, worth: str):
self.new_text = (worth or "").strip()
@rx.occasion
def add_todo(self):
textual content = (self.new_text or "").strip()
if not textual content:
return
self.todos.append({"id": str(uuid.uuid4()), "textual content": textual content, "performed": False})
self.new_text = ""
@rx.occasion
def toggle(self, todo_id: str):
for t in self.todos:
if t["id"] == todo_id:
t["done"] = not t["done"]
break
@rx.occasion
def take away(self, todo_id: str):
self.todos = [t for t in self.todos if t["id"] != todo_id]
@rx.occasion
def clear_completed(self):
self.todos = [t for t in self.todos if not t["done"]]
@rx.occasion
def set_filter(self, title: str):
if title in {"all", "energetic", "performed"}:
self.current_filter = title
def filter_button(title: str, label: str) -> rx.Part:
return rx.button(
label,
dimension="2",
variant=rx.cond(TodoState.current_filter == title, "strong", "delicate"),
background_color=rx.cond(
TodoState.current_filter == title, "blue.600", "grey.700"
),
coloration="white",
_hover={"background_color": "blue.500"},
on_click=lambda: TodoState.set_filter(title),
)
def render_todo_item(todo: rx.Var[dict]) -> rx.Part:
return rx.hstack(
rx.checkbox(
is_checked=todo["done"],
on_change=lambda _: TodoState.toggle(todo["id"]),
dimension="2",
color_scheme="blue",
),
rx.textual content(
todo["text"],
flex="1",
coloration=rx.cond(todo["done"], "grey.500", "white"),
text_decoration=rx.cond(todo["done"], "line-through", "none"),
),
rx.icon_button(
"trash",
color_scheme="purple",
variant="delicate",
on_click=lambda: TodoState.take away(todo["id"]),
),
align="middle",
spacing="3",
width="100%",
)
def todo_input_bar() -> rx.Part:
return rx.hstack(
rx.enter(
placeholder="What must be performed?",
worth=TodoState.new_text,
on_change=TodoState.set_new_text,
flex="1",
dimension="3",
background_color="grey.800",
coloration="white",
border_color="grey.600",
_placeholder={"coloration": "grey.400"},
),
rx.button(
"Add",
dimension="3",
background_color="blue.600",
coloration="white",
_hover={"background_color": "blue.500"},
on_click=TodoState.add_todo,
),
spacing="3",
width="100%",
)
def todo_list_panel() -> rx.Part:
return rx.vstack(
rx.foreach(TodoState.filtered_todos, render_todo_item),
spacing="2",
width="100%",
)
def footer_bar() -> rx.Part:
return rx.hstack(
rx.textual content(TodoState.items_left_label, dimension="2", coloration="grey.300"),
rx.hstack(
filter_button("all", "All"),
filter_button("energetic", "Energetic"),
filter_button("performed", "Performed"),
spacing="2",
),
rx.button(
"Clear Accomplished",
variant="delicate",
background_color="grey.700",
coloration="white",
_hover={"background_color": "grey.600"},
on_click=TodoState.clear_completed,
),
justify="between",
align="middle",
width="100%",
)
def index() -> rx.Part:
return rx.middle(
rx.card(
rx.vstack(
rx.heading("Reflex To-Do", dimension="6", coloration="white"),
todo_input_bar(),
rx.separator(border_color="grey.700"),
todo_list_panel(),
rx.separator(margin_y="2", border_color="grey.700"),
footer_bar(),
width="min(720px, 92vw)",
spacing="4",
),
dimension="4",
width="min(760px, 96vw)",
shadow="lg",
background_color="grey.900",
),
min_h="100vh",
padding_y="8",
background_color="black",
)
app = rx.App()
app.add_page(index, route="https://www.kdnuggets.com/", title="Reflex To-Do")
The results of the applying will seem like the picture beneath.
Within the code above, the movement basically works as follows:
- The app retains a small reminiscence: your duties, what you’re typing, and which filter is chosen.
- You kind within the field and that textual content is saved as you kind.
- You press “Add” and the duty is saved (with an id) and the field clears.
- The listing immediately refreshes to point out what’s in reminiscence.
- Every job row has a checkbox and a trash icon. Checking toggles completion; the trash removes the duty.
- The three filter buttons (All / Energetic / Performed) change which duties are seen.
- The footer exhibits what number of duties will not be performed and allows you to “Clear Accomplished”.
A number of essential distinctions—past the fundamental elements lined earlier—embrace:
- Enhance with
@rx.occasion
to declare occasions inside the state. - Enhance with
@rx.var
to create derived variables within the state. - Use
rx.Part
signatures when constructing reusable UI helpers on your Reflex software.
That’s the primary rationalization and instance of how Reflex works. Strive it your self and construct the net software you want with pure Python.
Conclusion
Reflex is an open-source library that enables us to construct net functions in pure Python with a easy but intuitive code sample. Its simple setup and easy-to-understand code enable customers to maintain the logic and UI in a single place. It’s a helpful library for newcomers {and professional} builders alike who wish to construct an software with Python.
I hope this has helped!
Cornellius Yudha Wijaya is a knowledge science assistant supervisor and knowledge author. Whereas working full-time at Allianz Indonesia, he likes to share Python and knowledge ideas by way of social media and writing media. Cornellius writes on quite a lot of AI and machine studying matters.