Skip to content

Commit cb3e32c

Browse files
Session.query to Session.exec (#174)
1 parent d71a4eb commit cb3e32c

File tree

10 files changed

+96
-64
lines changed

10 files changed

+96
-64
lines changed

basic_crud/basic_crud/basic_crud.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import json
44

55
import httpx
6+
from sqlmodel import select
67

78
import reflex as rx
89

@@ -35,7 +36,7 @@ class State(rx.State):
3536

3637
def load_product(self):
3738
with rx.session() as session:
38-
self.products = session.query(Product).all()
39+
self.products = session.exec(select(Product)).all()
3940
yield State.reload_product
4041

4142
@rx.background
@@ -45,7 +46,7 @@ async def reload_product(self):
4546
if self.db_updated:
4647
async with self:
4748
with rx.session() as session:
48-
self.products = session.query(Product).all()
49+
self.products = session.exec(select(Product)).all()
4950
self._db_updated = False
5051

5152
@rx.var

crm/crm/state/login.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
import reflex as rx
2+
from sqlmodel import select
3+
24
from .models import User
35
from .state import State
46

@@ -11,7 +13,7 @@ class LoginState(State):
1113

1214
def log_in(self):
1315
with rx.session() as sess:
14-
user = sess.query(User).filter_by(email=self.email_field).first()
16+
user = sess.exec(select(User).where(User.email == self.email_field)).first()
1517
if user and user.password == self.password_field:
1618
self.user = user
1719
return rx.redirect("/")
@@ -20,7 +22,7 @@ def log_in(self):
2022

2123
def sign_up(self):
2224
with rx.session() as sess:
23-
user = sess.query(User).filter_by(email=self.email_field).first()
25+
user = sess.exec(select(User).where(User.email == self.email_field)).first()
2426
if user:
2527
return rx.window_alert(
2628
"Looks like you’re already registered! Try logging in instead."

crm/crm/state/state.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
from typing import Optional
22
import reflex as rx
3-
from .models import User, Contact
3+
from .models import User
44

55

66
class State(rx.State):

gpt/gpt/gpt.py

Lines changed: 40 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
from openai import OpenAI
55

66
import reflex as rx
7+
from sqlmodel import select
78

89
from .helpers import navbar
910

@@ -29,6 +30,7 @@ class Question(rx.Model, table=True):
2930

3031
class State(rx.State):
3132
"""The app state."""
33+
3234
show_columns = ["Question", "Answer"]
3335
username: str = ""
3436
password: str = ""
@@ -42,21 +44,22 @@ def questions(self) -> list[Question]:
4244
"""Get the users saved questions and answers from the database."""
4345
with rx.session() as session:
4446
if self.logged_in:
45-
qa = (
46-
session.query(Question)
47+
qa = session.exec(
48+
select(Question)
4749
.where(Question.username == self.username)
4850
.distinct(Question.prompt)
4951
.order_by(Question.timestamp.desc())
5052
.limit(MAX_QUESTIONS)
51-
.all()
52-
)
53+
).all()
5354
return [[q.prompt, q.answer] for q in qa]
5455
else:
5556
return []
5657

5758
def login(self):
5859
with rx.session() as session:
59-
user = session.query(User).where(User.username == self.username).first()
60+
user = session.exec(
61+
select(User).where(User.username == self.username)
62+
).first()
6063
if (user and user.password == self.password) or self.username == "admin":
6164
self.logged_in = True
6265
return rx.redirect("/home")
@@ -76,25 +79,28 @@ def signup(self):
7679
return rx.redirect("/home")
7780

7881
def get_result(self):
79-
if (
80-
rx.session()
81-
.query(Question)
82-
.where(Question.username == self.username)
83-
.where(Question.prompt == self.prompt)
84-
.first()
85-
or rx.session()
86-
.query(Question)
87-
.where(Question.username == self.username)
88-
.where(
89-
Question.timestamp
90-
> datetime.datetime.now() - datetime.timedelta(days=1)
91-
)
92-
.count()
93-
> MAX_QUESTIONS
94-
):
95-
return rx.window_alert(
96-
"You have already asked this question or have asked too many questions in the past 24 hours."
97-
)
82+
with rx.session as session:
83+
if (
84+
session.exec(
85+
select(Question)
86+
.where(Question.username == self.username)
87+
.where(Question.prompt == self.prompt)
88+
).first()
89+
or len(
90+
session.exec(
91+
select(Question)
92+
.where(Question.username == self.username)
93+
.where(
94+
Question.timestamp
95+
> datetime.datetime.now() - datetime.timedelta(days=1)
96+
)
97+
).all()
98+
)
99+
> MAX_QUESTIONS
100+
):
101+
return rx.window_alert(
102+
"You have already asked this question or have asked too many questions in the past 24 hours."
103+
)
98104
try:
99105
response = client.completions.create(
100106
model="text-davinci-002",
@@ -180,7 +186,12 @@ def login():
180186
return rx.center(
181187
rx.vstack(
182188
rx.input(on_blur=State.set_username, placeholder="Username", width="100%"),
183-
rx.input(type_="password", on_blur=State.set_password, placeholder="Password", width="100%"),
189+
rx.input(
190+
type_="password",
191+
on_blur=State.set_password,
192+
placeholder="Password",
193+
width="100%",
194+
),
184195
rx.button("Login", on_click=State.login, width="100%"),
185196
rx.link(rx.button("Sign Up", width="100%"), href="/signup", width="100%"),
186197
),
@@ -201,7 +212,10 @@ def signup():
201212
on_blur=State.set_username, placeholder="Username", width="100%"
202213
),
203214
rx.input(
204-
type_="password", on_blur=State.set_password, placeholder="Password", width="100%"
215+
type_="password",
216+
on_blur=State.set_password,
217+
placeholder="Password",
218+
width="100%",
205219
),
206220
rx.input(
207221
type_="password",

local_auth/local_auth/base_state.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -31,13 +31,14 @@ def authenticated_user(self) -> User:
3131
corresponding to the currently authenticated user.
3232
"""
3333
with rx.session() as session:
34-
result = session.query(User, AuthSession).where(
34+
result = session.exec(
35+
select(User, AuthSession).where(
3536
AuthSession.session_id == self.auth_token,
3637
AuthSession.expiration
3738
>= datetime.datetime.now(datetime.timezone.utc),
3839
User.id == AuthSession.user_id,
39-
).first()
40-
40+
),
41+
).first()
4142
if result:
4243
user, session = result
4344
return user
@@ -55,7 +56,9 @@ def is_authenticated(self) -> bool:
5556
def do_logout(self) -> None:
5657
"""Destroy AuthSessions associated with the auth_token."""
5758
with rx.session() as session:
58-
for auth_session in session.query(AuthSession).filter_by(session_id=self.auth_token).all():
59+
for auth_session in session.exec(
60+
select(AuthSession).where(AuthSession.session_id == self.auth_token)
61+
).all():
5962
session.delete(auth_session)
6063
session.commit()
6164
self.auth_token = self.auth_token

local_auth/local_auth/login.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
"""Login page and authentication logic."""
22
import reflex as rx
3+
from sqlmodel import select
34

45
from .base_state import State
56
from .user import User
@@ -25,7 +26,9 @@ def on_submit(self, form_data) -> rx.event.EventSpec:
2526
username = form_data["username"]
2627
password = form_data["password"]
2728
with rx.session() as session:
28-
user = session.query(User).filter_by(username=username).first()
29+
user = session.exec(
30+
select(User).where(User.username == username)
31+
).one_or_none()
2932
if user is not None and not user.enabled:
3033
self.error_message = "This account is disabled."
3134
return rx.set_value("password", "")

local_auth/local_auth/registration.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
from collections.abc import AsyncGenerator
66

77
import reflex as rx
8+
from sqlmodel import select
89

910
from .base_state import State
1011
from .login import LOGIN_ROUTE, REGISTER_ROUTE
@@ -33,7 +34,9 @@ async def handle_registration(
3334
self.error_message = "Username cannot be empty"
3435
yield rx.set_focus("username")
3536
return
36-
existing_user = session.query(User).filter_by(username=username).first()
37+
existing_user = session.exec(
38+
select(User).where(User.username == username)
39+
).one_or_none()
3740
if existing_user is not None:
3841
self.error_message = (
3942
f"Username {username} is already registered. Try a different name"

sales/sales/sales.py

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from openai import OpenAI
22

33
import reflex as rx
4+
from sqlmodel import select
45

56
from .models import Customer
67

@@ -64,7 +65,9 @@ class State(rx.State):
6465
def add_customer(self):
6566
"""Add a customer to the database."""
6667
with rx.session() as session:
67-
if session.query(Customer).filter_by(email=self.email).first():
68+
if session.exec(
69+
select(Customer).where(Customer.email == self.email)
70+
).first():
6871
return rx.window_alert("User already exists")
6972
session.add(
7073
Customer(
@@ -91,7 +94,10 @@ def onboarding_page(self):
9194
def delete_customer(self, email: str):
9295
"""Delete a customer from the database."""
9396
with rx.session() as session:
94-
session.query(Customer).filter_by(email=email).delete()
97+
customer = session.exec(
98+
select(Customer).where(Customer.email == email)
99+
).first()
100+
session.delete(customer)
95101
session.commit()
96102

97103
generate_email_data: dict = {}
@@ -117,7 +123,7 @@ async def call_openai(self):
117123
# save the data related to email_content
118124
self.email_content_data = response.choices[0].text
119125
# update layout of email_content manually
120-
return rx.set_value("email_content", self.email_content_data)
126+
return rx.set_value("email_content", self.email_content_data)
121127

122128
def generate_email(
123129
self,
@@ -144,7 +150,7 @@ def generate_email(
144150
def get_users(self) -> list[Customer]:
145151
"""Get all users from the database."""
146152
with rx.session() as session:
147-
self.users = session.query(Customer).all()
153+
self.users = session.exec(select(Customer)).all()
148154
return self.users
149155

150156
def open_text_area(self):

twitter/twitter/state/auth.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
"""The authentication state."""
22
import reflex as rx
3+
from sqlmodel import select
34

45
from .base import State, User
56

@@ -16,7 +17,7 @@ def signup(self):
1617
with rx.session() as session:
1718
if self.password != self.confirm_password:
1819
return rx.window_alert("Passwords do not match.")
19-
if session.query(User).filter_by(username=self.username).first():
20+
if session.exec(select(User).where(User.username == self.username)).first():
2021
return rx.window_alert("Username already exists.")
2122
self.user = User(username=self.username, password=self.password)
2223
session.add(self.user)
@@ -27,7 +28,9 @@ def signup(self):
2728
def login(self):
2829
"""Log in a user."""
2930
with rx.session() as session:
30-
user = session.query(User).filter_by(username=self.username).first()
31+
user = session.exec(
32+
select(User).where(User.username == self.username)
33+
).first()
3134
if user and user.password == self.password:
3235
self.user = user
3336
return rx.redirect("/")

twitter/twitter/state/home.py

Lines changed: 18 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
from datetime import datetime
33

44
import reflex as rx
5+
from sqlmodel import select
56

67
from .base import Follows, State, Tweet, User
78

@@ -33,13 +34,11 @@ def get_tweets(self):
3334
"""Get tweets from the database."""
3435
with rx.session() as session:
3536
if self.search:
36-
self.tweets = (
37-
session.query(Tweet)
38-
.filter(Tweet.content.contains(self.search))
39-
.all()[::-1]
40-
)
37+
self.tweets = session.exec(
38+
select(Tweet).where(Tweet.content.contains(self.search))
39+
).all()[::-1]
4140
else:
42-
self.tweets = session.query(Tweet).all()[::-1]
41+
self.tweets = session.exec(select(Tweet)).all()[::-1]
4342

4443
def set_search(self, search):
4544
"""Set the search query."""
@@ -60,23 +59,23 @@ def following(self) -> list[Follows]:
6059
"""Get a list of users the current user is following."""
6160
if self.logged_in:
6261
with rx.session() as session:
63-
return (
64-
session.query(Follows)
65-
.filter(Follows.follower_username == self.user.username)
66-
.all()
67-
)
62+
return session.exec(
63+
select(Follows).where(
64+
Follows.follower_username == self.user.username
65+
)
66+
).all()
6867
return []
6968

7069
@rx.var
7170
def followers(self) -> list[Follows]:
7271
"""Get a list of users following the current user."""
7372
if self.logged_in:
7473
with rx.session() as session:
75-
return (
76-
session.query(Follows)
77-
.where(Follows.followed_username == self.user.username)
78-
.all()
79-
)
74+
return session.exec(
75+
select(Follows).where(
76+
Follows.followed_username == self.user.username
77+
)
78+
).all()
8079
return []
8180

8281
@rx.var
@@ -85,13 +84,11 @@ def search_users(self) -> list[User]:
8584
if self.friend != "":
8685
with rx.session() as session:
8786
current_username = self.user.username if self.user is not None else ""
88-
users = (
89-
session.query(User)
90-
.filter(
87+
users = session.exec(
88+
select(User).where(
9189
User.username.contains(self.friend),
9290
User.username != current_username,
9391
)
94-
.all()
95-
)
92+
).all()
9693
return users
9794
return []

0 commit comments

Comments
 (0)