Skip to content

Commit 4340505

Browse files
authored
make demos background events (#1547)
1 parent b944972 commit 4340505

File tree

3 files changed

+53
-35
lines changed

3 files changed

+53
-35
lines changed

pcweb/pages/framework/demos/chatbot/chatbot.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ class TutorialState(rx.State):
1515
)
1616
]
1717

18-
@rx.event
18+
@rx.event(background=True)
1919
async def submit(self, form_data: dict):
2020
question = form_data["question"]
2121
# Our chatbot has some brains now!
@@ -31,17 +31,19 @@ async def submit(self, form_data: dict):
3131
# Add to the answer as the chatbot responds.
3232
answer = ""
3333
# self.chat_history = []
34-
self.chat_history.append((question, answer))
35-
yield
34+
async with self:
35+
self.chat_history.append((question, answer))
36+
yield
3637

3738
async for item in session:
3839
if hasattr(item.choices[0].delta, "content"):
3940
if item.choices[0].delta.content is None:
4041
# presence of 'None' indicates the end of the response
4142
break
4243
answer += item.choices[0].delta.content
43-
self.chat_history[-1] = (self.chat_history[-1][0], answer)
44-
yield
44+
async with self:
45+
self.chat_history[-1] = (self.chat_history[-1][0], answer)
46+
yield
4547

4648
@rx.event
4749
def clear_chat(self):

pcweb/pages/framework/demos/image_gen/image_gen.py

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -10,22 +10,30 @@ class ImageGenState(rx.State):
1010
image_url: str = ""
1111
processing: bool = False
1212

13-
@rx.event
14-
def get_image(self, form_data):
13+
@rx.event(background=True)
14+
async def get_image(self, form_data):
1515
"""Get the image from the prompt."""
1616
prompt = form_data["prompt"]
1717
if prompt == "":
1818
return
19-
self.processing = True
20-
yield
19+
async with self:
20+
self.processing = True
21+
yield
2122
input = {"prompt": prompt}
2223

23-
output = replicate.run(
24-
"black-forest-labs/flux-schnell",
25-
input=input,
26-
)
27-
self.image_url = str(output[0])
28-
self.processing = False
24+
try:
25+
output = await replicate.async_run(
26+
"black-forest-labs/flux-schnell",
27+
input=input,
28+
)
29+
async with self:
30+
self.image_url = str(output[0])
31+
except Exception:
32+
async with self:
33+
self.image_url = ""
34+
finally:
35+
async with self:
36+
self.processing = False
2937

3038

3139
def image_gen() -> rx.Component:

pcweb/signup.py

Lines changed: 28 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -28,20 +28,23 @@ class IndexState(rx.State):
2828
# Whether to show the confetti.
2929
show_confetti: bool = False
3030

31-
def send_contact_to_webhook(
31+
@rx.event(background=True)
32+
async def send_contact_to_webhook(
3233
self,
3334
email: str,
3435
) -> None:
35-
with contextlib.suppress(httpx.HTTPError) and httpx.Client() as client:
36-
response = client.post(
37-
REFLEX_DEV_WEB_NEWSLETTER_FORM_WEBHOOK_URL,
38-
json={
39-
"email": email,
40-
},
41-
)
36+
with contextlib.suppress(httpx.HTTPError):
37+
async with httpx.AsyncClient() as client:
38+
response = await client.post(
39+
REFLEX_DEV_WEB_NEWSLETTER_FORM_WEBHOOK_URL,
40+
json={
41+
"email": email,
42+
},
43+
)
4244
response.raise_for_status()
4345

44-
def add_contact_to_loops(
46+
@rx.event(background=True)
47+
async def add_contact_to_loops(
4548
self,
4649
email: str,
4750
):
@@ -56,8 +59,8 @@ def add_contact_to_loops(
5659
"Authorization": f"Bearer {loops_api_key}",
5760
}
5861
try:
59-
with httpx.Client() as client:
60-
response = client.post(
62+
async with httpx.AsyncClient() as client:
63+
response = await client.post(
6164
url,
6265
headers=headers,
6366
json={
@@ -73,8 +76,8 @@ def add_contact_to_loops(
7376
def signup_for_another_user(self):
7477
self.signed_up = False
7578

76-
@rx.event
77-
def signup(
79+
@rx.event(background=True)
80+
async def signup(
7881
self,
7982
form_data: dict[str, Any],
8083
):
@@ -90,17 +93,22 @@ def signup(
9093

9194
except EmailNotValidError as e:
9295
# Alert the error message.
93-
return rx.toast.warning(
96+
yield rx.toast.warning(
9497
str(e),
9598
style={
9699
"border": "1px solid #3C3646",
97100
"background": "linear-gradient(218deg, #1D1B23 -35.66%, #131217 100.84%)",
98101
},
99102
)
100-
self.send_contact_to_webhook(email)
101-
self.add_contact_to_loops(email)
102-
self.signed_up = True
103-
return [
104-
rx.call_script(f"try {{ ko.identify('{email}'); }} catch(e) {{ console.warn('Koala identify failed:', e); }}"),
105-
rx.toast.success("Thanks for signing up to the Newsletter!")
103+
return
104+
yield IndexState.send_contact_to_webhook(email)
105+
yield IndexState.add_contact_to_loops(email)
106+
async with self:
107+
self.signed_up = True
108+
yield
109+
yield [
110+
rx.call_script(
111+
f"try {{ ko.identify('{email}'); }} catch(e) {{ console.warn('Koala identify failed:', e); }}"
112+
),
113+
rx.toast.success("Thanks for signing up to the Newsletter!"),
106114
]

0 commit comments

Comments
 (0)