-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
executable file
·101 lines (82 loc) · 2.7 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
#!/usr/bin/python3
"""
Flask RestAPI to fetch persons details
"""
from flask import Flask, request, jsonify
from dotenv import load_dotenv
import os
import psycopg2
load_dotenv()
app = Flask(__name__)
database_url = os.getenv("DATABASE_URL")
conn = psycopg2.connect(database_url)
# create postgress table
CREATE_PERSONS_TABLE = "CREATE TABLE IF NOT EXISTS persons\
(id SERIAL PRIMARY KEY, name TEXT);"
# connect and execute creation of table
with conn:
with conn.cursor() as cursor:
cursor.execute(CREATE_PERSONS_TABLE)
# query to insert new person into table
INSERT_PERSON = "INSERT INTO persons (name) VALUES (%s) RETURNING id;"
@app.route("/api", methods=['POST'])
def create():
"""
creates and adds new person based on provided details
"""
data = request.get_json()
name = data['name']
with conn:
with conn.cursor() as cursor:
cursor.execute(INSERT_PERSON, (name,))
person_id = cursor.fetchone()[0]
return jsonify({"id": person_id, "name": name}), 201
@app.route("/api/<int:person_id>", methods=['GET'])
def get(person_id):
"""
Fetches user based on user id
"""
with conn:
with conn.cursor() as cursor:
cursor.execute("SELECT * FROM persons WHERE id = %s", (person_id,))
user = cursor.fetchone()
if user:
return jsonify({"id": user[0], "name": user[1]}), 200
else:
return jsonify({"error": f"User with ID {person_id} not found"}), 404
@app.route("/api/<int:person_id>", methods=['PUT'])
def update_persons(person_id):
"""
Updates person based on provided id
"""
data = request.get_json()
name = data['name']
with conn:
with conn.cursor() as cursor:
cursor.execute(
"UPDATE persons SET name = %s WHERE id = %s",
(name,person_id,)
)
if cursor.rowcount == 0:
return jsonify({"error": f"User with ID {person_id} not found."}), 404
return jsonify({
"id": person_id,
"name": name,
"message": f"User {person_id} updated"
}), 201
@app.route("/api/<int:person_id>", methods=['DELETE'])
def delete_person(person_id):
"""
Deletes person based on provided id
"""
with conn:
with conn.cursor() as cursor:
cursor.execute("DELETE FROM persons WHERE id = %s", (person_id,))
if cursor.rowcount == 0:
return jsonify({"error": f"{person_id} not found"}), 404
return jsonify({
"id": person_id,
"message": f"User {person_id} deleted"
}), 201
if __name__ == "__main__":
app.run(debug=True)