-
Notifications
You must be signed in to change notification settings - Fork 65
/
Copy path__init__.py
executable file
·2387 lines (2128 loc) · 98.3 KB
/
__init__.py
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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import base64
import csv
import datetime
import gzip
import io
import logging
import os
import re
import shutil
import time
import urllib.error
import urllib.parse
import urllib.request
import zipfile
from copy import deepcopy
from http.client import IncompleteRead
from inspect import isfunction
from json.decoder import JSONDecodeError
from multiprocessing import cpu_count
from multiprocessing.pool import ThreadPool
from socket import timeout
from .paginator import ConcurrentPaginator
try:
import ujson as json
except ImportError:
import json
try:
import ciso8601
except ImportError:
# If ciso8601 is not installed datetime will be used instead
pass
class MixpanelUtils(object):
"""An object for querying, importing, exporting and modifying Mixpanel data via their various APIs"""
VERSION = "2.0"
LOGGER = logging.getLogger(__name__)
LOGGER.setLevel(logging.WARNING)
sh = logging.StreamHandler()
formatter = logging.Formatter("%(levelname)s: %(message)s")
sh.setFormatter(formatter)
LOGGER.addHandler(sh)
"""
Public, external methods
"""
def __init__(
self,
api_secret,
token=None,
service_account_username=None,
project_id=None,
strict_import=True,
timeout=120,
pool_size=None,
read_pool_size=2,
max_retries=4,
debug=False,
eu=False,
):
"""Initializes the MixpanelUtils object
:param api_secret: API Secret for your project OR your Service Account
:param token: Project Token for your project, required for imports
:param service_account_username: Username for your Service Account
:param project_id: project id, required for Service Account authentication
:param strict_import: When set to True (recommended), Mixpanel will validate imported events and return errors
per event that failed. (Default value = True)
:param timeout: Time in seconds to wait for HTTP responses
:param pool_size: Number of threads to use for sending data to Mixpanel (Default value = cpu_count * 2)
:param read_pool_size: Separate number of threads to use just for read operations (i.e. query_engage)
(Default value = 2)
:param max_retries: Maximum number of times to retry when a 5xx HTTP response is received (Default value = 4)
:param debug: Enable debug logging
:param eu: Is the project participating in EU residency
:type api_secret: str
:type token: str
:type service_account_username: str
:type project_id: int
:type strict_import: bool
:type timeout: int
:type pool_size: int
:type read_pool_size: int
:type max_retries: int
:type debug: bool
:type eu: bool
"""
self.api_secret = api_secret
self.token = token
self.service_account_username = service_account_username
self.project_id = project_id
self.strict_import = strict_import
if self.service_account_username is not None:
assert self.project_id, "project_id required for Service Account authentication!"
self.timeout = timeout
if pool_size is None:
# Default number of threads is system dependent
pool_size = cpu_count() * 2
self.pool_size = pool_size
self.read_pool_size = read_pool_size
self.max_retries = max_retries
self.eu = eu
self.raw_api = (
"https://data.mixpanel.com/api"
if eu is False
else "https://data-eu.mixpanel.com/api"
)
self.import_api = (
"https://api.mixpanel.com" if eu is False else "https://api-eu.mixpanel.com"
)
self.formatted_api = (
"https://mixpanel.com/api" if eu is False else "https://eu.mixpanel.com/api"
)
log_level = MixpanelUtils.LOGGER.getEffectiveLevel()
""" The logger is a singleton for the MixpanelUtils class, so multiple instances of the MixpanelUtils class will use the
same logger instance. Subsequent instances can upgrade the logging level to debug but they cannot downgrade it.
"""
if debug or log_level == 10:
MixpanelUtils.LOGGER.setLevel(logging.DEBUG)
else:
MixpanelUtils.LOGGER.setLevel(logging.WARNING)
@staticmethod
def export_data(
data, output_file, append_mode=False, format="json", compress=False
):
"""Writes and optionally compresses Mixpanel data to disk in json or csv format
:param data: A list of Mixpanel events or People profiles, if format='json', arbitrary json can be exported
:param output_file: Name of file to write to
:param append_mode: Set this to True to append data to an existing file using open() mode 'a+', uses open() mode
'w+' when False (Default value = False)
:param format: Output format can be 'json' or 'csv' (Default value = 'json')
:param compress: Option to gzip output (Default value = False)
:type data: list
:type output_file: str
:type append_mode: bool
:type format: str
:type compress: bool
"""
open_mode = "w+"
if append_mode:
open_mode = "a+"
with open(output_file, open_mode, encoding="utf-8") as output:
if format == "json":
json.dump(data, output)
elif format == "csv":
MixpanelUtils._write_items_to_csv(data, output_file)
else:
MixpanelUtils.LOGGER.warning(
f"Invalid format - must be 'json' or 'csv': format = {format}\nDumping json to {output_file}"
)
json.dump(data, output)
if compress:
MixpanelUtils._gzip_file(output_file)
@staticmethod
def sum_transactions(profile):
"""Returns a dict with a single key, 'Revenue' and the sum of all $transaction $amounts for the given profile as
the value
:param profile: A Mixpanel People profile dict
:type profile: dict
:return: A dict with key 'Revenue' and value containing the sum of all $transactions for the give profile
:rtype: dict
"""
total = 0
try:
transactions = profile["$properties"]["$transactions"]
for t in transactions:
total = total + t["$amount"]
except KeyError:
pass
return {"Revenue": total}
def request(
self,
base_url,
path_components,
params,
method="GET",
headers=None,
raw_stream=False,
retries=0,
):
"""Base method for sending HTTP requests to the various Mixpanel APIs
:param base_url: Ex: https://api.mixpanel.com
:param path_components: endpoint path as list of strings
:param params: dictionary containing the Mixpanel parameters for the API request
:param method: HTTP method verb: 'GET', 'POST', 'PUT', 'DELETE', 'PATCH'
:param headers: HTTP request headers dict (Default value = None)
:param raw_stream: Return the raw file-like response directly from urlopen, only works when base_url is
self.raw_api
:param retries: number of times the request has been retried (Default value = 0)
:type base_url: str
:type path_components: list
:type params: dict
:type method: str
:type headers: dict
:type raw_stream: bool
:type retries: int
:return: JSON data returned from API
:rtype: str
"""
if retries < self.max_retries:
# Add API version to url path if needed
if base_url == self.import_api:
base = [base_url]
else:
base = [base_url, str(MixpanelUtils.VERSION)]
request_url = "/".join(base + path_components)
if self.service_account_username:
basic_credentials = f"{self.service_account_username}:{self.api_secret}"
else:
basic_credentials = f"{self.api_secret}:"
encoded_credentials = base64.b64encode(basic_credentials.encode("utf-8")).decode("utf-8")
if headers is None:
headers = {}
headers["Authorization"] = f"Basic {encoded_credentials}"
# Set up request url and body based on HTTP method and endpoint
if self.service_account_username:
params['project_id'] = self.project_id
if method == "GET" or method == "DELETE":
data = None
request_url += "?" + MixpanelUtils._unicode_urlencode(params)
else:
if "import" in path_components:
headers["Content-Type"] = "application/json"
data = params["data"]
query_params = {}
if self.strict_import:
query_params["strict"] = 1
if self.service_account_username:
query_params["project_id"] = self.project_id
if query_params:
request_url += "?" + MixpanelUtils._unicode_urlencode(query_params)
else:
data = MixpanelUtils._unicode_urlencode(params).encode("utf-8")
if "engage" in path_components:
request_url += "?verbose=1"
# Uncomment the line below to debug log the request body data
# MixpanelUtils.LOGGER.debug(f"{method} data: {data}")
MixpanelUtils.LOGGER.debug(f"Request Method: {method}")
MixpanelUtils.LOGGER.debug(f"Request URL: {request_url}")
request = urllib.request.Request(request_url, data, headers, method=method)
MixpanelUtils.LOGGER.debug(f"Request Headers: {json.dumps(headers)}")
try:
response = urllib.request.urlopen(request, timeout=self.timeout)
if raw_stream and base_url == self.raw_api:
return response
except urllib.error.HTTPError as e:
MixpanelUtils.LOGGER.error("The server couldn't fulfill the request.")
MixpanelUtils.LOGGER.error(f"HTTP Error Code: {e.code}")
MixpanelUtils.LOGGER.error(f"Reason: {e.reason}")
if hasattr(e, "read"):
MixpanelUtils.LOGGER.error(f"Response: {e.read().decode('utf-8')}")
if e.code >= 500:
# Retry if we get an HTTP 5xx error
MixpanelUtils.LOGGER.warning(f"Attempting retry #{retries + 1}")
return self.request(
base_url,
path_components,
params,
method=method,
headers=headers,
raw_stream=raw_stream,
retries=retries + 1,
)
except urllib.error.URLError as e:
MixpanelUtils.LOGGER.error("We failed to reach a server.")
MixpanelUtils.LOGGER.error(f"Reason: {e.reason}")
if hasattr(e, "read"):
MixpanelUtils.LOGGER.error(f"Response: {e.read()}")
MixpanelUtils.LOGGER.warning(f"Attempting retry #{retries + 1}")
return self.request(
base_url,
path_components,
params,
method=method,
headers=headers,
raw_stream=raw_stream,
retries=retries + 1,
)
except timeout:
MixpanelUtils.LOGGER.error("The read operation timed out.")
self.timeout = self.timeout + 30
MixpanelUtils.LOGGER.warning(
f"Increasing timeout to {self.timeout} and attempting retry #{retries + 1}"
)
return self.request(
base_url,
path_components,
params,
method=method,
headers=headers,
raw_stream=raw_stream,
retries=retries + 1,
)
else:
try:
# If the response is gzipped we go ahead and decompress
if response.info().get("Content-Encoding") == "gzip":
response_data = gzip.decompress(response.read())
else:
response_data = response.read()
return response_data.decode("utf-8")
except IncompleteRead:
MixpanelUtils.LOGGER.error(
f"Response data is incomplete. Attempting retry #{retries + 1}"
)
return self.request(
base_url,
path_components,
params,
method=method,
headers=headers,
raw_stream=raw_stream,
retries=retries + 1,
)
else:
MixpanelUtils.LOGGER.error(
"Maximum retries reached. Request failed. Try again later."
)
raise BaseException
def people_operation(
self,
operation,
value,
profiles=None,
query_params=None,
timezone_offset=None,
ignore_alias=False,
backup=False,
backup_file=None,
):
"""Base method for performing any of the People analytics update operations
https://mixpanel.com/help/reference/http#update-operations
:param operation: A string with name of a Mixpanel People operation, like $set or $delete
:param value: Can be a static value applied to all profiles or a user-defined function (or lambda) that takes a
profile as its only parameter and returns the value to use for the operation on the given profile
:param profiles: Can be a list of profiles or the name of a file containing a JSON array or CSV of profiles.
Alternative to query_params. (Default value = None)
:param query_params: Parameters to query /engage API. Alternative to profiles param. (Default value = None)
:param timezone_offset: UTC offset in hours of project timezone setting, used to calculate as_of_timestamp
parameter for queries that use behaviors. Required if query_params contains behaviors (Default value = None)
:param ignore_alias: True or False (Default value = False)
:param backup: True to create backup file otherwise False (default)
:param backup_file: Optional filename to use for the backup file (Default value = None)
:type operation: str
:type profiles: list | str
:type query_params: dict
:type timezone_offset: int | float
:type ignore_alias: bool
:type backup: bool
:type backup_file: str
:return: Number of profiles operated on
:rtype: int
"""
assert self.token, "Project token required for People operation!"
if profiles is not None and query_params is not None:
MixpanelUtils.LOGGER.error(
"profiles and query_params both provided, please use one or the other"
)
return
if profiles is not None:
profiles_list = MixpanelUtils._list_from_argument(profiles)
elif query_params is not None:
profiles_list = self.query_engage(
query_params, timezone_offset=timezone_offset
)
else:
# If both profiles and query_params are None just fetch all profiles
profiles_list = self.query_engage()
if backup:
if backup_file is None:
backup_file = "backup_{:.0f}.json".format(time.time())
self.export_data(profiles_list, backup_file, append_mode=True)
# Set the dynamic flag to True if value is a function
dynamic = isfunction(value)
self._dispatch_batches(
self.import_api,
"engage",
profiles_list,
[{}, self.token, operation, value, ignore_alias, dynamic],
)
profile_count = len(profiles_list)
MixpanelUtils.LOGGER.debug(
f"{operation} operation applied to {profile_count} profiles"
)
return profile_count
def people_delete(
self,
profiles=None,
query_params=None,
timezone_offset=None,
ignore_alias=True,
backup=True,
backup_file=None,
):
"""Deletes the specified People profiles with the $delete operation and optionally creates a backup file
:param profiles: Can be a list of profiles or the name of a file containing a JSON array or CSV of profiles.
Alternative to query_params. (Default value = None)
:param query_params: Parameters to query /engage API. Alternative to profiles param. (Default value = None)
:param timezone_offset: UTC offset in hours of project timezone setting, used to calculate as_of_timestamp
parameter for queries that use behaviors. Required if query_params contains behaviors (Default value = None)
:param ignore_alias: True or False (Default value = True)
:param backup: True to create backup file otherwise False (default)
:param backup_file: Optional filename to use for the backup file (Default value = None)
:type profiles: list | str
:type query_params: dict
:type ignore_alias: bool
:type timezone_offset: int | float
:type backup: bool
:type backup_file: str
:return: Number of profiles deleted
:rtype: int
"""
return self.people_operation(
"$delete",
"",
profiles=profiles,
query_params=query_params,
timezone_offset=timezone_offset,
ignore_alias=ignore_alias,
backup=backup,
backup_file=backup_file,
)
def people_set(
self,
value,
profiles=None,
query_params=None,
timezone_offset=None,
ignore_alias=False,
backup=True,
backup_file=None,
):
"""Sets People properties for the specified profiles using the $set operation and optionally creates a backup file
:param value: Can be a static value applied to all profiles or a user-defined function (or lambda) that takes a
profile as its only parameter and returns the value to use for the operation on the given profile
:param profiles: Can be a list of profiles or the name of a file containing a JSON array or CSV of profiles.
Alternative to query_params. (Default value = None)
:param query_params: Parameters to query /engage API. Alternative to profiles param. (Default value = None)
:param timezone_offset: UTC offset in hours of project timezone setting, used to calculate as_of_timestamp
parameter for queries that use behaviors. Required if query_params contains behaviors (Default value = None)
:param ignore_alias: True or False (Default value = False)
:param backup: True to create backup file otherwise False (default)
:param backup_file: Optional filename to use for the backup file (Default value = None)
:type profiles: list | str
:type query_params: dict
:type timezone_offset: int | float
:type ignore_alias: bool
:type backup: bool
:type backup_file: str
:return: Number of profiles operated on
:rtype: int
"""
return self.people_operation(
"$set",
value=value,
profiles=profiles,
query_params=query_params,
timezone_offset=timezone_offset,
ignore_alias=ignore_alias,
backup=backup,
backup_file=backup_file,
)
def people_set_once(
self,
value,
profiles=None,
query_params=None,
timezone_offset=None,
ignore_alias=False,
backup=False,
backup_file=None,
):
"""Sets People properties for the specified profiles only if the properties do not yet exist, using the $set_once
operation and optionally creates a backup file
:param value: Can be a static value applied to all profiles or a user-defined function (or lambda) that takes a
profile as its only parameter and returns the value to use for the operation on the given profile
:param profiles: Can be a list of profiles or the name of a file containing a JSON array or CSV of profiles.
Alternative to query_params. (Default value = None)
:param query_params: Parameters to query /engage API. Alternative to profiles param. (Default value = None)
:param timezone_offset: UTC offset in hours of project timezone setting, used to calculate as_of_timestamp
parameter for queries that use behaviors. Required if query_params contains behaviors (Default value = None)
:param ignore_alias: True or False (Default value = False)
:param backup: True to create backup file otherwise False (default)
:param backup_file: Optional filename to use for the backup file (Default value = None)
:type profiles: list | str
:type query_params: dict
:type timezone_offset: int | float
:type ignore_alias: bool
:type backup: bool
:type backup_file: str
:return: Number of profiles operated on
:rtype: int
"""
return self.people_operation(
"$set_once",
value=value,
profiles=profiles,
query_params=query_params,
timezone_offset=timezone_offset,
ignore_alias=ignore_alias,
backup=backup,
backup_file=backup_file,
)
def people_unset(
self,
value,
profiles=None,
query_params=None,
timezone_offset=None,
ignore_alias=False,
backup=True,
backup_file=None,
):
"""Unsets properties from the specified profiles using the $unset operation and optionally creates a backup file
:param value: Can be a static value applied to all profiles or a user-defined function (or lambda) that takes a
profile as its only parameter and returns the value to use for the operation on the given profile
:param profiles: Can be a list of profiles or the name of a file containing a JSON array or CSV of profiles.
Alternative to query_params. (Default value = None)
:param query_params: Parameters to query /engage API. Alternative to profiles param. (Default value = None)
:param timezone_offset: UTC offset in hours of project timezone setting, used to calculate as_of_timestamp
parameter for queries that use behaviors. Required if query_params contains behaviors (Default value = None)
:param ignore_alias: True or False (Default value = False)
:param backup: True to create backup file otherwise False (default)
:param backup_file: Optional filename to use for the backup file (Default value = None)
:type value: list | (profile) -> list
:type profiles: list | str
:type query_params: dict
:type timezone_offset: int | float
:type ignore_alias: bool
:type backup: bool
:type backup_file: str
:return: Number of profiles operated on
:rtype: int
"""
return self.people_operation(
"$unset",
value=value,
profiles=profiles,
query_params=query_params,
timezone_offset=timezone_offset,
ignore_alias=ignore_alias,
backup=backup,
backup_file=backup_file,
)
def people_add(
self,
value,
profiles=None,
query_params=None,
timezone_offset=None,
ignore_alias=False,
backup=True,
backup_file=None,
):
"""Increments numeric properties on the specified profiles using the $add operation and optionally creates a
backup file
:param value: Can be a static value applied to all profiles or a user-defined function (or lambda) that takes a
profile as its only parameter and returns the value to use for the operation on the given profile
:param profiles: Can be a list of profiles or the name of a file containing a JSON array or CSV of profiles.
Alternative to query_params. (Default value = None)
:param query_params: Parameters to query /engage API. Alternative to profiles param. (Default value = None)
:param timezone_offset: UTC offset in hours of project timezone setting, used to calculate as_of_timestamp
parameter for queries that use behaviors. Required if query_params contains behaviors (Default value = None)
:param ignore_alias: True or False (Default value = False)
:param backup: True to create backup file otherwise False (default)
:param backup_file: Optional filename to use for the backup file (Default value = None)
:type value: dict[str, float] | (profile) -> dict[str, float]
:type profiles: list | str
:type query_params: dict
:type timezone_offset: int | float
:type ignore_alias: bool
:type backup: bool
:type backup_file: str
:return: Number of profiles operated on
:rtype: int
"""
return self.people_operation(
"$add",
value=value,
profiles=profiles,
query_params=query_params,
timezone_offset=timezone_offset,
ignore_alias=ignore_alias,
backup=backup,
backup_file=backup_file,
)
def people_append(
self,
value,
profiles=None,
query_params=None,
timezone_offset=None,
ignore_alias=False,
backup=True,
backup_file=None,
):
"""Appends values to list properties on the specified profiles using the $append operation and optionally creates
a backup file.
:param value: Can be a static value applied to all profiles or a user-defined function (or lambda) that takes a
profile as its only parameter and returns the value to use for the operation on the given profile
:param profiles: Can be a list of profiles or the name of a file containing a JSON array or CSV of profiles.
Alternative to query_params. (Default value = None)
:param query_params: Parameters to query /engage API. Alternative to profiles param. (Default value = None)
:param timezone_offset: UTC offset in hours of project timezone setting, used to calculate as_of_timestamp
parameter for queries that use behaviors. Required if query_params contains behaviors (Default value = None)
:param ignore_alias: True or False (Default value = False)
:param backup: True to create backup file otherwise False (default)
:param backup_file: Optional filename to use for the backup file (Default value = None)
:type value: dict | (profile) -> dict
:type profiles: list | str
:type query_params: dict
:type timezone_offset: int | float
:type ignore_alias: bool
:type backup: bool
:type backup_file: str
:return: Number of profiles operated on
:rtype: int
"""
return self.people_operation(
"$append",
value=value,
profiles=profiles,
query_params=query_params,
timezone_offset=timezone_offset,
ignore_alias=ignore_alias,
backup=backup,
backup_file=backup_file,
)
def people_union(
self,
value,
profiles=None,
query_params=None,
timezone_offset=None,
ignore_alias=False,
backup=True,
backup_file=None,
):
"""Union a list of values with list properties on the specified profiles using the $union operation and optionally
create a backup file
:param value: Can be a static value applied to all profiles or a user-defined function (or lambda) that takes a
profile as its only parameter and returns the value to use for the operation on the given profile
:param profiles: Can be a list of profiles or the name of a file containing a JSON array or CSV of profiles.
Alternative to query_params. (Default value = None)
:param query_params: Parameters to query /engage API. Alternative to profiles param. (Default value = None)
:param timezone_offset: UTC offset in hours of project timezone setting, used to calculate as_of_timestamp
parameter for queries that use behaviors. Required if query_params contains behaviors (Default value = None)
:param ignore_alias: True or False (Default value = False)
:param backup: True to create backup file otherwise False (default)
:param backup_file: Optional filename to use for the backup file (Default value = None)
:type value: dict[str, list] | (profile) -> dict[str, list]
:type profiles: list | str
:type query_params: dict
:type timezone_offset: int | float
:type ignore_alias: bool
:type backup: bool
:type backup_file: str
:return: Number of profiles operated on
:rtype: int
"""
return self.people_operation(
"$union",
value=value,
profiles=profiles,
query_params=query_params,
timezone_offset=timezone_offset,
ignore_alias=ignore_alias,
backup=backup,
backup_file=backup_file,
)
def people_remove(
self,
value,
profiles=None,
query_params=None,
timezone_offset=None,
ignore_alias=False,
backup=True,
backup_file=None,
):
"""Removes values from list properties on the specified profiles using the $remove operation and optionally
creates a backup file
:param value: Can be a static value applied to all profiles or a user-defined function (or lambda) that takes a
profile as its only parameter and returns the value to use for the operation on the given profile
:param profiles: Can be a list of profiles or the name of a file containing a JSON array or CSV of profiles.
Alternative to query_params. (Default value = None)
:param query_params: Parameters to query /engage API. Alternative to profiles param. (Default value = None)
:param timezone_offset: UTC offset in hours of project timezone setting, used to calculate as_of_timestamp
parameter for queries that use behaviors. Required if query_params contains behaviors (Default value = None)
:param ignore_alias: True or False (Default value = False)
:param backup: True to create backup file otherwise False (default)
:param backup_file: Optional filename to use for the backup file (Default value = None)
:type value: dict | (profile) -> dict
:type profiles: list | str
:type query_params: dict
:type timezone_offset: int | float
:type ignore_alias: bool
:type backup: bool
:type backup_file: str
:return: Number of profiles operated on
:rtype: int
"""
return self.people_operation(
"$remove",
value=value,
profiles=profiles,
query_params=query_params,
timezone_offset=timezone_offset,
ignore_alias=ignore_alias,
backup=backup,
backup_file=backup_file,
)
def people_change_property_name(
self,
old_name,
new_name,
profiles=None,
query_params=None,
timezone_offset=None,
ignore_alias=False,
backup=True,
backup_file=None,
unset=True,
):
"""Copies the value of an existing property into a new property and optionally unsets the existing property.
Optionally creates a backup file.
:param old_name: The name of an existing property.
:param new_name: The new name to replace the old_name with
:param profiles: Can be a list of profiles or the name of a file containing a JSON array or CSV of profiles.
Alternative to query_params. (Default value = None)
:param query_params: Parameters to query /engage API. Alternative to profiles param. If both query_params and
profiles are None all profiles with old_name set are targeted. (Default value = None)
:param timezone_offset: UTC offset in hours of project timezone setting, used to calculate as_of_timestamp
parameter for queries that use behaviors. Required if query_params contains behaviors (Default value = None)
:param ignore_alias: True or False (Default value = False)
:param backup: True to create backup file otherwise False (default)
:param backup_file: Optional filename to use for the backup file (Default value = None)
:param unset: Option to unset the old_name property (Default value = True)
:type profiles: list | str
:type query_params: dict
:type timezone_offset: int | float
:type ignore_alias: bool
:type backup: bool
:type backup_file: str
:type unset: bool
:return: Number of profiles operated on
:rtype: int
"""
if profiles is None and query_params is None:
query_params = {"selector": '(defined (properties["' + old_name + '"]))'}
profile_count = self.people_operation(
"$set",
lambda p: {new_name: p["$properties"][old_name]},
profiles=profiles,
query_params=query_params,
timezone_offset=timezone_offset,
ignore_alias=ignore_alias,
backup=backup,
backup_file=backup_file,
)
if unset:
self.people_operation(
"$unset",
[old_name],
profiles=profiles,
query_params=query_params,
timezone_offset=timezone_offset,
ignore_alias=ignore_alias,
backup=False,
)
return profile_count
def people_revenue_property_from_transactions(
self,
profiles=None,
query_params=None,
timezone_offset=None,
ignore_alias=False,
backup=True,
backup_file=None,
):
"""Creates a property named 'Revenue' for the specified profiles by summing their $transaction $amounts and
optionally creates a backup file
:param profiles: Can be a list of profiles or the name of a file containing a JSON array or CSV of profiles.
Alternative to query_params. (Default value = None)
:param query_params: Parameters to query /engage API. Alternative to profiles param. If both query_params and
profiles are None, all profiles with $transactions are targeted. (Default value = None)
:param timezone_offset: UTC offset in hours of project timezone setting, used to calculate as_of_timestamp
parameter for queries that use behaviors. Required if query_params contains behaviors (Default value = None)
:param ignore_alias: True or False (Default value = False)
:param backup: True to create backup file otherwise False (default)
:param backup_file: Optional filename to use for the backup file (Default value = None)
:type profiles: list | str
:type query_params: dict
:type timezone_offset: int | float
:type ignore_alias: bool
:type backup: bool
:type backup_file: str
:return: Number of profiles operated on
:rtype: int
"""
if profiles is None and query_params is None:
query_params = {"selector": '(defined (properties["$transactions"]))'}
return self.people_operation(
"$set",
MixpanelUtils.sum_transactions,
profiles=profiles,
query_params=query_params,
timezone_offset=timezone_offset,
ignore_alias=ignore_alias,
backup=backup,
backup_file=backup_file,
)
def deduplicate_people(
self,
profiles=None,
prop_to_match="$email",
merge_props=False,
case_sensitive=False,
backup=True,
backup_file=None,
):
"""Determines duplicate profiles based on the value of a specified property. The profile with the latest
$last_seen is kept and the others are deleted. Optionally adds any properties from the profiles to be deleted to
the remaining profile using $set_once. Backup files are always created.
:param profiles: Can be a list of profiles or the name of a file containing a JSON array or CSV of profiles. If
this is None all profiles with prop_to_match set will be downloaded. (Default value = None)
:param prop_to_match: Name of property whose value will be used to determine duplicates
(Default value = '$email')
:param merge_props: Option to call $set_once on remaining profile with all props from profiles to be deleted.
This ensures that any properties that existed on the duplicates but not on the remaining profile are
preserved. (Default value = False)
:param case_sensitive: Option to use case sensitive or case insensitive matching (Default value = False)
:param backup: Create a backup file (default True)
:param backup_file: Optional filename to use for the backup file (Default value = None)
:type profiles: list | str
:type prop_to_match: str
:type merge_props: bool
:type case_sensitive: bool
:type backup: bool
:type backup_file: str
:return: Number of profiles deleted
:rtype: int
"""
main_reference = {}
update_profiles = []
delete_profiles = []
if profiles is not None:
profiles_list = MixpanelUtils._list_from_argument(profiles)
else:
# Unless the user provides a list of profiles we only look at profiles which have the prop_to_match set
selector = '(boolean(properties["{}"]) == true)'.format(prop_to_match)
profiles_list = self.query_engage({"where": selector})
if backup:
if backup_file is None:
backup_file = "backup_{:.0f}.json".format(time.time())
self.export_data(profiles_list, backup_file, append_mode=True)
for profile in profiles_list:
try:
match_prop = str(profile["$properties"][prop_to_match])
except UnicodeError:
match_prop = profile["$properties"][prop_to_match].encode("utf-8")
except KeyError:
continue
finally:
try:
if not case_sensitive:
match_prop = match_prop.lower()
except NameError:
pass
# Ensure each value for the prop we are matching on has a key pointing to an array in the main_reference
if not main_reference.get(match_prop):
main_reference[match_prop] = []
# Append each profile to the array under the key corresponding to the value it has for prop we are matching
main_reference[match_prop].append(profile)
for matching_prop, matching_profiles in main_reference.items():
if len(matching_profiles) > 1:
matching_profiles.sort(
key=lambda dupe: MixpanelUtils._dt_from_iso(dupe)
)
# We create a $delete update for each duplicate profile and at the same time create a
# $set_once update for the keeper profile by working through duplicates oldest to newest
if merge_props:
prop_update = {
"$distinct_id": matching_profiles[-1]["$distinct_id"],
"$properties": {},
}
for x in range(len(matching_profiles) - 1):
delete_profiles.append(
{"$distinct_id": matching_profiles[x]["$distinct_id"]}
)
if merge_props:
prop_update["$properties"].update(
matching_profiles[x]["$properties"]
)
# Remove $last_seen from any updates to avoid weirdness
if merge_props and "$last_seen" in prop_update["$properties"]:
del prop_update["$properties"]["$last_seen"]
if merge_props:
update_profiles.append(prop_update)
# The "merge" is really just a $set_once call with all of the properties from the deleted profiles
if merge_props:
self.people_operation(
"$set_once",
lambda p: p["$properties"],
profiles=update_profiles,
ignore_alias=True,
backup=False,
)
return self.people_operation(
"$delete", "", profiles=delete_profiles, ignore_alias=True, backup=False
)
def query_jql(self, script, params=None, format="json"):
"""Query the Mixpanel JQL API
https://mixpanel.com/help/reference/jql/api-reference#api/access
:param script: String containing a JQL script to run
:param params: Optional dict that will be made available to the script as the params global variable.
:param format: Output format can be either 'json' or 'csv'
:type script: str
:type params: dict
:type format: str