-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
241 lines (198 loc) · 7.39 KB
/
server.py
File metadata and controls
241 lines (198 loc) · 7.39 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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
from flask import Flask, jsonify, request, send_from_directory
import requests
from apscheduler.schedulers.background import BackgroundScheduler
from datetime import datetime
from bs4 import BeautifulSoup, Tag
import sqlite3
import os
app = Flask(__name__)
URL = "https://www.stw.berlin/mensen/einrichtungen/technische-universit%C3%A4t-berlin/mensa-tu-marchstra%C3%9Fe.html"
last_run = None
last_status = None
main_dishes_data = None
# Database initialization
def init_db():
conn = sqlite3.connect("ratings.db")
cursor = conn.cursor()
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS ratings (
id INTEGER PRIMARY KEY AUTOINCREMENT,
dish_name TEXT NOT NULL,
rating INTEGER NOT NULL CHECK (rating >= 1 AND rating <= 5),
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
)
"""
)
conn.commit()
conn.close()
# Initialize database on startup
init_db()
def fetch_mensa_page():
global last_run, last_status, main_dishes_data
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
}
try:
html = requests.get(URL, headers=headers, timeout=20).text
soup = BeautifulSoup(html, "html.parser")
speiseplan = soup.find(id="speiseplan")
if not speiseplan:
last_status = "Speiseplan not found"
return
# Find all splGroupWrapper containers
group_wrappers = speiseplan.find_all("div", class_="splGroupWrapper")
descriptions = []
for wrapper in group_wrappers:
# Check if this wrapper contains the "Essen" group
group_div = wrapper.find("div", class_="splGroup")
if group_div and group_div.get_text(strip=True) == "Essen":
# Find all splMeal divs that follow this group
meal_divs = wrapper.find_all("div", class_="splMeal")
for meal in meal_divs:
desc_tag = meal.find("span", class_="bold")
if desc_tag:
desc = desc_tag.get_text(strip=True)
descriptions.append(desc)
break # Found Essen group, no need to continue
main_dishes_data = descriptions[:3]
last_status = "Success"
# Save HTML to file for analysis
with open("last_mensa.html", "w", encoding="utf-8") as f:
f.write(html)
except Exception as e:
last_status = str(e)
last_run = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
scheduler = BackgroundScheduler()
scheduler.add_job(fetch_mensa_page, "cron", hour=8, minute=0)
scheduler.start()
@app.route("/status")
def status():
return jsonify(
{
"last_run": last_run,
"last_status": last_status,
"main_dishes": main_dishes_data,
}
)
@app.route("/fetch-now")
def fetch_now():
fetch_mensa_page()
return jsonify(
{"message": "Fetch triggered", "last_run": last_run, "last_status": last_status}
)
@app.route("/main-dishes")
def main_dishes():
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
}
try:
html = requests.get(URL, headers=headers, timeout=20).text
soup = BeautifulSoup(html, "html.parser")
speiseplan = soup.find(id="speiseplan")
if not speiseplan:
return jsonify({"error": "Speiseplan not found"}), 404
# Find all splGroupWrapper containers
group_wrappers = speiseplan.find_all("div", class_="splGroupWrapper")
descriptions = []
for wrapper in group_wrappers:
# Check if this wrapper contains the "Essen" group
group_div = wrapper.find("div", class_="splGroup")
if group_div and group_div.get_text(strip=True) == "Essen":
# Find all splMeal divs that follow this group
meal_divs = wrapper.find_all("div", class_="splMeal")
for meal in meal_divs:
desc_tag = meal.find("span", class_="bold")
if desc_tag:
desc = desc_tag.get_text(strip=True)
descriptions.append(desc)
break # Found Essen group, no need to continue
return jsonify({"main_dishes": descriptions[:3]})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route("/submit-rating", methods=["POST"])
def submit_rating():
try:
data = request.get_json()
dish_name = data.get("dish_name")
rating = data.get("rating")
if not dish_name or not rating:
return jsonify({"error": "Missing dish_name or rating"}), 400
if not isinstance(rating, int) or rating < 1 or rating > 5:
return jsonify({"error": "Rating must be an integer between 1 and 5"}), 400
conn = sqlite3.connect("ratings.db")
cursor = conn.cursor()
cursor.execute(
"INSERT INTO ratings (dish_name, rating) VALUES (?, ?)", (dish_name, rating)
)
conn.commit()
conn.close()
return jsonify({"message": "Rating submitted successfully"}), 200
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route("/ratings")
def get_ratings():
try:
conn = sqlite3.connect("ratings.db")
cursor = conn.cursor()
cursor.execute(
"""
SELECT dish_name,
COUNT(*) as count,
AVG(rating) as avg_rating,
MIN(rating) as min_rating,
MAX(rating) as max_rating
FROM ratings
GROUP BY dish_name
ORDER BY avg_rating DESC
"""
)
results = cursor.fetchall()
conn.close()
ratings_data = []
for row in results:
ratings_data.append(
{
"dish_name": row[0],
"count": row[1],
"avg_rating": round(row[2], 2) if row[2] else 0,
"min_rating": row[3],
"max_rating": row[4],
}
)
return jsonify({"ratings": ratings_data})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route("/all-reviews")
def get_all_reviews():
try:
conn = sqlite3.connect("ratings.db")
cursor = conn.cursor()
cursor.execute(
"""
SELECT id, dish_name, rating, timestamp
FROM ratings
ORDER BY timestamp DESC
"""
)
results = cursor.fetchall()
conn.close()
reviews_data = []
for row in results:
reviews_data.append(
{
"id": row[0],
"dish_name": row[1],
"rating": row[2],
"timestamp": row[3],
}
)
return jsonify({"reviews": reviews_data, "total_count": len(reviews_data)})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route("/")
def index():
return send_from_directory(".", "index.html")
if __name__ == "__main__":
app.run(debug=True, host="0.0.0.0", port=5001)
# Next step: Open 'last_mensa.html' and inspect the structure of the divs to refine the BeautifulSoup parsing logic for the main dishes.