-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathclient.py
More file actions
2350 lines (2056 loc) · 83.6 KB
/
client.py
File metadata and controls
2350 lines (2056 loc) · 83.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
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 atexit
import logging
import os
import sys
import warnings
from datetime import datetime, timedelta
from typing import Any, Dict, Optional, Union
from uuid import uuid4
from dateutil.tz import tzutc
from six import string_types
from typing_extensions import Unpack
from posthog.args import ID_TYPES, ExceptionArg, OptionalCaptureArgs, OptionalSetArgs
from posthog.consumer import Consumer
from posthog.contexts import (
_get_current_context,
get_capture_exception_code_variables_context,
get_code_variables_ignore_patterns_context,
get_code_variables_mask_patterns_context,
get_context_device_id,
get_context_distinct_id,
get_context_session_id,
new_context,
)
from posthog.exception_capture import ExceptionCapture
from posthog.exception_utils import (
DEFAULT_CODE_VARIABLES_IGNORE_PATTERNS,
DEFAULT_CODE_VARIABLES_MASK_PATTERNS,
exc_info_from_error,
exception_is_already_captured,
exceptions_from_error_tuple,
handle_in_app,
mark_exception_as_captured,
try_attach_code_variables_to_frames,
)
from posthog.feature_flags import (
InconclusiveMatchError,
RequiresServerEvaluation,
match_feature_flag_properties,
resolve_bucketing_value,
)
from posthog.flag_definition_cache import (
FlagDefinitionCacheData,
FlagDefinitionCacheProvider,
)
from posthog.poller import Poller
from posthog.request import (
DEFAULT_HOST,
APIError,
QuotaLimitError,
RequestsConnectionError,
RequestsTimeout,
batch_post,
determine_server_host,
flags,
get,
remote_config,
)
from posthog.types import (
FeatureFlag,
FeatureFlagError,
FeatureFlagResult,
FlagMetadata,
FlagsAndPayloads,
FlagsResponse,
FlagValue,
SendFeatureFlagsOptions,
normalize_flags_response,
to_flags_and_payloads,
to_payloads,
to_values,
)
from posthog.utils import (
FlagCache,
RedisFlagCache,
SizeLimitedDict,
clean,
guess_timezone,
system_context,
)
from posthog.version import VERSION
try:
import queue
except ImportError:
import Queue as queue
MAX_DICT_SIZE = 50_000
def get_identity_state(passed) -> tuple[str, bool]:
"""Returns the distinct id to use, and whether this is a personless event or not"""
stringified = stringify_id(passed)
if stringified and len(stringified):
return (stringified, False)
context_id = get_context_distinct_id()
if context_id:
return (context_id, False)
return (str(uuid4()), True)
def add_context_tags(properties):
properties = properties or {}
current_context = _get_current_context()
if current_context:
context_tags = current_context.collect_tags()
properties["$context_tags"] = set(context_tags.keys())
# We want explicitly passed properties to override context tags
context_tags.update(properties)
properties = context_tags
if "$session_id" not in properties and get_context_session_id():
properties["$session_id"] = get_context_session_id()
return properties
def no_throw(default_return=None):
"""
Decorator to prevent raising exceptions from public API methods.
Note that this doesn't prevent errors from propagating via `on_error`.
Exceptions will still be raised if the debug flag is enabled.
Args:
default_return: Value to return on exception (default: None)
"""
def decorator(func):
from functools import wraps
@wraps(func)
def wrapper(self, *args, **kwargs):
try:
return func(self, *args, **kwargs)
except Exception as e:
if self.debug:
raise e
self.log.exception(f"Error in {func.__name__}: {e}")
return default_return
return wrapper
return decorator
class Client(object):
"""
This is the SDK reference for the PostHog Python SDK.
You can learn more about example usage in the [Python SDK documentation](/docs/libraries/python).
You can also follow [Flask](/docs/libraries/flask) and [Django](/docs/libraries/django)
guides to integrate PostHog into your project.
Examples:
```python
from posthog import Posthog
posthog = Posthog('<ph_project_api_key>', host='<ph_client_api_host>')
posthog.debug = True
if settings.TEST:
posthog.disabled = True
```
"""
log = logging.getLogger("posthog")
def __init__(
self,
project_api_key: str,
host=None,
debug=False,
max_queue_size=10000,
send=True,
on_error=None,
flush_at=100,
flush_interval=0.5,
gzip=False,
max_retries=3,
sync_mode=False,
timeout=15,
thread=1,
poll_interval=30,
personal_api_key=None,
disabled=False,
disable_geoip=True,
historical_migration=False,
feature_flags_request_timeout_seconds=3,
super_properties=None,
enable_exception_autocapture=False,
log_captured_exceptions=False,
project_root=None,
privacy_mode=False,
before_send=None,
flag_fallback_cache_url=None,
enable_local_evaluation=True,
flag_definition_cache_provider: Optional[FlagDefinitionCacheProvider] = None,
capture_exception_code_variables=False,
code_variables_mask_patterns=None,
code_variables_ignore_patterns=None,
in_app_modules: list[str] | None = None,
):
"""
Initialize a new PostHog client instance.
Args:
project_api_key: The project API key.
host: The host to use for the client.
debug: Whether to enable debug mode.
Examples:
```python
from posthog import Posthog
posthog = Posthog('<ph_project_api_key>', host='<ph_app_host>')
```
Category:
Initialization
"""
self.queue = queue.Queue(max_queue_size)
# api_key: This should be the Team API Key (token), public
self.api_key = project_api_key
self.on_error = on_error
self.debug = debug
self.send = send
self.sync_mode = sync_mode
# Used for session replay URL generation - we don't want the server host here.
self.raw_host = host or DEFAULT_HOST
self.host = determine_server_host(host)
self.gzip = gzip
self.timeout = timeout
self._feature_flags = None # private variable to store flags
self.feature_flags_by_key = None
self.group_type_mapping: Optional[dict[str, str]] = None
self.cohorts: Optional[dict[str, Any]] = None
self.poll_interval = poll_interval
self.feature_flags_request_timeout_seconds = (
feature_flags_request_timeout_seconds
)
self.poller = None
self.distinct_ids_feature_flags_reported = SizeLimitedDict(MAX_DICT_SIZE, set)
self.flag_cache = self._initialize_flag_cache(flag_fallback_cache_url)
self.flag_definition_version = 0
self._flags_etag: Optional[str] = None
self._flag_definition_cache_provider = flag_definition_cache_provider
self.disabled = disabled
self.disable_geoip = disable_geoip
self.historical_migration = historical_migration
self.super_properties = super_properties
self.enable_exception_autocapture = enable_exception_autocapture
self.log_captured_exceptions = log_captured_exceptions
self.exception_capture = None
self.privacy_mode = privacy_mode
self.enable_local_evaluation = enable_local_evaluation
self.capture_exception_code_variables = capture_exception_code_variables
self.code_variables_mask_patterns = (
code_variables_mask_patterns
if code_variables_mask_patterns is not None
else DEFAULT_CODE_VARIABLES_MASK_PATTERNS
)
self.code_variables_ignore_patterns = (
code_variables_ignore_patterns
if code_variables_ignore_patterns is not None
else DEFAULT_CODE_VARIABLES_IGNORE_PATTERNS
)
self.in_app_modules = in_app_modules
if project_root is None:
try:
project_root = os.getcwd()
except Exception:
project_root = None
self.project_root = project_root
# personal_api_key: This should be a generated Personal API Key, private
self.personal_api_key = personal_api_key
if debug:
# Ensures that debug level messages are logged when debug mode is on.
# Otherwise, defaults to WARNING level. See https://docs.python.org/3/howto/logging.html#what-happens-if-no-configuration-is-provided
logging.basicConfig()
self.log.setLevel(logging.DEBUG)
else:
self.log.setLevel(logging.WARNING)
if before_send is not None:
if callable(before_send):
self.before_send = before_send
else:
self.log.warning("before_send is not callable, it will be ignored")
self.before_send = None
else:
self.before_send = None
if self.enable_exception_autocapture:
self.exception_capture = ExceptionCapture(self)
if sync_mode:
self.consumers = None
else:
# On program exit, allow the consumer thread to exit cleanly.
# This prevents exceptions and a messy shutdown when the
# interpreter is destroyed before the daemon thread finishes
# execution. However, it is *not* the same as flushing the queue!
# To guarantee all messages have been delivered, you'll still need
# to call flush().
if send:
atexit.register(self.join)
self.consumers = []
for _ in range(thread):
consumer = Consumer(
self.queue,
self.api_key,
host=self.host,
on_error=on_error,
flush_at=flush_at,
flush_interval=flush_interval,
gzip=gzip,
retries=max_retries,
timeout=timeout,
historical_migration=historical_migration,
)
self.consumers.append(consumer)
# if we've disabled sending, just don't start the consumer
if send:
consumer.start()
def new_context(self, fresh=False, capture_exceptions=True):
"""
Create a new context for managing shared state. Learn more about [contexts](/docs/libraries/python#contexts).
Args:
fresh: Whether to create a fresh context that doesn't inherit from parent.
capture_exceptions: Whether to automatically capture exceptions in this context.
Examples:
```python
with posthog.new_context():
identify_context('<distinct_id>')
posthog.capture('event_name')
```
Category:
Contexts
"""
return new_context(
fresh=fresh, capture_exceptions=capture_exceptions, client=self
)
@property
def feature_flags(self):
"""
Get the local evaluation feature flags.
"""
return self._feature_flags
@feature_flags.setter
def feature_flags(self, flags):
"""
Set the local evaluation feature flags.
"""
self._feature_flags = flags or []
self.feature_flags_by_key = {
flag["key"]: flag
for flag in self._feature_flags
if flag.get("key") is not None
}
assert self.feature_flags_by_key is not None, (
"feature_flags_by_key should be initialized when feature_flags is set"
)
def get_feature_variants(
self,
distinct_id,
groups=None,
person_properties=None,
group_properties=None,
disable_geoip=None,
flag_keys_to_evaluate: Optional[list[str]] = None,
device_id: Optional[str] = None,
) -> dict[str, Union[bool, str]]:
"""
Get feature flag variants for a user by calling decide.
Args:
distinct_id: The distinct ID of the user.
groups: A dictionary of group information.
person_properties: A dictionary of person properties.
group_properties: A dictionary of group properties.
disable_geoip: Whether to disable GeoIP for this request.
flag_keys_to_evaluate: A list of specific flag keys to evaluate. If provided,
only these flags will be evaluated, improving performance.
device_id: The device ID for this request.
Category:
Feature flags
"""
resp_data = self.get_flags_decision(
distinct_id,
groups,
person_properties,
group_properties,
disable_geoip,
flag_keys_to_evaluate,
device_id=device_id,
)
return to_values(resp_data) or {}
def get_feature_payloads(
self,
distinct_id,
groups=None,
person_properties=None,
group_properties=None,
disable_geoip=None,
flag_keys_to_evaluate: Optional[list[str]] = None,
device_id: Optional[str] = None,
) -> dict[str, str]:
"""
Get feature flag payloads for a user by calling decide.
Args:
distinct_id: The distinct ID of the user.
groups: A dictionary of group information.
person_properties: A dictionary of person properties.
group_properties: A dictionary of group properties.
disable_geoip: Whether to disable GeoIP for this request.
flag_keys_to_evaluate: A list of specific flag keys to evaluate. If provided,
only these flags will be evaluated, improving performance.
device_id: The device ID for this request.
Examples:
```python
payloads = posthog.get_feature_payloads('<distinct_id>')
```
Category:
Feature flags
"""
resp_data = self.get_flags_decision(
distinct_id,
groups,
person_properties,
group_properties,
disable_geoip,
flag_keys_to_evaluate,
device_id=device_id,
)
return to_payloads(resp_data) or {}
def get_feature_flags_and_payloads(
self,
distinct_id,
groups=None,
person_properties=None,
group_properties=None,
disable_geoip=None,
flag_keys_to_evaluate: Optional[list[str]] = None,
device_id: Optional[str] = None,
) -> FlagsAndPayloads:
"""
Get feature flags and payloads for a user by calling decide.
Args:
distinct_id: The distinct ID of the user.
groups: A dictionary of group information.
person_properties: A dictionary of person properties.
group_properties: A dictionary of group properties.
disable_geoip: Whether to disable GeoIP for this request.
flag_keys_to_evaluate: A list of specific flag keys to evaluate. If provided,
only these flags will be evaluated, improving performance.
device_id: The device ID for this request.
Examples:
```python
result = posthog.get_feature_flags_and_payloads('<distinct_id>')
```
Category:
Feature flags
"""
resp = self.get_flags_decision(
distinct_id,
groups,
person_properties,
group_properties,
disable_geoip,
flag_keys_to_evaluate,
device_id=device_id,
)
return to_flags_and_payloads(resp)
def get_flags_decision(
self,
distinct_id: Optional[ID_TYPES] = None,
groups: Optional[dict] = None,
person_properties=None,
group_properties=None,
disable_geoip=None,
flag_keys_to_evaluate: Optional[list[str]] = None,
device_id: Optional[str] = None,
) -> FlagsResponse:
"""
Get feature flags decision.
Args:
distinct_id: The distinct ID of the user.
groups: A dictionary of group information.
person_properties: A dictionary of person properties.
group_properties: A dictionary of group properties.
disable_geoip: Whether to disable GeoIP for this request.
flag_keys_to_evaluate: A list of specific flag keys to evaluate. If provided,
only these flags will be evaluated, improving performance.
device_id: The device ID for this request.
Examples:
```python
decision = posthog.get_flags_decision('user123')
```
Category:
Feature flags
"""
groups = groups or {}
person_properties = person_properties or {}
group_properties = group_properties or {}
if distinct_id is None:
distinct_id = get_context_distinct_id()
if device_id is None:
device_id = get_context_device_id()
if disable_geoip is None:
disable_geoip = self.disable_geoip
if not groups:
groups = {}
request_data = {
"distinct_id": distinct_id,
"groups": groups,
"person_properties": person_properties,
"group_properties": group_properties,
"geoip_disable": disable_geoip,
"device_id": device_id,
}
if flag_keys_to_evaluate:
request_data["flag_keys_to_evaluate"] = flag_keys_to_evaluate
resp_data = flags(
self.api_key,
self.host,
timeout=self.feature_flags_request_timeout_seconds,
**request_data,
)
return normalize_flags_response(resp_data)
@no_throw()
def capture(
self, event: str, **kwargs: Unpack[OptionalCaptureArgs]
) -> Optional[str]:
"""
Captures an event manually. [Learn about capture best practices](https://posthog.com/docs/product-analytics/capture-events)
Args:
event: The event name to capture.
distinct_id: The distinct ID of the user.
properties: A dictionary of properties to include with the event.
timestamp: The timestamp of the event.
uuid: A unique identifier for the event.
groups: A dictionary of group information.
send_feature_flags: Whether to send feature flags with the event.
disable_geoip: Whether to disable GeoIP for this event.
Examples:
```python
# Anonymous event
posthog.capture('some-anon-event')
```
```python
# Context usage
from posthog import identify_context, new_context
with new_context():
identify_context('distinct_id_of_the_user')
posthog.capture('user_signed_up')
posthog.capture('user_logged_in')
posthog.capture('some-custom-action', distinct_id='distinct_id_of_the_user')
```
```python
# Set event properties
posthog.capture(
"user_signed_up",
distinct_id="distinct_id_of_the_user",
properties={
"login_type": "email",
"is_free_trial": "true"
}
)
```
```python
# Page view event
posthog.capture('$pageview', distinct_id="distinct_id_of_the_user", properties={'$current_url': 'https://example.com'})
```
Category:
Capture
"""
distinct_id = kwargs.get("distinct_id", None)
properties = kwargs.get("properties", None)
timestamp = kwargs.get("timestamp", None)
uuid = kwargs.get("uuid", None)
groups = kwargs.get("groups", None)
send_feature_flags = kwargs.get("send_feature_flags", False)
disable_geoip = kwargs.get("disable_geoip", None)
properties = {**(properties or {}), **system_context()}
properties = add_context_tags(properties)
assert properties is not None # Type hint for mypy
(distinct_id, personless) = get_identity_state(distinct_id)
if personless and "$process_person_profile" not in properties:
properties["$process_person_profile"] = False
msg = {
"properties": properties,
"timestamp": timestamp,
"distinct_id": distinct_id,
"event": event,
"uuid": uuid,
}
if groups:
properties["$groups"] = groups
extra_properties: dict[str, Any] = {}
feature_variants: Optional[dict[str, Union[bool, str]]] = {}
# Parse and normalize send_feature_flags parameter
flag_options = self._parse_send_feature_flags(send_feature_flags)
if flag_options["should_send"]:
try:
if flag_options["only_evaluate_locally"] is True:
# Local evaluation explicitly requested
feature_variants = self.get_all_flags(
distinct_id,
groups=(groups or {}),
person_properties=flag_options["person_properties"],
group_properties=flag_options["group_properties"],
disable_geoip=disable_geoip,
only_evaluate_locally=True,
flag_keys_to_evaluate=flag_options["flag_keys_filter"],
)
elif flag_options["only_evaluate_locally"] is False:
# Remote evaluation explicitly requested
feature_variants = self.get_feature_variants(
distinct_id,
groups,
person_properties=flag_options["person_properties"],
group_properties=flag_options["group_properties"],
disable_geoip=disable_geoip,
flag_keys_to_evaluate=flag_options["flag_keys_filter"],
)
elif self.feature_flags:
# Local flags available, prefer local evaluation
feature_variants = self.get_all_flags(
distinct_id,
groups=(groups or {}),
person_properties=flag_options["person_properties"],
group_properties=flag_options["group_properties"],
disable_geoip=disable_geoip,
only_evaluate_locally=True,
flag_keys_to_evaluate=flag_options["flag_keys_filter"],
)
else:
# Fall back to remote evaluation
feature_variants = self.get_feature_variants(
distinct_id,
groups,
person_properties=flag_options["person_properties"],
group_properties=flag_options["group_properties"],
disable_geoip=disable_geoip,
flag_keys_to_evaluate=flag_options["flag_keys_filter"],
)
except Exception as e:
self.log.exception(
f"[FEATURE FLAGS] Unable to get feature variants: {e}"
)
for feature, variant in (feature_variants or {}).items():
extra_properties[f"$feature/{feature}"] = variant
active_feature_flags = [
key
for (key, value) in (feature_variants or {}).items()
if value is not False
]
if active_feature_flags:
extra_properties["$active_feature_flags"] = active_feature_flags
if extra_properties:
properties = {**extra_properties, **properties}
msg["properties"] = properties
return self._enqueue(msg, disable_geoip)
def _parse_send_feature_flags(self, send_feature_flags) -> SendFeatureFlagsOptions:
"""
Parse and normalize send_feature_flags parameter into a standard format.
Args:
send_feature_flags: Either bool or SendFeatureFlagsOptions dict
Returns:
SendFeatureFlagsOptions: Normalized options with keys: should_send, only_evaluate_locally,
person_properties, group_properties, flag_keys_filter
Raises:
TypeError: If send_feature_flags is not bool or dict
"""
if isinstance(send_feature_flags, dict):
return {
"should_send": True,
"only_evaluate_locally": send_feature_flags.get(
"only_evaluate_locally"
),
"person_properties": send_feature_flags.get("person_properties"),
"group_properties": send_feature_flags.get("group_properties"),
"flag_keys_filter": send_feature_flags.get("flag_keys_filter"),
}
elif isinstance(send_feature_flags, bool):
return {
"should_send": send_feature_flags,
"only_evaluate_locally": None,
"person_properties": None,
"group_properties": None,
"flag_keys_filter": None,
}
else:
raise TypeError(
f"Invalid type for send_feature_flags: {type(send_feature_flags)}. "
f"Expected bool or dict."
)
@no_throw()
def set(self, **kwargs: Unpack[OptionalSetArgs]) -> Optional[str]:
"""
Set properties on a person profile.
Args:
distinct_id: The distinct ID of the user.
properties: A dictionary of properties to set.
timestamp: The timestamp of the event.
uuid: A unique identifier for the event.
disable_geoip: Whether to disable GeoIP for this event.
Examples:
```python
# Set with distinct id
posthog.set(distinct_id='user123', properties={'name': 'Max Hedgehog'})
```
Category:
Identification
Note: This method will not raise exceptions. Errors are logged.
"""
distinct_id = kwargs.get("distinct_id", None)
properties = kwargs.get("properties", None)
timestamp = kwargs.get("timestamp", None)
uuid = kwargs.get("uuid", None)
disable_geoip = kwargs.get("disable_geoip", None)
properties = properties or {}
properties = add_context_tags(properties)
(distinct_id, personless) = get_identity_state(distinct_id)
if personless or not properties:
return None # Personless set() does nothing
msg = {
"timestamp": timestamp,
"distinct_id": distinct_id,
"$set": properties,
"event": "$set",
"uuid": uuid,
}
return self._enqueue(msg, disable_geoip)
@no_throw()
def set_once(self, **kwargs: Unpack[OptionalSetArgs]) -> Optional[str]:
"""
Set properties on a person profile only if they haven't been set before.
Args:
distinct_id: The distinct ID of the user.
properties: A dictionary of properties to set once.
timestamp: The timestamp of the event.
uuid: A unique identifier for the event.
disable_geoip: Whether to disable GeoIP for this event.
Examples:
```python
posthog.set_once(distinct_id='user123', properties={'initial_signup_date': '2024-01-01'})
```
Category:
Identification
Note: This method will not raise exceptions. Errors are logged.
"""
distinct_id = kwargs.get("distinct_id", None)
properties = kwargs.get("properties", None)
timestamp = kwargs.get("timestamp", None)
uuid = kwargs.get("uuid", None)
disable_geoip = kwargs.get("disable_geoip", None)
properties = properties or {}
properties = add_context_tags(properties)
(distinct_id, personless) = get_identity_state(distinct_id)
if personless or not properties:
return None # Personless set_once() does nothing
msg = {
"timestamp": timestamp,
"distinct_id": distinct_id,
"$set_once": properties,
"event": "$set_once",
"uuid": uuid,
}
return self._enqueue(msg, disable_geoip)
@no_throw()
def group_identify(
self,
group_type: str,
group_key: str,
properties: Optional[Dict[str, Any]] = None,
timestamp: Optional[Union[datetime, str]] = None,
uuid: Optional[str] = None,
disable_geoip: Optional[bool] = None,
distinct_id: Optional[ID_TYPES] = None,
) -> Optional[str]:
"""
Identify a group and set its properties.
Args:
group_type: The type of group (e.g., 'company', 'team').
group_key: The unique identifier for the group.
properties: A dictionary of properties to set on the group.
timestamp: The timestamp of the event.
uuid: A unique identifier for the event.
disable_geoip: Whether to disable GeoIP for this event.
distinct_id: The distinct ID of the user performing the action.
Examples:
```python
posthog.group_identify('company', 'company_id_in_your_db', {
'name': 'Awesome Inc.',
'employees': 11
})
```
Category:
Identification
Note: This method will not raise exceptions. Errors are logged.
"""
properties = properties or {}
# group_identify is purposefully always personful
distinct_id = get_identity_state(distinct_id)[0]
msg: Dict[str, Any] = {
"event": "$groupidentify",
"properties": {
"$group_type": group_type,
"$group_key": group_key,
"$group_set": properties,
},
"distinct_id": distinct_id,
"timestamp": timestamp,
"uuid": uuid,
}
# NOTE - group_identify doesn't generally use context properties - should it?
if get_context_session_id():
msg["properties"]["$session_id"] = str(get_context_session_id())
return self._enqueue(msg, disable_geoip)
@no_throw()
def alias(
self,
previous_id: str,
distinct_id: Optional[str],
timestamp=None,
uuid=None,
disable_geoip=None,
):
"""
Create an alias between two distinct IDs.
Args:
previous_id: The previous distinct ID.
distinct_id: The new distinct ID to alias to.
timestamp: The timestamp of the event.
uuid: A unique identifier for the event.
disable_geoip: Whether to disable GeoIP for this event.
Examples:
```python
posthog.alias(previous_id='distinct_id', distinct_id='alias_id')
```
Category:
Identification
Note: This method will not raise exceptions. Errors are logged.
"""
(distinct_id, personless) = get_identity_state(distinct_id)
if personless:
return None # Personless alias() does nothing - should this throw?
msg = {
"properties": {
"distinct_id": previous_id,
"alias": distinct_id,
},
"timestamp": timestamp,
"event": "$create_alias",
"distinct_id": previous_id,
"uuid": uuid,
}
if get_context_session_id():
msg["properties"]["$session_id"] = str(get_context_session_id())
return self._enqueue(msg, disable_geoip)
def capture_exception(
self,
exception: Optional[ExceptionArg],
**kwargs: Unpack[OptionalCaptureArgs],
):
"""
Capture an exception for error tracking.
Args:
exception: The exception to capture.
distinct_id: The distinct ID of the user.
properties: A dictionary of additional properties.
send_feature_flags: Whether to send feature flags with the exception.
disable_geoip: Whether to disable GeoIP for this event.
Examples:
```python
try:
# Some code that might fail
pass
except Exception as e:
posthog.capture_exception(e, 'user_distinct_id', properties=additional_properties)
```
Category:
Error Tracking
"""
distinct_id = kwargs.get("distinct_id", None)
properties = kwargs.get("properties", None)
send_feature_flags = kwargs.get("send_feature_flags", False)
disable_geoip = kwargs.get("disable_geoip", None)
# this function shouldn't ever throw an error, so it logs exceptions instead of raising them.
# this is important to ensure we don't unexpectedly re-raise exceptions in the user's code.
try:
properties = properties or {}
# Check if this exception has already been captured
if exception is not None and exception_is_already_captured(exception):
self.log.debug("Exception already captured, skipping")
return None