How to Build an Advanced Multi-Page Reflex Web Application with Real-Time Database, Dynamic State Management, and Reactive UI
In this tutorial, we construct an superior Reflex net software completely in Python that runs seamlessly inside Colab. We design the app to display how Reflex permits full-stack growth with no JavaScript, simply reactive Python code. We create an entire notes-management dashboard that includes two pages, real-time database interactions, filtering, sorting, analytics, and person personalization. We progressively assemble the venture in 5 clear snippets, protecting setup, configuration, mannequin and state administration, person interface design, and remaining execution, which supplies us with a hands-on understanding of Reflex’s declarative structure and reactivity system. Check out the FULL CODES here.
import os, subprocess, sys, pathlib
APP = "reflex_colab_advanced"
os.makedirs(APP, exist_ok=True)
os.chdir(APP)
subprocess.run([sys.executable, "-m", "pip", "install", "-q", "reflex==0.5.9"])
We arrange our working atmosphere and put in Reflex inside Colab. We create a brand new venture listing and make sure the framework is prepared to be used. We put together the bottom atmosphere so our app can run easily later with out dependency points. Check out the FULL CODES here.
rxconfig = """
import reflex as rx
class Config(rx.Config):
app_name = "reflex_colab_advanced"
db_url = "sqlite:///reflex.db"
config = Config()
"""
pathlib.Path("rxconfig.py").write_text(rxconfig)
We outline the configuration file that specifies the app identify and database connection. We join Reflex to a neighborhood SQLite database to retailer our notes. We preserve this configuration as minimal as potential whereas nonetheless being important for managing persistent knowledge. Check out the FULL CODES here.
app_py = """
import reflex as rx
class Note(rx.Model, desk=True):
content material: str
tag: str = "basic"
finished: bool = False
class State(rx.State):
person: str = ""
search: str = ""
tag_filter: str = "all"
sort_desc: bool = True
new_content: str = ""
new_tag: str = "basic"
toast_msg: str = ""
def set_user(self, v: str): self.person = v
def set_search(self, v: str): self.search = v
def set_tag_filter(self, v: str): self.tag_filter = v
def set_new_content(self, v: str): self.new_content = v
def set_new_tag(self, v: str): self.new_tag = v
def toggle_sort(self): self.sort_desc = not self.sort_desc
async def add_note(self):
if self.new_content.strip():
await Note.create(content material=self.new_content.strip(), tag=self.new_tag.strip() or "basic")
self.new_content = ""; self.toast_msg = "Note added"
async def toggle_done(self, note_id: int):
observe = await Note.get(id=note_id)
if observe:
await observe.replace(finished=not observe.finished)
async def delete_note(self, note_id: int):
await Note.delete(id=note_id)
self.toast_msg = "Deleted"
async def clear_done(self):
objects = await Note.all()
for n in objects:
if n.finished:
await Note.delete(id=n.id)
self.toast_msg = "Cleared finished notes"
async def notes_filtered(self):
objects = await Note.all()
q = self.search.decrease()
if q:
objects = [n for n in items if q in n.content.lower() or q in n.tag.lower()]
if self.tag_filter != "all":
objects = [n for n in items if n.tag == self.tag_filter]
objects.kind(key=lambda n: n.id, reverse=self.sort_desc)
return objects
async def stats(self):
objects = await Note.all()
whole = len(objects)
finished = len([n for n in items if n.done])
tags = {}
for n in objects:
tags[n.tag] = tags.get(n.tag, 0) + 1
top_tags = sorted(tags.objects(), key=lambda x: x[1], reverse=True)[:5]
return {"whole": whole, "finished": finished, "pending": whole - finished, "tags": top_tags}
"""
We outline our knowledge mannequin Note and the reactive State class that controls person enter, filtering, and database operations. We handle asynchronous actions, reminiscent of including, deleting, and updating notes. We additionally embrace logic for computing statistics dynamically from saved knowledge. Check out the FULL CODES here.
app_py += """
def sidebar():
return rx.vstack(
rx.heading("RC Advanced", dimension="6"),
rx.hyperlink("Dashboard", href="/"),
rx.hyperlink("Notes Board", href="/board"),
rx.textual content("User"),
rx.enter(placeholder="your identify", worth=State.person, on_change=State.set_user),
spacing="3", width="15rem", padding="1rem", border_right="1px strong #eee"
)
async def stats_cards():
s = await State.stats()
return rx.hstack(
rx.field(rx.textual content("Total"), rx.heading(str(s["total"]), dimension="5"), padding="1rem", border="1px strong #eee", border_radius="0.5rem"),
rx.field(rx.textual content("Done"), rx.heading(str(s["done"]), dimension="5"), padding="1rem", border="1px strong #eee", border_radius="0.5rem"),
rx.field(rx.textual content("Pending"), rx.heading(str(s["pending"]), dimension="5"), padding="1rem", border="1px strong #eee", border_radius="0.5rem"),
spacing="4"
)
def tag_pill(tag: str, depend: int = 0):
return rx.badge(
f"{tag} ({depend})" if depend else tag,
on_click=State.set_tag_filter(tag),
cursor="pointer",
color_scheme="blue" if tag == State.tag_filter else "grey"
)
async def tags_bar():
s = await State.stats()
tags = [("all", s["total"])] + s["tags"]
return rx.hstack(*[tag_pill(t[0], t[1]) for t in tags], spacing="2", wrap="wrap")
def note_row(observe: Note):
return rx.hstack(
rx.hstack(
rx.checkbox(is_checked=observe.finished, on_change=State.toggle_done(observe.id)),
rx.textual content(observe.content material, text_decoration="line-through" if observe.finished else "none"),
),
rx.badge(observe.tag, color_scheme="inexperienced"),
rx.button("
", on_click=State.delete_note(observe.id), color_scheme="purple", dimension="1"),
justify="between", width="100%"
)
async def notes_list():
objects = await State.notes_filtered()
return rx.vstack(*[note_row(n) for n in items], spacing="2", width="100%")
"""
We design modular UI parts, together with the sidebar, tag filters, and particular person observe rows. We use Reflex components like vstack, hstack, and suspense to construct responsive layouts. We make sure that every UI factor straight displays state adjustments in real-time. Check out the FULL CODES here.
app_py += """
def dashboard_page():
return rx.hstack(
sidebar(),
rx.field(
rx.heading("Dashboard", dimension="8"),
rx.cond(State.person != "", rx.textual content(f"Hi {State.person}, right here is your exercise")),
rx.vstack(
rx.suspense(stats_cards, fallback=rx.textual content("Loading stats...")),
rx.suspense(tags_bar, fallback=rx.textual content("Loading tags...")),
spacing="4"
),
padding="2rem", width="100%"
),
width="100%"
)
def board_page():
return rx.hstack(
sidebar(),
rx.field(
rx.heading("Notes Board", dimension="8"),
rx.hstack(
rx.enter(placeholder="search...", worth=State.search, on_change=State.set_search, width="50%"),
rx.button("Toggle kind", on_click=State.toggle_sort),
rx.button("Clear finished", on_click=State.clear_done, color_scheme="purple"),
spacing="2"
),
rx.hstack(
rx.enter(placeholder="observe content material", worth=State.new_content, on_change=State.set_new_content, width="60%"),
rx.enter(placeholder="tag", worth=State.new_tag, on_change=State.set_new_tag, width="20%"),
rx.button("Add", on_click=State.add_note),
spacing="2"
),
rx.cond(State.toast_msg != "", rx.callout(State.toast_msg, icon="information")),
rx.suspense(notes_list, fallback=rx.textual content("Loading notes...")),
padding="2rem", width="100%"
),
width="100%"
)
app = rx.App()
app.add_page(dashboard_page, route="/", title="RC Dashboard")
app.add_page(board_page, route="/board", title="Notes Board")
app.compile()
"""
pathlib.Path("app.py").write_text(app_py)
subprocess.run(["reflex", "run", "--env", "prod", "--backend-only"], examine=False)
Finally, we assemble the dashboard and board pages and compile your entire Reflex app. We add navigation, enter fields, buttons, and reside statistics to create a completely interactive interface. We conclude by operating the backend server, bringing our superior Reflex app to life.
In conclusion, we developed and ran a full-featured Reflex software that integrates stateful logic, dynamic parts, and a persistent SQLite database, all from inside Python. We witness how simply we are able to outline each frontend and backend conduct utilizing a unified reactive framework. Through this step-by-step course of, we acquire sensible perception into managing asynchronous state updates, composing UI components declaratively, and extending the app with multi-page navigation and analytics.
Check out the FULL CODES here. Feel free to try our GitHub Page for Tutorials, Codes and Notebooks. Also, be at liberty to observe us on Twitter and don’t neglect to be part of our 100k+ ML SubReddit and Subscribe to our Newsletter. Wait! are you on telegram? now you can join us on telegram as well.
The publish How to Build an Advanced Multi-Page Reflex Web Application with Real-Time Database, Dynamic State Management, and Reactive UI appeared first on MarkTechPost.
