-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdao.py
More file actions
184 lines (157 loc) · 5.62 KB
/
dao.py
File metadata and controls
184 lines (157 loc) · 5.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
from asyncpg import UniqueViolationError
from sqlalchemy import insert, select, update, delete
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.exc import IntegrityError
from fastapi import HTTPException, status
from sqlalchemy.orm import joinedload
from models import User, UserRefreshToken, Product, OrderProduct
from database import async_session_maker
from datetime import datetime
async def create_user(
name: str,
email: str,
hashed_password: str,
session: AsyncSession,
) -> User:
user = User(
email=email,
name=name,
hashed_password=hashed_password,
)
session.add(user)
try:
await session.commit()
await session.refresh(user)
return user
except IntegrityError:
await session.rollback()
raise HTTPException(detail=f'User with email {email} probably already exists',
status_code=status.HTTP_403_FORBIDDEN)
async def get_user_by_email(email: str, session: AsyncSession) -> User | None:
query = select(User).filter_by(email=email)
result = await session.execute(query)
return result.scalar_one_or_none()
async def get_user_by_uuid(user_uuid: str, session: AsyncSession) -> User | None:
query = select(User).filter_by(user_uuid=user_uuid)
result = await session.execute(query)
return result.scalar_one_or_none()
async def activate_user_account(user_uuid: str, session: AsyncSession) -> User | None:
user = await get_user_by_uuid(user_uuid, session)
if not user:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Data for account activation is not correct"
)
if user.verified_at:
return user
user.verified_at = True
session.add(user)
await session.commit()
await session.refresh(user)
return user
# async def fetch_users(skip: int = 0, limit: int = 10) -> list[User]:
# async with async_session_maker() as session:
# query = select(User).offset(skip).limit(limit)
# result = await session.execute(query)
# print(query)
# # print(type(result.scalars().all()))
# print(result.scalars().all()[0].login)
# # print(result.scalars().all()[0].__dict__)
# return result.scalars().all()
#
#
# async def get_user_by_id(user_id: int) -> User | None:
# async with async_session_maker() as session:
# query = select(User).filter_by(id=user_id)
# result = await session.execute(query)
# # print(result.scalar_one_or_none())
# return result.scalar_one_or_none()
#
#
# async def update_user(user_id: int, values: dict):
# if not values:
# return
# async with async_session_maker() as session:
# query = update(User).where(User.id == user_id).values(**values)
# result = await session.execute(query)
# await session.commit()
# # print(tuple(result))
# print(query)
#
#
# async def delete_user(user_id: int):
# async with async_session_maker() as session:
# query = delete(User).where(User.id == user_id)
# await session.execute(query)
# await session.commit()
# print(query)
async def create_refresh_token(
user_id: int,
refresh_key: str,
expires_at: datetime,
session: AsyncSession,
) -> None:
token = UserRefreshToken(
user_id=user_id,
refresh_key=refresh_key,
expires_at=expires_at,
)
session.add(token)
await session.commit()
async def get_refresh_token_by_key(key: str, session: AsyncSession) -> UserRefreshToken | None:
user_token = await session.execute(
select(UserRefreshToken)
.options(joinedload(UserRefreshToken.user))
.where(
UserRefreshToken.refresh_key == key,
UserRefreshToken.expires_at > datetime.utcnow(),
)
)
return user_token.scalar_one_or_none()
async def add_product(
title: str,
price: float,
session: AsyncSession,
image_url: str = '',
image_file: str = '',
) -> Product | None:
product = Product(
title=title,
price=price,
image_url=image_url,
image_file=image_file
)
session.add(product)
try:
await session.commit()
await session.refresh(product)
return product
except IntegrityError:
await session.rollback()
return None
async def fetch_products(session: AsyncSession, offset=0, limit=12, q='') -> list:
if q:
query = select(Product).filter(Product.title.ilike(f'%{q}%')).offset(offset).limit(limit)
else:
query = select(Product).offset(offset).limit(limit)
result = await session.execute(query)
return result.scalars().all() or []
async def get_product(session: AsyncSession, product_id: int) -> Product | None:
query = select(Product).filter(Product.id==product_id)
result = await session.execute(query)
return result.scalar_one_or_none()
async def get_or_create(session: AsyncSession, model, only_get=False, **kwargs):
query = select(model).filter_by(**kwargs)
instance = await session.execute(query)
instance = instance.scalar_one_or_none()
if instance or only_get:
return instance
instance = model(**kwargs)
session.add(instance)
await session.commit()
await session.refresh(instance)
return instance
async def fetch_order_products(session: AsyncSession, order_id: int) -> list:
query = select(OrderProduct).filter(OrderProduct.order_id==order_id).options(joinedload(OrderProduct.product))
result = await session.execute(query)
return result.scalars().all() or []