-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
113 lines (93 loc) · 3.71 KB
/
main.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
import imp
import time
from typing import Optional
from fastapi import FastAPI, Response, status, HTTPException, Depends
from fastapi.params import Body
from pydantic import BaseModel
from random import randrange
import psycopg2
from psycopg2.extras import RealDictCursor
from sqlalchemy.orm import Session
from . import models
from .database import SessionLocal, engine
models.Base.metadata.create_all(bind=engine)
from starlette.status import HTTP_201_CREATED, HTTP_204_NO_CONTENT, HTTP_404_NOT_FOUND
app = FastAPI()
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
class Post(BaseModel):
title: str
content: str
published: bool = True
#rating: Optional[int] = None
while 1:
try:
conn = psycopg2.connect(host='localhost', database='fastapi', user='postgres', password='112121', cursor_factory=RealDictCursor)
cursor = conn.cursor()
print("*********************************")
print("Database Connection Is Succesfull")
print("*********************************")
break
except Exception as error:
print('connection is failed')
print('Error: ', error)
time.sleep(5)
my_posts = [{"title": "title of post 1", "content": "content of post 1", "id": 1},{"title": "my favorite meals", "content": "I like icecream", "id": 2}, {"title": "Do you like my photos?", "content": "yes very nice", "id": 3}]
def find_post(id):
for p in my_posts:
if p["id"] == id:
return p
def find_index_post(id):
for i, p in enumerate(my_posts):
if p['id'] == id:
return i
@app.get("/")
async def root():
return {"message": "HELLO WORLD! I'm still here and in windows"}
@app.get("/sqlalchemy")
def test_posts(db:Session = Depends(get_db)):
return {'status': 'success'}
@app.get("/posts")
def get_posts():
cursor.execute(""" SELECT * FROM posts""")
posts = cursor.fetchall()
#print(posts)
return{"data": posts}
@app.post("/posts", status_code=HTTP_201_CREATED)
def create_posts(post: Post):
cursor.execute("""INSERT INTO posts (title, content, published) VALUES (%s, %s, %s) RETURNING * """, (post.title, post.content, post.published))
new_post = cursor.fetchone()
conn.commit()
return{"data": new_post}
#return{"new_message": f"title: {PayLoad['title']} content:{PayLoad['content']}"}
@app.get("/posts/{id}")
def get_post(id: int, response: Response):
cursor.execute("""SELECT * FROM posts WHERE id = %s """, (str(id),))
post = cursor.fetchone()
if not post:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"post with id: {id} doesn't exist")
#response.status_code = status.HTTP_404_NOT_FOUND
#return{"error message": f"post with id: {id} doesn't exist"}
print(post)
return{"post_details": post}
@app.delete("/posts/{id}", status_code=HTTP_204_NO_CONTENT)
def delete_post(id: int):
cursor.execute("""DELETE FROM posts WHERE id = %s RETURNING *""", (str(id),))
deleted_post = cursor.fetchone()
conn.commit()
if deleted_post == None:
raise HTTPException(status_code=HTTP_404_NOT_FOUND, detail=f"post with id: {id} doesn't exist")
#return{"message": f"post {id} was deleted"}
return Response(status_code=HTTP_204_NO_CONTENT)
@app.put("/posts/{id}")
def update_post(id: int, post: Post):
cursor.execute("""UPDATE posts SET title = %s, content = %s, published = %s WHERE id = %s RETURNING *""", (post.title, post.content, post.published, str(id)))
updated_post = cursor.fetchone()
conn.commit()
if updated_post == None:
raise HTTPException(status_code=HTTP_404_NOT_FOUND, detail=f"post with id: {id} doesn't exist")
return{"data": updated_post}