This repository has been archived by the owner on May 30, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
micro_rental_log.py
143 lines (126 loc) · 4.55 KB
/
micro_rental_log.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
#!/usr/bin/env python3
import os
from flask import Flask, request, jsonify
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import desc
from os import environ
from datetime import datetime
app = Flask(__name__)
CORS(app)
app = Flask(__name__)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_ENGINE_OPTIONS'] = {'pool_recycle': 299}
# app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqlconnector://root:root@localhost:8889/Rental_log'
#app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqlconnector://root@localhost:3306/rental_log'
app.config['SQLALCHEMY_DATABASE_URI'] = environ.get('dbURL')
db = SQLAlchemy(app)
class Rental_log(db.Model):
__tablename__ = 'rental_log'
log_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
log_entry_time = db.Column(db.DateTime, nullable=False, default=datetime.now)
vehicle_id = db.Column(db.Integer, nullable=False)
user_id = db.Column(db.Integer, nullable=False)
status = db.Column(db.String(10), nullable=False, default='CONFIRMED')
def json(self):
return {"log_id": self.log_id, "log_entry_time":self.log_entry_time, "vehicle_id": self.vehicle_id, "user_id": self.user_id,"status":self.status}
#create rental log
#userID/VehicleID/Latitude/Longitude
@app.route("/rental_log", methods=['POST'])
def createRentalLog():
# JSON data validation
rental_data = None
if request.is_json:
rental_data = request.get_json()
result = processRentalLog(rental_data)
return result
else:
data = request.get_data()
print("Received an invalid rental log entry:")
print(data)
return jsonify({"code": 400,
"data": str(data),
"message": "Ensure that rental log entry is in JSON format."}), 400
#update rental log as cancelled
@app.route("/rental_log/cancel", methods=['PUT'])
def update_log_entry():
report = request.get_json()
vehicle_id = report['vehicle_id']
try:
rental_log = db.session.scalars(
db.select(Rental_log).filter_by(vehicle_id=vehicle_id).order_by(desc(Rental_log.log_entry_time))).first()
if not rental_log:
return jsonify(
{
"code": 404,
"data": {
"vehicle_id": vehicle_id
},
"message": "Rental log for Vehicle ID" + str(vehicle_id) + "was not found."
}
), 404
# update availability
rental_log.status = "Cancelled"
db.session.commit()
return jsonify(
{
"code": 200,
"data": rental_log.json()
}
), 200
except Exception as e:
return jsonify(
{
"code": 500,
"data": {
"vehicle_id": vehicle_id,
"status": "Cancelled"
},
"message": "An error occurred while updating the rental log. " + str(e)
}
), 500
#get rental log
@app.route("/rental_log/<user_id>", methods=['GET'])
def getRentalLog(user_id):
# JSON data validation
log = db.session.scalars(
db.select(Rental_log).filter_by(user_id=user_id).order_by(desc(Rental_log.log_entry_time))).first()
if log:
return jsonify(
{
"code": 200,
"data": log.json()
}
)
return jsonify(
{
"code": 404,
"message": "Booking not found."
}
), 404
def processRentalLog(rental_data):
print("Processing a rental log entry:")
print(rental_data)
if ("user_id" not in rental_data) or ("vehicle_id" not in rental_data):
return jsonify(
{
"code": 400,
"message": "Missing user ID or Vehicle ID"
}
), 400
new_log = Rental_log(user_id = rental_data["user_id"], vehicle_id = rental_data["vehicle_id"])
db.session.add(new_log)
db.session.commit() # This step generates the log_id
data = {
'log_id': new_log.log_id,
'log_time': new_log.log_entry_time
}
return jsonify({
"code": 201,
"data" : data,
"message": "Rental log successfully created"
}), 201
# Execute this program only if it is run as a script (not by 'import')
if __name__ == "__main__":
print("This is flask " + os.path.basename(__file__) + ": handling rental log entries ...")
app.run(host='0.0.0.0', port=5002, debug=True)