-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpractice2.py
270 lines (234 loc) · 7.97 KB
/
practice2.py
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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
import stat
from fastapi import Depends, FastAPI,HTTPException,Response
import psycopg2
from pydantic import BaseModel
from typing import Optional
import jwt
from fastapi.security import HTTPBearer,HTTPAuthorizationCredentials
from datetime import datetime,timedelta
app = FastAPI()
# def get_current_user(authorization: HTTPAuthorizationCredentials = Depends(HTTPBearer())):
# token = authorization.credentials
# try:
# payload = jwt.decode(token, "secret", "HS256")
# username: str = payload.get("sub")
# if username is None:
# raise HTTPException(
# status_code=status.HTTP_401_UNAUTHORIZED,
# detail="Could not validate credentials",
# headers={"WWW-Authenticate": "Bearer"},
# )
# return username
# except jwt.ExpiredSignatureError:
# raise HTTPException(
# status_code=stat.HTTP_401_UNAUTHORIZED,
# detail="Token has expired",
# headers={"WWW-Authenticate": "Bearer"},
# )
# except jwt.PyJWTError:
# raise HTTPException(
# status_code=stat.HTTP_401_UNAUTHORIZED,
# detail="Could not validate credentials",
# headers={"WWW-Authenticate": "Bearer"},
# )
def generate_access_token(data :dict):
to_encode = data.copy()
expire = datetime.utcnow() + timedelta(minutes=30)
to_encode.update({"exp" : expire})
encode_jwt = jwt.encode(to_encode,"secret",algorithm="HS256")
return encode_jwt
# Data base connection
def connect_db():
conn = psycopg2.connect(
host = "localhost",
dbname = 'postgres',
user = "postgres",
password = "ganesh",
port = 5432
)
return conn
class PostUpdate(BaseModel):
title: Optional[str] = None
author: Optional[str] = None
content: Optional[str] = None
class Post(BaseModel):
title : str
author : str
content : str
@app.post("/create-post")
def create_post(post: Post):
conn = connect_db()
try:
with conn.cursor() as cur:
print("Data base connected")
cur.execute(
"""
CREATE TABLE IF NOT EXISTS post(
id SERIAL PRIMARY KEY,
title VARCHAR(255),
author VARCHAR(255),
content TEXT
)
"""
)
cur.execute(
"""
INSERT INTO post(title,author,content)
VALUES (%s,%s,%s)
RETURNING id
""",
(post.title,post.author,post.content)
)
post_id = cur.fetchone()[0]
conn.commit()
return {**post.dict(),"id":post_id}
except Exception as e:
conn.rollback()
raise HTTPException(status_code=404,detail="Error in create post route")
finally:
conn.close()
@app.get("/allposts")
def allposts():
conn = connect_db()
try:
with conn.cursor() as cur:
cur.execute(
"""
SELECT id,title,author,content from post
"""
)
rows = cur.fetchall()
if not rows:
raise HTTPException(status_code=404,detail="no posts")
posts = [
{"id": row[0], "title": row[1], "author": row[2], "content": row[3]}
for row in rows
]
return posts
except Exception as e:
raise HTTPException(status_code=404,detail="Error in all posts route")
finally:
conn.close()
@app.put("/update/{id}")
def update(updated_post: Post, id: int):
conn = connect_db()
try:
with conn.cursor() as cur:
# Print to debug
print(f"Updating post with ID: {id}")
print(f"New data: {updated_post.dict()}")
# Update the post
cur.execute(
"""
UPDATE post
SET title = %s, author = %s, content = %s
WHERE id = %s
RETURNING id, title, author, content
""",
(updated_post.title, updated_post.author, updated_post.content, id)
)
updated_row = cur.fetchone()
# Check if the post was updated
if updated_row is None:
raise HTTPException(status_code=404, detail="Post not found")
conn.commit()
return {
"id": updated_row[0],
"title": updated_row[1],
"author": updated_row[2],
"content": updated_row[3]
}
except Exception as e:
# Log the exception for debugging
print(f"Error occurred: {e}")
conn.rollback()
raise HTTPException(status_code=500, detail="Error in update route")
finally:
conn.close()
@app.delete("/delete/{id}")
def delete(id :int):
conn = connect_db()
try:
with conn.cursor() as cur:
cur.execute(
"""
DELETE from post
WHERE id = %s
RETURNING id
""",
(id,)
)
deleted_row = cur.fetchone()
if deleted_row is None:
raise HTTPException(status_code=404,detail="Not found")
conn.commit()
return {"message" : f"Test with {id} deleted"}
except Exception as e:
conn.rollback()
raise HTTPException(status_code=404,detail="Error in delete route")
finally:
conn.close()
class User(BaseModel):
username:str
email:str
password:str
@app.post("/create-user")
def create_user(user:User,response:Response):
conn = connect_db()
try:
with conn.cursor() as cur:
print("Data base connected")
cur.execute(
"""
CREATE TABLE IF NOT EXISTS users(
id SERIAL PRIMARY KEY,
username VARCHAR(255) UNIQUE,
email VARCHAR(255) UNIQUE,
password VARCHAR(255)
)
"""
)
cur.execute(
"""
INSERT INTO users(username,email,password)
VALUES (%s,%s,%s)
RETURNING id
""",
(user.username,user.email,user.password)
)
user_id = cur.fetchone()[0]
conn.commit()
#Generate token
token = generate_access_token({"sub" : user.username})
response.set_cookie(key="access_token", value=f"Bearer {token}", httponly=True)
return {"id": user_id, "username": user.username, "email": user.email,}
except Exception as e:
conn.rollback()
raise HTTPException(status_code=404, detail="Error in create user route")
finally:
conn.close()
@app.post("/login")
def login_user(email: str, password: str, response: Response):
conn = connect_db()
try:
with conn.cursor() as cur:
cur.execute(
"SELECT id, username, password FROM users WHERE email = %s",
(email,) # Fixed the missing comma
)
user = cur.fetchone()
if not user:
raise HTTPException(status_code=404, detail="Invalid email or password")
user_id, db_username, db_password = user
# Verify the password using bcrypt
if not (password, db_password):
raise HTTPException(status_code=404, detail="Invalid password")
# Generate JWT token
token = generate_access_token({"sub": db_username})
response.set_cookie(key="access_token", value=f"Bearer {token}", httponly=True)
return {"message": "Login successful"}
except Exception as e:
conn.rollback()
raise HTTPException(status_code=404,detail="Error in login route")
finally:
conn.close()