forked from mixpanel/mixpanel-utils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path__init__.py
executable file
·1585 lines (1365 loc) · 76.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 urllib # for url encoding
import urllib2 # for sending requests
from httplib import IncompleteRead
import cStringIO
import logging
import gzip
import shutil
import time
import os
import datetime
from inspect import isfunction
from multiprocessing import cpu_count
from multiprocessing.pool import ThreadPool
from paginator import ConcurrentPaginator
from ast import literal_eval
from copy import deepcopy
import csv
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 Mixpanel(object):
"""An object for querying, importing, exporting and modifying Mixpanel data via their various APIs
"""
FORMATTED_API = 'https://mixpanel.com/api'
RAW_API = 'https://data.mixpanel.com/api'
IMPORT_API = 'https://api.mixpanel.com'
BETA_IMPORT_API = 'https://api-beta.mixpanel.com'
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, dataset_id=None, timeout=120, pool_size=None,
read_pool_size=None, max_retries=10, debug=False):
"""Initializes the Mixpanel object
:param api_secret: API Secret for your project
:param token: Project Token for your project, required for imports
:param dataset_id: The name of the dataset to operate on
:param timeout: Time in seconds to wait for HTTP responses
:param pool_size: Number of threads to use for multiprocessing, default is cpu_count * 2
:param read_pool_size: Optional separate number of threads to use just for read operations (i.e. query_engage)
:param max_retries: Maximum number of times to retry when a 503 HTTP response is received
:param debug: Enable debug logging
:type api_secret: str
:type token: str
:type dataset_id: str
:type timeout: int
:type pool_size: int
:type read_pool_size: int
:type max_retries: int
:type debug: bool
"""
self.api_secret = api_secret
self.token = token
self.dataset_id = dataset_id
self.timeout = timeout
if pool_size is None:
# Default number of threads is system dependent
pool_size = cpu_count() * 2
if read_pool_size is None:
read_pool_size = pool_size
self.pool_size = pool_size
self.read_pool_size = read_pool_size
self.max_retries = max_retries
log_level = Mixpanel.LOGGER.getEffectiveLevel()
''' The logger is a singleton for the Mixpanel class, so multiple instances of the Mixpanel class will use the
same logger. Subsequent instances can upgrade the logging level to debug but they cannot downgrade it.
'''
if debug or log_level == 10:
Mixpanel.LOGGER.setLevel(logging.DEBUG)
else:
Mixpanel.LOGGER.setLevel(logging.WARNING)
@staticmethod
def export_data(data, output_file, 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 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 format: str
:type compress: bool
"""
with open(output_file, 'w+') as output:
if format == 'json':
json.dump(data, output)
elif format == 'csv':
Mixpanel._write_items_to_csv(data, output_file)
else:
msg = "Invalid format - must be 'json' or 'csv': format = " + str(format) + '\n' \
+ "Dumping json to " + output_file
Mixpanel.LOGGER.warning(msg)
json.dump(data, output)
if compress:
Mixpanel._gzip_file(output_file)
os.remove(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, 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 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 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 == Mixpanel.IMPORT_API or base_url == Mixpanel.BETA_IMPORT_API:
base = [base_url]
else:
base = [base_url, str(Mixpanel.VERSION)]
request_url = '/'.join(base + path_components)
encoded_params = Mixpanel._unicode_urlencode(params)
# Set up request url and body based on HTTP method and endpoint
if method == 'GET' or method == 'DELETE':
data = None
request_url += '?' + encoded_params
else:
data = encoded_params
if base_url == self.IMPORT_API or 'import-people' in path_components or 'import-events' in path_components:
data += '&verbose=1'
# Uncomment the line below to log the request body data
# Mixpanel.LOGGER.debug(method + ' data: ' + data)
Mixpanel.LOGGER.debug("Request Method: " + method)
Mixpanel.LOGGER.debug("Request URL: " + request_url)
if headers is None:
headers = {}
headers['Authorization'] = 'Basic {encoded_secret}'.format(
encoded_secret=base64.b64encode(self.api_secret + ':'))
request = urllib2.Request(request_url, data, headers)
Mixpanel.LOGGER.debug("Request Headers: " + json.dumps(headers))
# This is the only way to use HTTP methods other than GET or POST with urllib2
if method != 'GET' and method != 'POST':
request.get_method = lambda: method
try:
response = urllib2.urlopen(request, timeout=self.timeout)
except urllib2.HTTPError as e:
Mixpanel.LOGGER.warning('The server couldn\'t fulfill the request.')
Mixpanel.LOGGER.warning('Error code: ' + str(e.code))
Mixpanel.LOGGER.warning('Reason: ' + str(e.reason))
if hasattr(e, 'read'):
Mixpanel.LOGGER.warning('Response: ' + e.read())
except urllib2.URLError as e:
Mixpanel.LOGGER.warning('We failed to reach a server.')
Mixpanel.LOGGER.warning('Reason: ' + str(e.reason))
if hasattr(e, 'read'):
Mixpanel.LOGGER.warning('Response: ' + e.read())
else:
try:
# If the response is gzipped we go ahead and decompress
if response.info().get('Content-Encoding') == 'gzip':
buf = cStringIO.StringIO(response.read())
f = gzip.GzipFile(fileobj=buf)
response_data = f.read()
else:
response_data = response.read()
return response_data
except IncompleteRead as e:
Mixpanel.LOGGER.warning("Response data is incomplete. Attempting retry #" + str(retries + 1))
self.request(base_url, path_components, params, method=method, retries=retries + 1)
else:
Mixpanel.LOGGER.warning("Maximum retries reached. Request failed.")
Mixpanel.LOGGER.warning("The server may be overloaded. Try again later.")
return
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
"""
assert self.token, "Project token required for People operation!"
if profiles is not None and query_params is not None:
Mixpanel.LOGGER.warning("profiles and query_params both provided, please use one or the other")
return
if profiles is not None:
profiles_list = Mixpanel._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_" + str(int(time.time())) + ".json"
self.export_data(profiles_list, backup_file)
# 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])
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 timezone_offset: int | float
:type backup: bool
:type backup_file: str
"""
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
"""
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
"""
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
"""
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
"""
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
"""
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
"""
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
"""
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
"""
if profiles is None and query_params is None:
query_params = {'selector': '(defined (properties["' + old_name + '"]))'}
self.people_operation('$set', lambda p: {new_name: p['$properties'][old_name]}, 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)
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
"""
if profiles is None and query_params is None:
query_params = {'selector': '(defined (properties["$transactions"]))'}
self.people_operation('$set', Mixpanel.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: 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 prop_to_match: str
:type merge_props: bool
:type case_sensitive: bool
:type backup: bool
:type backup_file: str
"""
main_reference = {}
update_profiles = []
delete_profiles = []
if profiles is not None:
profiles_list = Mixpanel._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["' + prop_to_match + '"]) == true)'
profiles_list = self.query_engage({'where': selector})
if backup:
if backup_file is None:
backup_file = "backup_" + str(int(time.time())) + ".json"
self.export_data(profiles_list, backup_file)
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.iteritems():
if len(matching_profiles) > 1:
matching_profiles.sort(key=lambda dupe: Mixpanel._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 xrange(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)
self.people_operation('$delete', '', profiles=delete_profiles, ignore_alias=True, backup=False)
def query_jql(self, script, params=None):
"""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.
:type script: str
:type params: dict
"""
query_params = {"script": script}
if params is not None:
query_params["params"] = json.dumps(params)
response = self.request(Mixpanel.FORMATTED_API, ['jql'], query_params, method='POST')
return json.loads(response)
def jql_operation(self, jql_script, people_operation, update_value=lambda x: x['value'], jql_params=None,
ignore_alias=False, backup=True, backup_file=None):
"""Perform a JQL query to return a JSON array of objects that can then be used to dynamically construct People
updates via the update_value
:param jql_script: String containing a JQL script to run. The result should be an array of objects. Those
objects should contain at least a $distinct_id key
:param people_operation: A Mixpanel People update operation
:param update_value: Can be a static value applied to all $distinct_ids or a user defined function or lambda
that expects a dict containing at least a $distinct_id (or distinct_id) key, as its only parameter and
returns the value to use for the update on that $distinct_id. The default is a lambda that returns the
value at the dict's 'value' key.
:param jql_params: Optional dict that will be made available to the script as the params global variable.
(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 jql_script: str
:type people_operation: str
:type jql_params: dict
:type ignore_alias: bool
:type backup: bool
:type backup_file: str
"""
jql_data = self.query_jql(jql_script, jql_params)
if backup:
if backup_file is None:
backup_file = "backup_" + str(int(time.time())) + ".json"
# backs up ALL profiles, not just those affected by the JQL since jql_data might not contain full profiles
self.export_people(backup_file)
self.people_operation(people_operation, update_value, profiles=jql_data, ignore_alias=ignore_alias,
backup=False)
def event_counts_to_people(self, from_date, events):
"""Sets the per user count of events in events list param as People properties
:param from_date: A datetime or a date string of format YYYY-MM-DD to begin counting from
:param events: A list of strings of event names to be counted
:type from_date: datetime | str
:type events: list[str]
"""
jql_script = "function main() { var event_selectors_array = []; _.each(params.events, function(e) {" \
"event_selectors_array.push({'event': e});}); return join(Events({from_date: params.from_date," \
"to_date: params.to_date, event_selectors: event_selectors_array}), People(), {type: 'inner'})" \
".groupByUser(['event.name'], mixpanel.reducer.count()).map(function(row) {v = {}; v[row.key[1]]" \
" = row.value; return {$distinct_id: row.key[0],value: v};});}"
to_date = datetime.datetime.today().strftime('%Y-%m-%d')
if isinstance(from_date, datetime.date):
from_date = from_date.strftime('%Y-%m-%d')
params = {'from_date': from_date, 'to_date': to_date, 'events': events}
self.jql_operation(jql_script, '$set', jql_params=params, backup=False)
def query_export(self, params, add_gzip_header=False):
"""Queries the /export API and returns a list of Mixpanel event dicts
https://mixpanel.com/help/reference/exporting-raw-data#export-api-reference
:param params: Parameters to use for the /export API request
:param add_gzip_header: Adds 'Accept-encoding: gzip' to the request headers (Default value = False)
:type params: dict
:type add_gzip_header: bool
:return: A list of Mixpanel event dicts
:rtype: list
"""
headers = {}
if add_gzip_header:
headers = {'Accept-encoding': 'gzip'}
response = self.request(Mixpanel.RAW_API, ['export'], params, headers=headers)
try:
file_like_object = cStringIO.StringIO(response)
except TypeError as e:
Mixpanel.LOGGER.warning('Error querying /export API')
return
raw_data = file_like_object.getvalue().split('\n')
# Remove the last line which is only a newline
raw_data.pop()
events = []
for line in raw_data:
events.append(json.loads(line))
return events
def query_engage(self, params=None, timezone_offset=None):
"""Queries the /engage API and returns a list of Mixpanel People profile dicts
https://mixpanel.com/help/reference/data-export-api#people-analytics
:param params: Parameters to use for the /engage API request. Defaults to returning all profiles.
(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)
:type params: dict
:type timezone_offset: int | float
:raise RuntimeError: Raises Runtime error if params include behaviors and timezone_offset is None
:return: A list of Mixpanel People profile dicts
:rtype: list
"""
if params is None:
params = {}
if 'behaviors' in params and timezone_offset is None:
raise RuntimeError("timezone_offset required if params include behaviors")
elif 'behaviors' in params:
params['as_of_timestamp'] = int(int(time.time()) + (timezone_offset * 3600))
engage_paginator = ConcurrentPaginator(self._get_engage_page, concurrency=self.read_pool_size)
return engage_paginator.fetch_all(params)
def export_events(self, output_file, params, format='json', timezone_offset=None, add_gzip_header=False,
compress=False):
"""Queries the /export API and writes the Mixpanel event data to disk as a JSON or CSV file. Optionally gzip file.
https://mixpanel.com/help/reference/exporting-raw-data#export-api-reference
:param output_file: Name of the file to write to
:param params: Parameters to use for the /export API request
:param format: Can be either 'json' or 'csv' (Default value = 'json')
:param timezone_offset: UTC offset in hours of export project timezone setting. If set, used to convert event
timestamps from project time to UTC
:param add_gzip_header: Adds 'Accept-encoding: gzip' to the request headers (Default value = False)
:param compress: Option to gzip output_file (Default value = False)
:type output_file: str
:type params: dict
:type format: str
:type timezone_offset: int | float
:type add_gzip_header: bool
:type compress: bool
"""
# Increase timeout to 20 minutes if it's still set to default, /export requests can take a long time
timeout_backup = self.timeout
if self.timeout == 120:
self.timeout = 1200
events = self.query_export(params, add_gzip_header=add_gzip_header)
if timezone_offset is not None:
# Convert timezone_offset from hours to seconds
timezone_offset = timezone_offset * 3600
for event in events:
event['properties']['time'] = int(event['properties']['time'] - timezone_offset)
Mixpanel.export_data(events, output_file, format=format, compress=compress)
# If we modified the default timeout above, set it back
if timeout_backup == 120:
self.timeout = timeout_backup
def export_people(self, output_file, params=None, timezone_offset=None, format='json', compress=False):
"""Queries the /engage API and writes the Mixpanel People profile data to disk as a JSON or CSV file. Optionally
gzip file.
https://mixpanel.com/help/reference/data-export-api#people-analytics
:param output_file: Name of the file to write to
:param params: Parameters to use for the /engage API request (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 format: (Default value = 'json')
:param compress: (Default value = False)
:type output_file: str
:type params: dict
:type timezone_offset: int | float
:type format: str
:type compress: bool
"""
if params is None:
params = {}
profiles = self.query_engage(params, timezone_offset=timezone_offset)
Mixpanel.export_data(profiles, output_file, format=format, compress=compress)
def import_events(self, data, timezone_offset, dataset_version=None):
"""Imports a list of Mixpanel event dicts or a file containing a JSON array of Mixpanel events.
https://mixpanel.com/help/reference/importing-old-events
:param data: A list of Mixpanel event dicts or the name of a file containing a JSON array or CSV of Mixpanel
events
:param timezone_offset: UTC offset (number of hours) for the project that exported the data. Used to convert the
event timestamps back to UTC prior to import.
:param dataset_version: Dataset version to import into, required if self.dataset_id is set, otherwise
optional
:type data: list | str
:type timezone_offset: int | float
:type dataset_version: str
"""
if self.dataset_id or dataset_version:
if self.dataset_id and dataset_version:
endpoint = 'import-events'
base_url = self.BETA_IMPORT_API
else:
Mixpanel.LOGGER.warning('Must supply both, dataset_version and dataset_id in init, or neither!')
return
else:
endpoint = 'import'
base_url = self.IMPORT_API
self._import_data(data, base_url, endpoint, timezone_offset=timezone_offset, dataset_id=self.dataset_id,
dataset_version=dataset_version)
def import_people(self, data, ignore_alias=False, dataset_version=None, raw_record_import=False):
"""Imports a list of Mixpanel People profile dicts (or raw API update operations) or a file containing a JSON
array or CSV of Mixpanel People profiles (or raw API update operations).
https://mixpanel.com/help/reference/http#people-analytics-updates
:param data: A list of Mixpanel People profile dicts (or /engage API update operations) or the name of a file
containing a JSON array of Mixpanel People profiles (or /engage API update operations).
:param ignore_alias: Option to bypass Mixpanel's alias lookup table (Default value = False)
:param dataset_version: Dataset version to import into, required if self.dataset_id is set, otherwise
optional
:param raw_record_import: Set this to True if data is a list of API update operations (Default value = False)
:type data: list | str
:type ignore_alias: bool
:type dataset_version: str
"""
if self.dataset_id or dataset_version:
if self.dataset_id and dataset_version:
endpoint = 'import-people'
base_url = self.BETA_IMPORT_API
else:
Mixpanel.LOGGER.warning('Must supply both, dataset_version and dataset_id in init, or neither!')
return
else:
endpoint = 'engage'
base_url = self.IMPORT_API
self._import_data(data, base_url, endpoint, ignore_alias=ignore_alias, dataset_id=self.dataset_id,
dataset_version=dataset_version, raw_record_import=raw_record_import)
def list_all_dataset_versions(self):
"""Returns a list of all dataset version objects for the current dataset_id
:return: A list of dataset version objects
:rtype: list
"""
assert self.dataset_id, 'dataset_id required!'
return self._datasets_request('GET', dataset_id=self.dataset_id, versions_request=True)
def create_dataset_version(self):
"""Creates a new dataset version for the current dataset_id. Note that dataset_id must already exist!
:return: Returns a dataset version object. This version of the dataset is writable by default while the ready
and readable flags in the version state are false.
:rtype: dict
"""
assert self.dataset_id, 'dataset_id required!'
return self._datasets_request('POST', dataset_id=self.dataset_id, versions_request=True)
def update_dataset_version(self, version_id, state):
"""Updates a specific version_id for the current dataset_id. Currently, users can only update the state
of a given dataset version. Only the readable and writable boolean fields can be updated.
:param version_id: version_id of the version to be updated
:param state: State object with fields to be updated
:type version_id: str
:type state: dict
:return: True for success, False otherwise.
:rtype: bool
"""
assert self.dataset_id, 'dataset_id required!'
assert 'writable' in state, 'state must specify writable field!'
assert 'readable' in state, 'state must specify readable field!'
return self._datasets_request('PATCH', dataset_id=self.dataset_id, versions_request=True,
version_id=version_id, state=state)
def mark_dataset_version_readable(self, version_id):
"""Updates the readable field of the specified version_id's state to true for the current dataset_id
:param version_id: version_id of the version to be marked readable
:type version_id: str
:return: True for success, False otherwise.
:rtype: bool
"""
Mixpanel.LOGGER.debug('Fetching current version...')
version = self.list_dataset_version(version_id)
if 'state' in version:
writable = version['state']['writable']
state = {'writable': writable, 'readable': True}
Mixpanel.LOGGER.debug('Updating state with: ' + str(state))
self.update_dataset_version(version_id, state)
else:
Mixpanel.LOGGER.warning('Failed to get dataset version object for version_id ' + str(
version_id) + 'of dataset ' + self.dataset_id)
return False
def delete_dataset_version(self, version_id):
"""Deletes the version with version_id of the current dataset_id
:param version_id: version_id of the version to be deleted
:type version_id: str
:return: True for success, False otherwise.
:rtype: bool
"""
assert self.dataset_id, 'dataset_id required!'
return self._datasets_request('DELETE', dataset_id=self.dataset_id, versions_request=True,
version_id=version_id)
def list_dataset_version(self, version_id):
"""Returns the dataset version object with the specified version_id for the current dataset_id
:param version_id: version_id of the dataset version object to return
:type version_id: str
:return: Returns a dataset version object
:rtype: dict
"""
assert self.dataset_id, 'dataset_id required!'
return self._datasets_request('GET', dataset_id=self.dataset_id, versions_request=True,
version_id=version_id)
def wait_until_dataset_version_ready(self, version_id):
"""Polls the ready state of the specified version_id for the current dataset_id every 60 seconds until it's True
:param version_id: version_id of the dataset_version to check if ready
:type version_id: str
:return: Returns True once the dataset version's ready field is true. Returns False if the dataset version isn't
found
:rtype: bool
"""