-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
161 lines (130 loc) · 5.58 KB
/
Copy pathserver.py
File metadata and controls
161 lines (130 loc) · 5.58 KB
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
from dataclasses import dataclass
from random import choice
from flask import Flask, jsonify, render_template, request
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
from sqlalchemy import Integer, String, Boolean
app = Flask(__name__)
# CREATE DB
class Base(DeclarativeBase):
pass
# Connect to Database
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///cafes.db'
db = SQLAlchemy(model_class=Base)
db.init_app(app)
# Cafe TABLE Configuration
class Cafe(db.Model):
id: Mapped[int] = mapped_column(Integer, primary_key=True)
name: Mapped[str] = mapped_column(String(250), unique=True, nullable=False)
map_url: Mapped[str] = mapped_column(String(500), nullable=False)
img_url: Mapped[str] = mapped_column(String(500), nullable=False)
location: Mapped[str] = mapped_column(String(250), nullable=False)
seats: Mapped[str] = mapped_column(String(250), nullable=False)
has_toilet: Mapped[bool] = mapped_column(Boolean, nullable=False)
has_wifi: Mapped[bool] = mapped_column(Boolean, nullable=False)
has_sockets: Mapped[bool] = mapped_column(Boolean, nullable=False)
can_take_calls: Mapped[bool] = mapped_column(Boolean, nullable=False)
coffee_price: Mapped[str] = mapped_column(String(250), nullable=True)
def to_dict(self):
dictionary = {}
boolean_map = {}
for column in self.__table__.columns:
# if column.name != "id":
value = getattr(self, column.name)
if isinstance(value, bool):
boolean_map[column.name] = value
else:
dictionary[column.name] = value
if boolean_map:
dictionary['amenities'] = boolean_map
return dictionary
## Method 2. Alternatively use Dictionary Comprehension to do the same thing.
# return {column.name: getattr(self, column.name) for column in self.__table__.columns}
with app.app_context():
db.create_all()
@app.route("/")
def home():
return render_template("index.html")
# HTTP GET - Read Record
@app.route("/random")
def get_random_cafe():
result = db.session.execute(db.select(Cafe))
all_cafes = result.scalars().all()
random_cafe = choice(all_cafes)
# return jsonify(cafe={
# # Omit the id from the response
# # "id": random_cafe.id,
# "name": random_cafe.name,
# "map_url": random_cafe.map_url,
# "img_url": random_cafe.img_url,
# "location": random_cafe.location,
#
# # Put some properties in a sub-category
# "amenities": {
# "seats": random_cafe.seats,
# "has_toilet": random_cafe.has_toilet,
# "has_wifi": random_cafe.has_wifi,
# "has_sockets": random_cafe.has_sockets,
# "can_take_calls": random_cafe.can_take_calls,
# "coffee_price": random_cafe.coffee_price,
# }
# })
return jsonify(cafe=random_cafe.to_dict())
@app.route("/all")
def get_all_cafes():
result = db.session.execute(db.select(Cafe).order_by(Cafe.name))
all_cafes = result.scalars().all()
return jsonify(cafes=[cafe.to_dict() for cafe in all_cafes])
@app.route("/search")
def get_cafe_at_location():
query_location = request.args.get("loc")
result = db.session.execute(db.select(Cafe).where(Cafe.location == query_location))
# Note, this may get more than one cafe per location
all_cafes = result.scalars().all()
if all_cafes:
return jsonify(cafes=[cafe.to_dict() for cafe in all_cafes])
else:
return jsonify(error={"Not Found": "Sorry, we don't have a cafe at that location."}), 404
@app.route("/add", methods=["POST"])
def post_new_cafe():
new_cafe = Cafe(
name=request.form.get("name"),
map_url=request.form.get("map_url"),
img_url=request.form.get("img_url"),
location=request.form.get("loc"),
has_sockets=bool(request.form.get("sockets")),
has_toilet=bool(request.form.get("toilet")),
has_wifi=bool(request.form.get("wifi")),
can_take_calls=bool(request.form.get("calls")),
seats=request.form.get("seats"),
coffee_price=request.form.get("coffee_price"),
)
db.session.add(new_cafe)
db.session.commit()
return jsonify(response={"success": "Successfully added the new cafe."})
# http://127.0.0.1:5000/update-price/CAFE_ID?new_price=£5.67
@app.route("/update-price/<int:cafe_id>", methods=["PATCH"])
def patch_new_price(cafe_id):
new_price = request.args.get("new_price")
cafe = db.session.execute(db.select(Cafe).where(Cafe.id == cafe_id)).scalar()
if cafe:
cafe.coffee_price = new_price
db.session.commit()
return jsonify(response={f"success": f"Successfully update price for the cafe {cafe.name}."}), 204
else:
return jsonify(error={"Not Found": "Sorry a cafe with that id was not found in the database."}), 404
@app.route("/report-closed/<int:cafe_id>", methods=["DELETE"])
def delete_cafe(cafe_id):
api_key = request.args.get("api-key")
if api_key == "TopSecretAPIKey":
cafe = db.session.get(Cafe, cafe_id)
if cafe:
db.session.delete(cafe)
db.session.commit()
return jsonify(response={"success": "Successfully deleted the cafe from the database."}), 200
else:
return jsonify(error={"Not Found": "Sorry a cafe with that id was not found in the database."}), 404
else:
return jsonify(error={"Forbidden": "Sorry, that's not allowed. Make sure you have the correct api_key."}), 403
if __name__ == '__main__':
app.run(debug=True)