Skip to content

Commit

Permalink
Merge pull request #156 from reflex-dev/lendemor/add_basic_crud_example
Browse files Browse the repository at this point in the history
Lendemor/add basic crud example
  • Loading branch information
Lendemor authored Oct 22, 2023
2 parents 997ce25 + 750b2eb commit 65858ca
Show file tree
Hide file tree
Showing 9 changed files with 329 additions and 0 deletions.
4 changes: 4 additions & 0 deletions basic_crud/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
*.db
*.py[cod]
.web
__pycache__/
Binary file added basic_crud/assets/favicon.ico
Binary file not shown.
1 change: 1 addition & 0 deletions basic_crud/basic_crud/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""Basic CRUD example main package."""
80 changes: 80 additions & 0 deletions basic_crud/basic_crud/api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
"""API methods to handle products."""
import json
from datetime import datetime, timezone

from fastapi import APIRouter, Request
from fastapi.exceptions import HTTPException

import reflex as rx

from .model import Product


async def get_product(spec_id: int):
"""Get the product associated with spec_id."""
with rx.session() as session:
spec = session.query(Product).get(spec_id)
return spec if spec else HTTPException(status_code=404)


async def list_product(req: Request):
"""Get a list of all the products."""
with rx.session() as session:
specs = session.query(Product).all()
return specs


async def add_product(req: Request):
"""Add a new product."""
data = json.loads(await req.body())
with rx.session() as session:
now = datetime.now(timezone.utc)
code = data["code"]
if not code:
return HTTPException(status_code=402, detail="Invalid `code`")
session.add(
Product(
code=code,
created=now,
updated=now,
label=data["label"],
image="/favicon.ico",
quantity=data["quantity"],
category=data["category"],
seller=data["seller"],
sender=data["sender"],
)
)
session.commit()
return "OK"


async def update_product(spec_id: int, req: Request):
"""Update the product associated with spec_id."""
data = json.loads(await req.body())
with rx.session() as session:
spec = session.query(Product).get(spec_id)
for k, v in data.items():
setattr(spec, k, v)
spec.updated = datetime.now(timezone.utc)
# spec.__setattr__(k, v)
# spec.__setattr__("updated", datetime.now())
session.add(spec)
session.commit()


async def delete_product(spec_id):
"""Delete the product associated with spec_id."""
with rx.session() as session:
spec = session.query(Product).get(spec_id)
session.delete(spec)
session.commit()


product_router = APIRouter(prefix="/products", tags=["products"])

product_router.add_api_route("", add_product, methods=["POST"])
product_router.add_api_route("", list_product, methods=["GET"])
product_router.add_api_route("/{spec_id}", get_product, methods=["GET"])
product_router.add_api_route("/{spec_id}", update_product, methods=["PUT"])
product_router.add_api_route("/{spec_id}", delete_product, methods=["DELETE"])
199 changes: 199 additions & 0 deletions basic_crud/basic_crud/basic_crud.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
"""Welcome to Reflex! This file outlines the steps to create a basic app."""
import asyncio
import json

import httpx

import reflex as rx

from .api import product_router
from .model import Product

DEFAULT_BODY = """{
"code":"",
"label":"",
"image":"/favicon.ico",
"quantity":0,
"category":"",
"seller":"",
"sender":""
}"""

URL_OPTIONS = {
"GET": "products",
"POST": "products",
"PUT": "products/{pr_id}",
"DELETE": "products/{pr_id}",
}


class State(rx.State):
"""The app state."""

products: list[Product]
_db_updated: bool = False

def load_product(self):
with rx.session() as session:
self.products = session.query(Product).all()
yield State.reload_product

@rx.background
async def reload_product(self):
while True:
await asyncio.sleep(2)
if self.db_updated:
async with self:
with rx.session() as session:
self.products = session.query(Product).all()
self._db_updated = False

@rx.var
def db_updated(self):
return self._db_updated

@rx.var
def total(self):
return len(self.products)


class QueryState(State):
body: str = DEFAULT_BODY
response_code: str = ""
response: str = ""
method: str = "GET"
url_query: str = URL_OPTIONS["GET"]
query_options = list(URL_OPTIONS.keys())

def update_method(self, value):
if self.url_query == "":
self.url_query = URL_OPTIONS[value]
self.method = value

@rx.var
def need_body(self):
return False

@rx.var
def f_response(self):
return f"""```json\n{self.response}\n```"""

def clear_query(self):
self.url_query = URL_OPTIONS["GET"]
self.method = "GET"
self.body = DEFAULT_BODY

async def send_query(self):
url = f"http://localhost:8000/{self.url_query}"
async with httpx.AsyncClient() as client:
match self.method:
case "GET":
res = await client.get(url)
case "POST":
res = await client.post(url, data=self.body)
case "PUT":
res = await client.put(url, data=self.body)
case "DELETE":
res = await client.delete(url)
case _:
res = None
self.response_code = res.status_code
if self.response_code == 200:
self.response = json.dumps(res.json(), indent=2)
self._db_updated = True
else:
self.response = res.content.decode()


def data_display():
return rx.vstack(
rx.heading(State.total, " products found"),
rx.foreach(State.products, render_product),
rx.spacer(),
width="30vw",
height="100%",
)


def render_product(product: Product):
return rx.hstack(
rx.image(src=product.image, height="100%", width="3vw"),
rx.text(f"({product.code}) {product.label}", width="10vw"),
rx.vstack(
rx.text("Stock:", product.quantity),
rx.text("Category:", product.category),
spacing="0",
width="7vw",
),
rx.vstack(
rx.text("Seller:", product.seller),
rx.text("Sender:", product.sender),
spacing="0",
width="7vw",
),
rx.spacer(),
border="solid black 1px",
spcaing="5",
width="100%",
)


def query_form():
return rx.vstack(
rx.hstack(
rx.text("Query:"),
rx.select(
["GET", "POST", "PUT", "DELETE"],
on_change=QueryState.update_method,
),
rx.input(
value=QueryState.url_query,
on_change=QueryState.set_url_query,
width="30vw",
),
),
rx.text("Body:"),
rx.text_area(
value=QueryState.body, height="30vh", on_change=QueryState.set_body
),
rx.hstack(
rx.button("Clear", on_click=QueryState.clear_query),
rx.button("Send", on_click=QueryState.send_query),
),
rx.divider(orientation="horizontal", border="solid black 1px", width="100%"),
rx.hstack(
rx.text("Status: ", QueryState.response_code), rx.spacer(), width="100%"
),
rx.container(
rx.markdown(
QueryState.f_response,
language="json",
height="30vh",
)
),
# width="50vw",
width="100%",
)


def index() -> rx.Component:
return rx.hstack(
rx.spacer(),
data_display(),
rx.spacer(),
rx.divider(orientation="vertical", border="solid black 1px"),
query_form(),
rx.spacer(),
height="100vh",
width="100vw",
spacing="0",
)


# Add state and page to the app.
app = rx.App()
app.add_page(index, on_load=State.load_product)

app.api.include_router(product_router)

app.compile()
35 changes: 35 additions & 0 deletions basic_crud/basic_crud/model.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
"""Models used by the app."""
from datetime import datetime, timezone

from sqlmodel import Column, DateTime, Field, func

import reflex as rx


class Product(rx.Model, table=True):
"""Product model."""

code: str = Field(unique=True)
created: datetime = Field(
datetime.now(timezone.utc),
sa_column=Column(DateTime(timezone=True), server_default=func.now()),
nullable=False,
)
updated: datetime = Field(
datetime.now(timezone.utc),
sa_column=Column(DateTime(timezone=True), server_default=func.now()),
nullable=False,
)
label: str
image: str
quantity: int
category: str
seller: str
sender: str

def dict(self, *args, **kwargs) -> dict:
"""Serialize method."""
d = super().dict(*args, **kwargs)
d["created"] = self.created.replace(microsecond=0).isoformat()
d["updated"] = self.updated.replace(microsecond=0).isoformat()
return d
4 changes: 4 additions & 0 deletions basic_crud/basic_crud/test.http
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
GET http://localhost:8000/products/1



1 change: 1 addition & 0 deletions basic_crud/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
reflex>=0.2.9
5 changes: 5 additions & 0 deletions basic_crud/rxconfig.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import reflex as rx

config = rx.Config(
app_name="basic_crud",
)

0 comments on commit 65858ca

Please sign in to comment.