-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
171 lines (141 loc) · 5.99 KB
/
server.py
File metadata and controls
171 lines (141 loc) · 5.99 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
from tusk_drift_init import tusk_drift
from flask import Flask, request, jsonify
import requests
from opentelemetry import context as otel_context
app = Flask(__name__)
PORT = 3000
@app.route('/api/weather-activity', methods=['GET'])
def weather_activity():
"""Get location from IP, weather, and activity recommendations"""
try:
# First API call: Get user's location from IP
location_response = requests.get('http://ip-api.com/json/')
location_response.raise_for_status()
location_data = location_response.json()
city = location_data['city']
lat = location_data['lat']
lon = location_data['lon']
country = location_data['country']
# Business logic: Determine activity based on location
is_coastal = abs(lon) > 50 or abs(lat) < 30
# Second API call: Get weather for the location
weather_response = requests.get(
f'https://api.open-meteo.com/v1/forecast?latitude={lat}&longitude={lon}¤t_weather=true'
)
weather_response.raise_for_status()
weather = weather_response.json()['current_weather']
# Business logic: Recommend activity based on weather
recommended_activity = 'Play a board game'
if weather['temperature'] > 40:
recommended_activity = 'Too hot - stay indoors'
elif weather['temperature'] > 20 and weather['windspeed'] < 20:
recommended_activity = 'Beach day!' if is_coastal else 'Perfect for hiking!'
elif weather['temperature'] < 10:
recommended_activity = 'Hot chocolate weather'
elif weather['windspeed'] > 30:
recommended_activity = 'Too windy - indoor activities recommended'
else:
recommended_activity = 'Nice day for a walk'
# Third API call: Get a random activity suggestion
activity_response = requests.get('https://bored-api.appbrewery.com/random')
activity_response.raise_for_status()
alternative_activity = activity_response.json()
return jsonify({
'location': {
'city': city,
'country': country,
'coordinates': {'lat': lat, 'lon': lon},
'isCoastal': is_coastal
},
'weather': {
'temperature': weather['temperature'],
'windspeed': weather['windspeed'],
'weathercode': weather['weathercode'],
'time': weather['time']
},
'recommendations': {
'weatherBased': recommended_activity,
'alternative': {
'activity': alternative_activity['activity'],
'type': alternative_activity['type'],
'participants': alternative_activity['participants']
}
}
})
except Exception as error:
return jsonify({'error': 'Failed to fetch weather and activity data'}), 500
@app.route('/api/user/<user_id>', methods=['GET'])
def get_user(user_id):
"""Get random user with seed parameter"""
try:
response = requests.get(f'https://randomuser.me/api/?seed={user_id}')
response.raise_for_status()
return jsonify(response.json())
except Exception as error:
return jsonify({'error': 'Failed to fetch user data'}), 500
@app.route('/api/user', methods=['POST'])
def create_user():
"""Create random user (no seed)"""
try:
response = requests.get('https://randomuser.me/api/')
response.raise_for_status()
return jsonify(response.json())
except Exception as error:
return jsonify({'error': 'Failed to create user'}), 500
@app.route('/api/post/<int:post_id>', methods=['GET'])
def get_post(post_id):
"""Get post with comments"""
try:
post_response = requests.get(f'https://jsonplaceholder.typicode.com/posts/{post_id}')
post_response.raise_for_status()
comments_response = requests.get(f'https://jsonplaceholder.typicode.com/posts/{post_id}/comments')
comments_response.raise_for_status()
return jsonify({
'post': post_response.json(),
'comments': comments_response.json()
})
except Exception as error:
return jsonify({'error': 'Failed to fetch post data'}), 500
@app.route('/api/post', methods=['POST'])
def create_post():
"""Create new post"""
try:
data = request.get_json()
title = data.get('title')
body = data.get('body')
user_id = data.get('userId')
response = requests.post('https://jsonplaceholder.typicode.com/posts', json={
'title': title,
'body': body,
'userId': user_id
})
response.raise_for_status()
return jsonify(response.json()), 201
except Exception as error:
return jsonify({'error': 'Failed to create post'}), 500
@app.route('/api/post/<int:post_id>', methods=['DELETE'])
def delete_post(post_id):
"""Delete post"""
try:
response = requests.delete(f'https://jsonplaceholder.typicode.com/posts/{post_id}')
response.raise_for_status()
return jsonify({'message': f'Post {post_id} deleted successfully'})
except Exception as error:
return jsonify({'error': 'Failed to delete post'}), 500
@app.route('/health', methods=['GET'])
def health():
"""Health check endpoint"""
return jsonify({'status': 'healthy'})
def main():
tusk_drift.mark_app_as_ready()
print(f'Server is running on http://localhost:{PORT}')
print('\nAvailable endpoints:')
print(' GET /api/weather-activity - Recommend activity based on location and weather')
print(' GET /api/user/<id> - Get user')
print(' POST /api/user - Create user')
print(' GET /api/post/<id> - Get post, with comments')
print(' POST /api/post - Create post')
print(' DELETE /api/post/<id> - Delete post')
app.run(host='127.0.0.1', port=PORT)
if __name__ == '__main__':
main()