mibrahimzia commited on
Commit
697f7ef
·
verified ·
1 Parent(s): ec3bf2b

Create analytics.py

Browse files
Files changed (1) hide show
  1. utils/analytics.py +48 -0
utils/analytics.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Analytics and usage tracking utilities
3
+ """
4
+ from datetime import datetime, timedelta
5
+ from collections import defaultdict
6
+ import logging
7
+
8
+ logger = logging.getLogger("webtapi.analytics")
9
+
10
+ # In-memory storage (replace with database in production)
11
+ usage_data = defaultdict(lambda: {
12
+ "total_requests": 0,
13
+ "last_used": None,
14
+ "endpoints_created": 0,
15
+ "daily_usage": defaultdict(int)
16
+ })
17
+
18
+ def track_usage(api_key, endpoint_created=False):
19
+ """Track API usage"""
20
+ today = datetime.now().strftime("%Y-%m-%d")
21
+
22
+ usage_data[api_key]["total_requests"] += 1
23
+ usage_data[api_key]["last_used"] = datetime.now()
24
+ usage_data[api_key]["daily_usage"][today] += 1
25
+
26
+ if endpoint_created:
27
+ usage_data[api_key]["endpoints_created"] += 1
28
+
29
+ logger.info(f"Usage tracked for API key: {api_key}")
30
+
31
+ def get_usage_stats(api_key):
32
+ """Get usage statistics for an API key"""
33
+ if api_key not in usage_data:
34
+ return None
35
+
36
+ today = datetime.now().strftime("%Y-%m-%d")
37
+ daily_usage = usage_data[api_key]["daily_usage"].get(today, 0)
38
+
39
+ return {
40
+ "total_requests": usage_data[api_key]["total_requests"],
41
+ "endpoints_created": usage_data[api_key]["endpoints_created"],
42
+ "last_used": usage_data[api_key]["last_used"],
43
+ "daily_usage": daily_usage
44
+ }
45
+
46
+ def get_all_usage_stats():
47
+ """Get usage statistics for all API keys"""
48
+ return dict(usage_data)