forked from Flagsmith/flagsmith
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathviews.py
More file actions
164 lines (137 loc) · 6.08 KB
/
views.py
File metadata and controls
164 lines (137 loc) · 6.08 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
import logging
import typing
from common.core.utils import using_database_replica
from drf_yasg.utils import swagger_auto_schema # type: ignore[import-untyped]
from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.fields import IntegerField
from rest_framework.generics import CreateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.serializers import Serializer
from app_analytics.analytics_db_service import (
get_total_events_count,
get_usage_data,
)
from app_analytics.cache import FeatureEvaluationCache
from app_analytics.mappers import (
map_request_to_labels,
)
from environments.authentication import EnvironmentKeyAuthentication
from environments.permissions.permissions import EnvironmentKeyPermissions
from features.models import FeatureState
from organisations.models import Organisation
from telemetry.serializers import TelemetrySerializer
from .permissions import UsageDataPermission
from .serializers import (
SDKAnalyticsFlagsSerializer,
UsageDataQuerySerializer,
UsageDataSerializer,
UsageTotalCountSerializer,
)
logger = logging.getLogger(__name__)
feature_evaluation_cache = FeatureEvaluationCache()
class SDKAnalyticsFlagsV2(CreateAPIView): # type: ignore[type-arg]
permission_classes = (EnvironmentKeyPermissions,)
authentication_classes = (EnvironmentKeyAuthentication,)
serializer_class = SDKAnalyticsFlagsSerializer
throttle_classes = []
@swagger_auto_schema( # type: ignore[misc]
request_body=SDKAnalyticsFlagsSerializer(),
responses={204: Response(status=status.HTTP_204_NO_CONTENT)},
)
def create(self, request: Request, *args, **kwargs) -> Response: # type: ignore[no-untyped-def]
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save(environment=self.request.environment)
return Response(status=status.HTTP_204_NO_CONTENT)
class SDKAnalyticsFlags(CreateAPIView): # type: ignore[type-arg]
"""
Class to handle flag analytics events
"""
permission_classes = (EnvironmentKeyPermissions,)
authentication_classes = (EnvironmentKeyAuthentication,)
throttle_classes = []
format_kwarg = None
def get_serializer_class(self): # type: ignore[no-untyped-def]
if getattr(self, "swagger_fake_view", False):
return Serializer
environment_feature_names = set(
using_database_replica(FeatureState.objects)
.filter(
environment=self.request.environment,
feature_segment=None,
identity=None,
)
.values_list("feature__name", flat=True)
)
class _AnalyticsSerializer(Serializer): # type: ignore[type-arg]
def get_fields(self): # type: ignore[no-untyped-def]
return {
feature_name: IntegerField(required=False)
for feature_name in environment_feature_names
}
def save(self, **kwargs: typing.Any) -> None:
request = self.context["request"]
# validated_data splits out request body with '.' in feature name (e.g a.b.c).
# Instead, it's safe to use self.data as keys are not altered.
for feature_name, evaluation_count in self.data.items():
feature_evaluation_cache.track_feature_evaluation(
environment_id=request.environment.id,
feature_name=feature_name,
evaluation_count=evaluation_count,
labels=map_request_to_labels(request),
)
return _AnalyticsSerializer
@swagger_auto_schema( # type: ignore[misc]
request_body=SDKAnalyticsFlagsSerializer(),
responses={200: Response(status=status.HTTP_200_OK)},
)
def create(
self, request: Request, *args: typing.Any, **kwargs: typing.Any
) -> Response:
"""
Send flag evaluation events from the SDK back to the API for reporting.
TODO: Eventually replace this with the v2 version of
this endpoint once SDKs have been updated.
"""
serializer = self.get_serializer(data=request.data)
serializer.is_valid()
serializer.save(environment=self.request.environment)
return Response(status=status.HTTP_200_OK)
class SelfHostedTelemetryAPIView(CreateAPIView): # type: ignore[type-arg]
"""
Class to handle telemetry events from self hosted APIs so we can aggregate and track
self hosted installation data
"""
permission_classes = ()
authentication_classes = ()
throttle_classes = []
serializer_class = TelemetrySerializer
@swagger_auto_schema( # type: ignore[misc]
responses={200: UsageTotalCountSerializer()},
methods=["GET"],
)
@api_view(["GET"])
@permission_classes([IsAuthenticated, UsageDataPermission])
def get_usage_data_total_count_view(request: Request, organisation_pk: int) -> Response:
organisation = using_database_replica(Organisation.objects).get(id=organisation_pk)
count = get_total_events_count(organisation)
serializer = UsageTotalCountSerializer(data={"count": count})
serializer.is_valid(raise_exception=True)
return Response(serializer.data)
@swagger_auto_schema( # type: ignore[misc]
query_serializer=UsageDataQuerySerializer(),
responses={200: UsageDataSerializer()},
methods=["GET"],
)
@api_view(["GET"])
@permission_classes([IsAuthenticated, UsageDataPermission])
def get_usage_data_view(request: Request, organisation_pk: int) -> Response:
filters = UsageDataQuerySerializer(data=request.query_params)
filters.is_valid(raise_exception=True)
organisation = using_database_replica(Organisation.objects).get(id=organisation_pk)
usage_data = get_usage_data(organisation, **filters.validated_data)
serializer = UsageDataSerializer(usage_data, many=True)
return Response(serializer.data)