-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
85 lines (66 loc) · 2.39 KB
/
app.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
from flask import Flask, request, jsonify
import psycopg2
app = Flask(__name__)
DB_HOST = 'localhost'
DB_NAME = 'pagila'
DB_USER = 'timthom'
def create_connection():
try:
connection = psycopg2.connect(
host=DB_HOST,
database=DB_NAME,
user=DB_USER
)
return connection
except psycopg2.Error as e:
print(f"error connecting to database: {e}")
return None
@app.route('/')
def hello_world(): # put application's code here
return 'Hello World!'
@app.route('/get_actors', methods=['GET'])
def get_actors():
connection = create_connection()
if connection is None:
return jsonify({"error": "unable to connect to the database"}), 500
try:
with connection.cursor() as cursor:
cursor.execute("SELECT * FROM actor;")
actors = cursor.fetchall()
actor_list = []
for actor in actors:
actor_data = {
"actor_id": actor[0],
"first_name": actor[1],
"last_name": actor[2],
"last_update": actor[3]
}
actor_list.append(actor_data)
return jsonify({"actors": actor_list})
except psycopg2.Error as e:
print(f"Error retrieving data from the database: {e}")
return jsonify({"error": "error retrieving data from the database"}), 500
finally:
connection.close()
@app.route('/create_actor', methods=['POST'])
def create_actor():
connection = create_connection()
if connection is None:
return jsonify({"error": "unable to connect to the database"}), 500
try:
data = request.get_json()
first_name = data.get('first_name')
last_name = data.get('last_name')
with connection.cursor() as cursor:
query = "INSERT INTO actor (first_name, last_name) VALUES (%s, %s) RETURNING actor_id;"
cursor.execute(query, (first_name, last_name))
new_actor_id = cursor.fetchone()[0]
connection.commit()
return jsonify({"message": f"Actor {new_actor_id} created successfullly"}), 201
except psycopg2.Error as e:
print(f"Error creating actor: {e}")
return jsonify({"error": "failed to create actor"}), 500
finally:
connection.close()
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True)