-
-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathpython-flask.html
More file actions
494 lines (419 loc) · 18.5 KB
/
python-flask.html
File metadata and controls
494 lines (419 loc) · 18.5 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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" type="image/png" href="images/logo.png">
<link rel="apple-touch-icon" href="images/logo.png">
<title>Python Flask API - Developer Toolkit | DevDunia</title>
<meta name="description" content="Simple Flask API endpoints, routing, and request handling. Free online Python Flask examples for developers.">
<script src="https://cdn.tailwindcss.com"></script>
<style>
body {
background: linear-gradient(135deg, #0f172a 0%, #1e293b 50%, #0f172a 100%);
}
</style>
</head>
<body class="h-screen lg:ml-72">
<!-- Background: Consistent Subtle Dark Gradient -->
<div class="fixed inset-0 -z-10 bg-gradient-to-br from-gray-900 via-slate-900 to-gray-900"></div>
<!-- Main Container -->
<div class="relative z-10 container mx-auto px-4 pt-16 pb-24 sm:px-6 lg:px-8">
<!-- Page Header -->
<div class="text-center mb-12">
<h1 class="text-3xl sm:text-4xl font-bold mb-4 tracking-tight
text-transparent bg-clip-text bg-gradient-to-r from-emerald-400 to-teal-500">
Python Flask API
</h1>
<p class="text-lg text-gray-400 max-w-2xl mx-auto">
Simple Flask API endpoints, routing, and request handling.
</p>
</div>
<!-- Tool Container -->
<div class="max-w-4xl mx-auto">
<div class="bg-slate-800/70 backdrop-blur-md rounded-lg shadow-lg border border-slate-700/60 p-6">
<!-- API Type Selection -->
<div class="mb-6">
<label class="block text-sm font-medium text-gray-300 mb-3">API Type</label>
<div class="grid grid-cols-1 md:grid-cols-3 gap-3">
<button class="api-type-btn px-4 py-2 bg-emerald-600 hover:bg-emerald-700 text-white text-sm rounded-lg transition-colors duration-200" data-type="basic">
Basic API
</button>
<button class="api-type-btn px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white text-sm rounded-lg transition-colors duration-200" data-type="crud">
CRUD API
</button>
<button class="api-type-btn px-4 py-2 bg-purple-600 hover:bg-purple-700 text-white text-sm rounded-lg transition-colors duration-200" data-type="auth">
Auth API
</button>
</div>
</div>
<!-- Endpoint Configuration -->
<div class="mb-6">
<label class="block text-sm font-medium text-gray-300 mb-3">Endpoint Configuration</label>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<label for="app-name" class="block text-sm font-medium text-gray-300 mb-2">App Name</label>
<input
type="text"
id="app-name"
class="w-full px-4 py-3 bg-slate-700/50 border border-slate-600 rounded-lg text-gray-200 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-transparent font-mono text-sm"
placeholder="my_api"
value="my_api"
>
</div>
<div>
<label for="port" class="block text-sm font-medium text-gray-300 mb-2">Port</label>
<input
type="number"
id="port"
class="w-full px-4 py-3 bg-slate-700/50 border border-slate-600 rounded-lg text-gray-200 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-transparent font-mono text-sm"
placeholder="5000"
value="5000"
>
</div>
</div>
</div>
<!-- Generate Button -->
<div class="mb-6">
<button id="generate-btn" class="px-6 py-3 bg-emerald-600 hover:bg-emerald-700 text-white font-medium rounded-lg transition-colors duration-200 flex items-center space-x-2">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"></path>
</svg>
<span>Generate Flask Code</span>
</button>
</div>
<!-- Generated Code -->
<div id="code-section" class="hidden">
<h3 class="text-lg font-semibold text-gray-300 mb-4">Generated Flask Code</h3>
<div class="relative">
<textarea
id="generated-code"
rows="30"
class="w-full px-4 py-3 bg-slate-700/50 border border-slate-600 rounded-lg text-gray-200 font-mono text-sm resize-none"
readonly
></textarea>
<!-- Copy Button -->
<button id="copy-code-btn" class="absolute top-2 right-2 px-3 py-1 bg-slate-600 hover:bg-slate-700 text-white text-sm rounded transition-colors duration-200 flex items-center space-x-1">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v8a2 2 0 01-2 2h-2m-6-4l2 2m0 0l2-2m-2 2V10"></path>
</svg>
<span>Copy</span>
</button>
</div>
</div>
<!-- Requirements -->
<div class="mt-8 p-4 bg-slate-700/30 rounded-lg border border-slate-600/50">
<h3 class="text-lg font-semibold text-cyan-400 mb-3">Requirements</h3>
<div class="bg-slate-600/50 p-3 rounded border border-slate-500">
<pre class="text-cyan-300 font-mono text-sm">Flask==2.3.3
Flask-CORS==4.0.0</pre>
</div>
</div>
<!-- Usage Instructions -->
<div class="mt-6 p-4 bg-slate-700/30 rounded-lg border border-slate-600/50">
<h3 class="text-lg font-semibold text-cyan-400 mb-3">Usage Instructions</h3>
<div class="space-y-2 text-sm text-gray-300">
<p>1. Install requirements: <code class="bg-slate-600 px-2 py-1 rounded text-cyan-300">pip install -r requirements.txt</code></p>
<p>2. Run the application: <code class="bg-slate-600 px-2 py-1 rounded text-cyan-300">python app.py</code></p>
<p>3. Access the API at: <code class="bg-slate-600 px-2 py-1 rounded text-cyan-300">http://localhost:5000</code></p>
</div>
</div>
</div>
</div>
</div>
<!-- Footer include -->
<div id="footer"></div>
<script>
fetch("footer.html")
.then(response => response.text())
.then(data => {
document.getElementById("footer").innerHTML = data;
})
.catch(err => console.error("Failed to load footer:", err));
</script>
<script>
document.addEventListener('DOMContentLoaded', function() {
const apiTypeBtns = document.querySelectorAll('.api-type-btn');
const appNameInput = document.getElementById('app-name');
const portInput = document.getElementById('port');
const generateBtn = document.getElementById('generate-btn');
const codeSection = document.getElementById('code-section');
const generatedCode = document.getElementById('generated-code');
const copyCodeBtn = document.getElementById('copy-code-btn');
let selectedType = 'basic';
// API type selection
apiTypeBtns.forEach(btn => {
btn.addEventListener('click', function() {
selectedType = this.getAttribute('data-type');
// Update button states
apiTypeBtns.forEach(b => b.classList.remove('ring-2', 'ring-emerald-400'));
this.classList.add('ring-2', 'ring-emerald-400');
});
});
// Set initial type
document.querySelector('[data-type="basic"]').click();
// Generate code
generateBtn.addEventListener('click', function() {
const appName = appNameInput.value.trim() || 'my_api';
const port = portInput.value.trim() || '5000';
const code = generateFlaskCode(appName, port);
generatedCode.value = code;
codeSection.classList.remove('hidden');
});
// Copy code
copyCodeBtn.addEventListener('click', function() {
generatedCode.select();
document.execCommand('copy');
// Visual feedback
const originalText = copyCodeBtn.innerHTML;
copyCodeBtn.innerHTML = '<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path></svg><span>Copied!</span>';
copyCodeBtn.classList.add('bg-green-600');
setTimeout(() => {
copyCodeBtn.innerHTML = originalText;
copyCodeBtn.classList.remove('bg-green-600');
}, 2000);
});
function generateFlaskCode(appName, port) {
switch (selectedType) {
case 'basic':
return generateBasicAPI(appName, port);
case 'crud':
return generateCRUDAPI(appName, port);
case 'auth':
return generateAuthAPI(appName, port);
default:
return generateBasicAPI(appName, port);
}
}
function generateBasicAPI(appName, port) {
return `from flask import Flask, jsonify, request
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
# Sample data
users = [
{"id": 1, "name": "John Doe", "email": "john@example.com"},
{"id": 2, "name": "Jane Smith", "email": "jane@example.com"}
]
@app.route('/')
def home():
return jsonify({
"message": "Welcome to ${appName} API",
"version": "1.0.0",
"endpoints": [
"GET /users - Get all users",
"GET /users/<id> - Get user by ID",
"POST /users - Create new user"
]
})
@app.route('/users', methods=['GET'])
def get_users():
return jsonify(users)
@app.route('/users/<int:user_id>', methods=['GET'])
def get_user(user_id):
user = next((u for u in users if u['id'] == user_id), None)
if user:
return jsonify(user)
return jsonify({"error": "User not found"}), 404
@app.route('/users', methods=['POST'])
def create_user():
data = request.get_json()
if not data or 'name' not in data or 'email' not in data:
return jsonify({"error": "Name and email are required"}), 400
new_user = {
"id": len(users) + 1,
"name": data['name'],
"email": data['email']
}
users.append(new_user)
return jsonify(new_user), 201
@app.route('/health')
def health_check():
return jsonify({"status": "healthy", "service": "${appName}"})
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=${port})`;
}
function generateCRUDAPI(appName, port) {
return `from flask import Flask, jsonify, request
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
# In-memory database (replace with real database in production)
items = [
{"id": 1, "name": "Item 1", "description": "First item", "price": 10.99},
{"id": 2, "name": "Item 2", "description": "Second item", "price": 20.99}
]
@app.route('/')
def home():
return jsonify({
"message": "Welcome to ${appName} CRUD API",
"version": "1.0.0",
"endpoints": [
"GET /items - Get all items",
"GET /items/<id> - Get item by ID",
"POST /items - Create new item",
"PUT /items/<id> - Update item",
"DELETE /items/<id> - Delete item"
]
})
# READ - Get all items
@app.route('/items', methods=['GET'])
def get_items():
return jsonify(items)
# READ - Get item by ID
@app.route('/items/<int:item_id>', methods=['GET'])
def get_item(item_id):
item = next((i for i in items if i['id'] == item_id), None)
if item:
return jsonify(item)
return jsonify({"error": "Item not found"}), 404
# CREATE - Add new item
@app.route('/items', methods=['POST'])
def create_item():
data = request.get_json()
if not data or 'name' not in data:
return jsonify({"error": "Name is required"}), 400
new_item = {
"id": max([i['id'] for i in items], default=0) + 1,
"name": data['name'],
"description": data.get('description', ''),
"price": data.get('price', 0.0)
}
items.append(new_item)
return jsonify(new_item), 201
# UPDATE - Update existing item
@app.route('/items/<int:item_id>', methods=['PUT'])
def update_item(item_id):
item = next((i for i in items if i['id'] == item_id), None)
if not item:
return jsonify({"error": "Item not found"}), 404
data = request.get_json()
if not data:
return jsonify({"error": "No data provided"}), 400
# Update item fields
if 'name' in data:
item['name'] = data['name']
if 'description' in data:
item['description'] = data['description']
if 'price' in data:
item['price'] = data['price']
return jsonify(item)
# DELETE - Delete item
@app.route('/items/<int:item_id>', methods=['DELETE'])
def delete_item(item_id):
global items
item = next((i for i in items if i['id'] == item_id), None)
if not item:
return jsonify({"error": "Item not found"}), 404
items = [i for i in items if i['id'] != item_id]
return jsonify({"message": "Item deleted successfully"})
@app.route('/health')
def health_check():
return jsonify({"status": "healthy", "service": "${appName}"})
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=${port})`;
}
function generateAuthAPI(appName, port) {
return `from flask import Flask, jsonify, request, make_response
from flask_cors import CORS
import jwt
import datetime
from functools import wraps
app = Flask(__name__)
CORS(app)
app.config['SECRET_KEY'] = 'your-secret-key-change-in-production'
# Sample users database
users_db = {
"admin": {"password": "admin123", "role": "admin"},
"user": {"password": "user123", "role": "user"}
}
def token_required(f):
@wraps(f)
def decorated(*args, **kwargs):
token = request.headers.get('Authorization')
if not token:
return jsonify({'message': 'Token is missing!'}), 401
try:
if token.startswith('Bearer '):
token = token[7:]
data = jwt.decode(token, app.config['SECRET_KEY'], algorithms=['HS256'])
current_user = data['user']
except:
return jsonify({'message': 'Token is invalid!'}), 401
return f(current_user, *args, **kwargs)
return decorated
@app.route('/')
def home():
return jsonify({
"message": "Welcome to ${appName} Auth API",
"version": "1.0.0",
"endpoints": [
"POST /login - Login and get token",
"GET /protected - Protected route (requires token)",
"GET /admin - Admin only route"
]
})
@app.route('/login', methods=['POST'])
def login():
data = request.get_json()
if not data or 'username' not in data or 'password' not in data:
return jsonify({'message': 'Username and password required'}), 400
username = data['username']
password = data['password']
if username in users_db and users_db[username]['password'] == password:
token = jwt.encode({
'user': username,
'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=24)
}, app.config['SECRET_KEY'], algorithm='HS256')
return jsonify({
'token': token,
'user': username,
'role': users_db[username]['role']
})
return jsonify({'message': 'Invalid credentials'}), 401
@app.route('/protected')
@token_required
def protected(current_user):
return jsonify({
'message': f'Hello {current_user}! This is a protected route.',
'user': current_user
})
@app.route('/admin')
@token_required
def admin_only(current_user):
if users_db[current_user]['role'] != 'admin':
return jsonify({'message': 'Admin access required'}), 403
return jsonify({
'message': f'Welcome admin {current_user}!',
'admin_data': 'Sensitive admin information'
})
@app.route('/users')
@token_required
def get_users(current_user):
return jsonify({
'users': list(users_db.keys()),
'current_user': current_user
})
@app.route('/health')
def health_check():
return jsonify({"status": "healthy", "service": "${appName}"})
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=${port})`;
}
});
</script>
<!-- Include Final Sidebar -->
<div id="sidebar-container"></div>
<script>
// Load final_sidebar.html content
fetch('final_sidebar.html')
.then(response => response.text())
.then(html => {
document.getElementById('sidebar-container').innerHTML = html;
})
.catch(error => {
console.error('Error loading sidebar:', error);
});
</script>
</body>
</html>