repo stringclasses 454
values | file_path stringlengths 5 201 | extension stringclasses 1
value | content stringlengths 8 509k | num_lines int64 3 16.9k | size_bytes int64 8 511k |
|---|---|---|---|---|---|
posthog | posthog/test/test_scopes.py | .py | import runpy
from pathlib import Path
from posthog.test.base import BaseTest
from django.test import SimpleTestCase
from parameterized import parameterized
from posthog.scopes import (
ALL_SCOPES,
API_SCOPE_ACTIONS,
API_SCOPE_OBJECTS,
INTERNAL_API_SCOPE_OBJECTS,
OAUTH_HIDDEN_SCOPE_OBJECTS,
O... | 465 | 23,389 |
posthog | posthog/test/test_element_model.py | .py | from typing import cast
from posthog.test.base import BaseTest, ClickhouseTestMixin
from parameterized import parameterized
from posthog.api.element import ElementSerializer
from posthog.models.element import Element, chain_to_elements, elements_to_string
from posthog.models.element.element import build_attributes_f... | 159 | 6,775 |
posthog | posthog/test/test_utils.py | .py | import os
import json
import base64
import tempfile
from datetime import datetime, timedelta
from typing import TYPE_CHECKING, Any, cast
from zoneinfo import ZoneInfo
import pytest
from freezegun import freeze_time
from posthog.test.base import BaseTest
from unittest.mock import call, patch
from django.contrib.auth.m... | 1,496 | 63,895 |
posthog | posthog/test/test_request_memory.py | .py | import sys
import pytest
from posthog.middleware import current_rss_mb
@pytest.mark.skipif(sys.platform != "linux", reason="requires /proc (Linux only)")
def test_current_rss_mb_returns_positive_on_linux():
# On the Linux CI runners /proc/self/statm exists, so this returns the live RSS.
rss = current_rss_mb... | 25 | 804 |
posthog | posthog/test/api_keys.py | .py | from posthog.models import ProjectSecretAPIKey, Team, User
from posthog.models.utils import generate_random_token_secret, hash_key_value, mask_key_value
def create_project_secret_api_key(
team: Team,
created_by: User | None = None,
label: str = "Test key",
scopes: list[str] | None = None,
) -> tuple[P... | 23 | 830 |
posthog | posthog/test/test_persons_db.py | .py | import os
import pytest
from unittest.mock import patch
from posthog.persons_db import LOCAL_DEV_PERSONS_DB_URL, persons_db_aconnection, persons_db_connection, persons_db_url
class TestPersonsDbUrl:
def test_writer_uses_writer_env(self):
with patch.dict(os.environ, {"PERSONS_DB_WRITER_URL": "postgres://... | 54 | 2,112 |
posthog | posthog/test/test_settings_debug_guard.py | .py | from unittest import TestCase
from django.core.exceptions import ImproperlyConfigured
from parameterized import parameterized
from posthog.settings.utils import assert_debug_not_in_production
class TestAssertDebugNotInProduction(TestCase):
@parameterized.expand([("US",), ("us",), ("EU",), ("eu",), ("DEV",), ("... | 30 | 1,295 |
posthog | posthog/test/activity_logging/test_external_data_source_activity_logging.py | .py | from posthog.test.activity_log_utils import ActivityLogTestHelper
from products.warehouse_sources.backend.facade.models import ExternalDataSource
class TestExternalDataSourceActivityLogging(ActivityLogTestHelper):
def test_external_data_source_model_has_activity_mixin(self):
from posthog.models.activity_... | 68 | 3,058 |
posthog | posthog/test/activity_logging/test_feature_flag_activity_logging.py | .py | from typing import Optional
from posthog.test.base import APIBaseTest
from dateutil import parser
from posthog.models.activity_logging.activity_log import Change, changes_between
from products.feature_flags.backend.models.feature_flag import FeatureFlag
class TestChangesBetweenFeatureFlags(APIBaseTest):
def t... | 124 | 4,056 |
posthog | posthog/test/activity_logging/test_alert_activity_logging.py | .py | from typing import Any, cast
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.test.activity_log_utils import ActivityLogTestHelper
class TestAlertActivityLogging(ActivityLogTestHelper):
def test_alert_configuration_creation_activity_logging(self):
alert = self.create_aler... | 282 | 11,690 |
posthog | posthog/test/activity_logging/test_tag_activity_logging.py | .py | from django.db.models.query import QuerySet
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.test.activity_log_utils import ActivityLogTestHelper
class TestTagActivityLogging(ActivityLogTestHelper):
def test_tag_creation_via_insight_tagging(self):
insight = self.create_in... | 216 | 10,465 |
posthog | posthog/test/activity_logging/test_oauth_application_activity_logging.py | .py | from posthog.test.base import BaseTest
from parameterized import parameterized
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.activity_logging.utils import activity_storage
from posthog.models.oauth import OAuthApplication
from posthog.models.organization import Organization
... | 216 | 8,821 |
posthog | posthog/test/activity_logging/test_person_activity_logging.py | .py | import unittest
from dateutil import parser
from posthog.models import Person, Team, User
from posthog.models.activity_logging.activity_log import changes_between
from posthog.models.utils import UUIDT
class TestChangesBetweenPersons(unittest.TestCase):
def test_can_exclude_changed_fields_in_persons(self) -> No... | 47 | 1,724 |
posthog | posthog/test/activity_logging/test_identity_provider_config_activity_logging.py | .py | from posthog.test.base import APIBaseTest
from parameterized import parameterized
from posthog.models import IdentityProviderConfig, OrganizationMembership
from posthog.models.activity_logging.activity_log import ActivityLog
class TestIdentityProviderConfigActivityLogging(APIBaseTest):
def setUp(self):
... | 70 | 2,560 |
posthog | posthog/test/activity_logging/test_user_activity_logging.py | .py | from posthog.test.base import BaseTest
from django.utils import timezone
from parameterized import parameterized
from posthog.models import Organization, User
from posthog.models.activity_logging.activity_log import (
ActivityLog,
activity_visibility_restrictions,
field_exclusions,
field_with_masked_... | 343 | 14,341 |
posthog | posthog/test/activity_logging/test_batch_export_activity_logging.py | .py | from posthog.test.activity_log_utils import ActivityLogTestHelper
from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportDestination
class TestBatchExportActivityLogging(ActivityLogTestHelper):
def create_test_destination(self):
"""Helper to create a test destination for b... | 171 | 7,473 |
posthog | posthog/test/activity_logging/test_evaluation_activity_logging.py | .py | from typing import Any
from rest_framework import status
from posthog.test.activity_log_utils import ActivityLogTestHelper
from products.ai_observability.backend.models.evaluation_config import EvaluationConfig
from products.ai_observability.backend.models.evaluations import Evaluation
from products.ai_observability... | 230 | 9,900 |
posthog | posthog/test/activity_logging/test_external_data_schema_activity_logging.py | .py | from typing import get_args
from posthog.models.activity_logging.activity_log import ActivityScope, field_exclusions
from posthog.models.activity_logging.model_activity import ModelActivityMixin
from posthog.test.activity_log_utils import ActivityLogTestHelper
from products.warehouse_sources.backend.facade.models imp... | 106 | 4,643 |
posthog | posthog/test/activity_logging/test_activity_logging.py | .py | import pytest
from posthog.test.base import BaseTest
from unittest.mock import patch
from django.db.utils import IntegrityError
from parameterized import parameterized
from posthog.models import User
from posthog.models.activity_logging.activity_log import ActivityLog, Change, Detail, Trigger, log_activity
from post... | 391 | 18,769 |
posthog | posthog/test/activity_logging/test_organization_activity_logging.py | .py | from posthog.constants import AvailableFeature
from posthog.models import Organization, User
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.organization import OrganizationMembership
from posthog.models.organization_invite import OrganizationInvite
from posthog.models.uploaded_... | 396 | 18,629 |
posthog | posthog/test/activity_logging/test_organization_domain_activity_logging.py | .py | from freezegun import freeze_time
from posthog.test.base import APIBaseTest
from unittest.mock import patch
from django.utils import timezone
import dns.rrset
import dns.resolver
from parameterized import parameterized
from posthog.constants import AvailableFeature
from posthog.models import OrganizationDomain, Orga... | 201 | 7,603 |
posthog | posthog/test/activity_logging/test_personal_api_key_activity_logging.py | .py | from unittest.mock import MagicMock, patch
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.activity_logging.personal_api_key_utils import calculate_scope_change_logs
from posthog.models.organization import Organization
from posthog.models.team.team import Team
from posthog.test... | 658 | 31,164 |
posthog | posthog/async_migrations/utils.py | .py | import asyncio
from collections.abc import Callable
from datetime import datetime
from typing import Optional
from django.conf import settings
from django.db import transaction
from django.utils.timezone import now
import structlog
import posthoganalytics
from posthog.async_migrations.definition import AsyncMigratio... | 391 | 13,762 |
posthog | posthog/async_migrations/runner.py | .py | from typing import Optional
import structlog
from semantic_version.base import SimpleSpec
from posthog.async_migrations.definition import AsyncMigrationDefinition
from posthog.async_migrations.setup import (
FROZEN_POSTHOG_VERSION,
get_async_migration_definition,
get_async_migration_dependency,
)
from pos... | 302 | 11,288 |
posthog | posthog/async_migrations/setup.py | .py | from typing import Optional
from django.core.exceptions import ImproperlyConfigured
from infi.clickhouse_orm.utils import import_submodules
from semantic_version.base import Version
from posthog.async_migrations.definition import AsyncMigrationDefinition
from posthog.constants import FROZEN_POSTHOG_VERSION
from post... | 133 | 4,751 |
posthog | posthog/async_migrations/disk_util.py | .py | from posthog.clickhouse.client import sync_execute
from posthog.settings import CLICKHOUSE_DATABASE
def analyze_enough_disk_space_free_for_table(table_name: str, required_ratio: float):
"""
Analyzes whether there's enough disk space free for given async migration operation.
This is done by checking wheth... | 45 | 1,543 |
posthog | posthog/async_migrations/status.py | .py | def async_migrations_ok() -> bool:
from posthog.async_migrations.runner import is_posthog_version_compatible
from posthog.models.async_migration import AsyncMigration, MigrationStatus
for migration in AsyncMigration.objects.all():
migration_completed_or_running = migration.status in [
M... | 16 | 639 |
posthog | posthog/async_migrations/definition.py | .py | from collections.abc import Callable
from typing import TYPE_CHECKING, Any, Optional, Union
from posthog.constants import AnalyticsDBMS
from posthog.models.utils import sane_repr
from posthog.settings import ASYNC_MIGRATIONS_DEFAULT_TIMEOUT_SECONDS
from posthog.version_requirement import ServiceVersionRequirement
if ... | 128 | 4,634 |
posthog | posthog/async_migrations/test/test_migrations_not_required.py | .py | from posthog.async_migrations.setup import ALL_ASYNC_MIGRATIONS
from posthog.async_migrations.test.util import AsyncMigrationBaseTest
from posthog.clickhouse.client import sync_execute
from posthog.models.person.sql import COMMENT_DISTINCT_ID_COLUMN_SQL
# No pytest.mark.async_migrations here on purpose: the Core shard... | 26 | 1,209 |
posthog | posthog/async_migrations/test/test_0007_persons_and_groups_on_events_backfill.py | .py | import json
from uuid import uuid4
import pytest
from posthog.test.base import ClickhouseTestMixin, run_clickhouse_statement_in_parallel
from posthog.async_migrations.runner import start_async_migration
from posthog.async_migrations.setup import get_async_migration_definition, setup_async_migrations
from posthog.asyn... | 592 | 20,731 |
posthog | posthog/async_migrations/test/util.py | .py | from posthog.test.base import BaseTest
from unittest.mock import patch
from posthog.models.async_migration import AsyncMigration, MigrationStatus
class AsyncMigrationBaseTest(BaseTest):
def setUp(self):
super().setUp()
self.patcher = patch("posthoganalytics.capture")
self.patcher.start()
... | 29 | 772 |
posthog | posthog/async_migrations/test/test_runner.py | .py | from datetime import datetime
import pytest
from django.db import connection
from posthog.async_migrations.examples.test_migration import Migration
from posthog.async_migrations.runner import (
attempt_migration_rollback,
run_async_migration_next_op,
start_async_migration,
)
from posthog.async_migrations... | 185 | 6,973 |
posthog | posthog/async_migrations/test/test_0010_move_old_partitions.py | .py | import importlib
import pytest
from unittest.mock import patch
from posthog.async_migrations.setup import get_async_migration_definition
from posthog.async_migrations.test.util import AsyncMigrationBaseTest
pytestmark = [
pytest.mark.async_migrations,
pytest.mark.skip(
reason="Async migrations are fr... | 46 | 1,596 |
posthog | posthog/async_migrations/test/test_definition.py | .py | import pytest
from posthog.test.base import BaseTest
from django.test import SimpleTestCase
from infi.clickhouse_orm.utils import import_submodules
from posthog.async_migrations.definition import AsyncMigrationDefinition, AsyncMigrationOperation
from posthog.async_migrations.setup import (
ASYNC_MIGRATIONS_EXAMP... | 66 | 2,614 |
posthog | posthog/async_migrations/test/test_utils.py | .py | from datetime import UTC, datetime, timedelta
import pytest
from unittest.mock import patch
from django.test import SimpleTestCase
from posthog.async_migrations.definition import AsyncMigrationOperationSQL
from posthog.async_migrations.test.util import AsyncMigrationBaseTest, create_async_migration
from posthog.asyn... | 100 | 3,729 |
posthog | posthog/async_migrations/examples/example.py | .py | from django.conf import settings
from posthog.async_migrations.definition import (
AsyncMigrationDefinition,
AsyncMigrationOperation,
AsyncMigrationOperationSQL,
)
from posthog.clickhouse.client import sync_execute
from posthog.constants import AnalyticsDBMS
from posthog.models.person.sql import (
KAFK... | 123 | 5,021 |
posthog | posthog/async_migrations/examples/test_with_rollback_exception.py | .py | from posthog.async_migrations.definition import AsyncMigrationDefinition, AsyncMigrationOperation
# For testing purposes
def raise_exception_fn(_):
raise Exception("Test rollback Exception")
class Migration(AsyncMigrationDefinition):
# For testing only!!
description = "Another example async migration t... | 21 | 662 |
posthog | posthog/async_migrations/examples/test_migration.py | .py | from posthog.async_migrations.definition import (
AsyncMigrationDefinition,
AsyncMigrationOperation,
AsyncMigrationOperationSQL,
)
from posthog.constants import AnalyticsDBMS
# For testing purposes
class SideEffects:
def __init__(self):
self.reset_count()
def reset_count(self):
s... | 66 | 2,249 |
posthog | posthog/slo/types.py | .py | import dataclasses
from enum import StrEnum
from typing import Optional
class SloArea(StrEnum):
ANALYTIC_PLATFORM = "analytic-platform"
class SloOperation(StrEnum):
EXPORT = "export"
SUBSCRIPTION_DELIVERY = "subscription_delivery"
SUBSCRIPTION_CREATE = "subscription_create"
SUBSCRIPTION_DELETE =... | 74 | 2,244 |
posthog | posthog/slo/context.py | .py | """Helpers for emitting SLO lifecycle events around normal Python code.
Intended usage patterns:
1. Standard block instrumentation:
with slo_operation(spec=spec, properties=props):
do_work()
2. Explicit completion enrichment in the same block:
with slo_operation(spec=spec) as slo:
do_work()... | 184 | 6,635 |
posthog | posthog/slo/events.py | .py | from collections.abc import Callable
import posthoganalytics
from prometheus_client import Counter, Histogram
from posthog.exceptions_capture import capture_exception
from posthog.git import get_git_commit_short
from posthog.slo.types import SloCompletedProperties, SloStartedProperties
OPERATION_STARTED_COUNTER = Co... | 152 | 4,524 |
posthog | posthog/slo/test/test_slo_context.py | .py | import asyncio
import inspect
import traceback
import dataclasses
from collections.abc import Callable
from contextlib import nullcontext
from pathlib import Path
from typing import Any
import pytest
from unittest.mock import MagicMock, patch
from posthog.slo.context import (
SLO_REPO_ROOT,
SloSpec,
_buil... | 362 | 12,557 |
posthog | posthog/integration_secrets/callers.py | .py | from enum import StrEnum
class IntegrationCaller(StrEnum):
"""The product asking for a credential.
Passed explicitly at every call site rather than read from a setting, so the code
says which product wanted the credential instead of the pod it happened to run in.
One pod hosts many products, and "Dja... | 27 | 1,121 |
posthog | posthog/integration_secrets/errors.py | .py | class IntegrationSecretError(Exception):
def __init__(self, key: str, message: str) -> None:
self.key = key
super().__init__(message)
class SecretMissingError(IntegrationSecretError):
"""The key is unknown to the service, or has no value in this environment."""
def __init__(self, key: str... | 23 | 861 |
posthog | posthog/integration_secrets/client.py | .py | """Client for the integration service — platform integration credentials over HTTP.
These are the OAuth app client ids/secrets and API keys PostHog itself owns, which used
to be injected as environment variables into every pod that might need one. Reading them
over HTTP means rotation happens in one place with no char... | 219 | 8,870 |
posthog | posthog/integration_secrets/test/test_client.py | .py | from typing import Any
import pytest
from unittest.mock import patch
from django.test import SimpleTestCase, override_settings
import jwt
import requests
from parameterized import parameterized
from posthog.integration_secrets.callers import IntegrationCaller
from posthog.integration_secrets.client import (
Int... | 237 | 10,367 |
posthog | posthog/query_cache/__init__.py | .py | from posthog.query_cache.cache import CacheLookup, QueryCache
from posthog.query_cache.failures import FailureKind, QueryFailureRecord
from posthog.query_cache.freshness_index import clean_up_stale_insights, get_stale_insights
from posthog.query_cache.metrics import count_query_cache_hit
from posthog.query_cache.serial... | 17 | 549 |
posthog | posthog/query_cache/size_tracker.py | .py | import time
from datetime import timedelta
from typing import Optional
from django.conf import settings
from django.core.cache import BaseCache, caches
from django.db import DatabaseError
import structlog
from django_redis import get_redis_connection
from prometheus_client import Counter, Histogram
from redis import ... | 268 | 9,610 |
posthog | posthog/query_cache/freshness_index.py | .py | from datetime import UTC, datetime
from typing import Optional
from posthog import redis
_REDIS_KEY_PREFIX = "cache_timestamps"
def _redis_key(team_id: int) -> str:
return f"{_REDIS_KEY_PREFIX}:{team_id}"
def _identifier(insight_id: int, dashboard_id: Optional[int]) -> str:
return f"{insight_id}:{dashboar... | 64 | 2,848 |
posthog | posthog/query_cache/failures.py | .py | from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
from typing import Any, Literal, Optional, cast
from django.core.cache import caches
import structlog
from prometheus_client import Counter
from posthog.caching.redis_cluster_connection_factory import QUERY_CACHE_ALIAS
logger = structlo... | 166 | 7,202 |
posthog | posthog/query_cache/metrics.py | .py | from collections.abc import Generator
from contextlib import contextmanager
from typing import NamedTuple, Optional
from prometheus_client import CollectorRegistry, Counter, Histogram
from posthog.clickhouse.query_tagging import get_query_tag_value
from posthog.exceptions_capture import capture_exception
from posthog... | 144 | 4,480 |
posthog | posthog/query_cache/results.py | .py | from typing import Optional
from django.core.cache import caches
import structlog
from posthog.caching.redis_cluster_connection_factory import QUERY_CACHE_ALIAS
from posthog.query_cache.serialization import CachedEntry, split_cached_response_bytes
logger = structlog.get_logger(__name__)
def fetch_entry(cache_key:... | 33 | 1,042 |
posthog | posthog/query_cache/cache.py | .py | from dataclasses import dataclass
from datetime import datetime
from typing import Optional
from django.conf import settings
import structlog
from posthog.cache_utils import OrjsonJsonSerializer
from posthog.query_cache.failures import Budget, FailureKind, QueryFailureCache, QueryFailureRecord
from posthog.query_cac... | 93 | 4,065 |
posthog | posthog/query_cache/serialization.py | .py | from dataclasses import dataclass
from typing import Any, Optional
import structlog
from posthog.cache_utils import OrjsonJsonSerializer
logger = structlog.get_logger(__name__)
# Split cache format: magic + flags byte + 4-byte big-endian header length + header JSON + results JSON.
# Storing `results` as a separate ... | 97 | 3,859 |
posthog | posthog/query_cache/test/test_size_tracker.py | .py | from posthog.test.base import BaseTest
from unittest.mock import patch
from django.core.cache import cache
from django.db import OperationalError
from django.test import override_settings
from posthog.models import Team
from posthog.query_cache.size_tracker import TeamCacheSizeTracker, get_team_cache_limit
class Te... | 299 | 12,303 |
posthog | posthog/query_cache/test/test_failures.py | .py | from datetime import UTC, datetime, timedelta
from freezegun import freeze_time
from django.core.cache import caches
from django.test import SimpleTestCase
from parameterized import parameterized
from posthog.caching.redis_cluster_connection_factory import QUERY_CACHE_ALIAS
from posthog.query_cache.failures import ... | 135 | 6,117 |
posthog | posthog/query_cache/test/test_cache.py | .py | from datetime import UTC, datetime, timedelta
from posthog.test.base import BaseTest
from unittest.mock import patch
from django.core.cache import caches
from django.db import OperationalError
from posthog.cache_utils import OrjsonJsonSerializer
from posthog.caching.redis_cluster_connection_factory import QUERY_CACH... | 68 | 2,983 |
posthog | posthog/models/user_repo_preference.py | .py | from django.conf import settings
from django.db import models
from posthog.models.utils import UUIDModel
class UserRepoPreference(UUIDModel):
class ScopeType(models.TextChoices):
SLACK_CHANNEL = "slack_channel"
team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="user_rep... | 72 | 2,717 |
posthog | posthog/models/project_secret_api_key.py | .py | from typing import Optional
from django.contrib.postgres.fields import ArrayField
from django.contrib.postgres.indexes import GinIndex
from django.db import models
from django.utils import timezone
from posthog.models.activity_logging.model_activity import ModelActivityMixin
from .utils import generate_random_token,... | 70 | 2,674 |
posthog | posthog/models/integration_repository_cache.py | .py | """Per-repository heavy cache for GitHub integrations.
Stores README + full file tree + descriptive metadata so the Signals selection
agent can server-side grep paths via HogQL (`ARRAY JOIN splitByString('\\n',
tree_paths)`) instead of hitting GitHub's `/search/code` endpoint (30 req/min
ceiling). The lightweight (id,... | 475 | 21,988 |
posthog | posthog/models/user.py | .py | from collections.abc import Callable
from functools import cached_property
from typing import TYPE_CHECKING, Any, NoReturn, Optional, TypedDict, cast
from django.contrib.auth.models import AbstractUser, BaseUserManager
from django.core.management.base import CommandError
from django.db import models, transaction
from ... | 707 | 34,616 |
posthog | posthog/models/utils.py | .py | import re
import json
import string
import hashlib
import secrets
import datetime
from collections import namedtuple
from collections.abc import Callable, Iterable, Iterator
from contextlib import contextmanager
from decimal import Decimal
from typing import TYPE_CHECKING, Any, Literal, Optional, TypeVar, Union
from uu... | 560 | 21,325 |
posthog | posthog/models/quick_filter.py | .py | from django.db import models
from posthog.models.utils import UUIDModel
from posthog.schema_enums import QuickFilterType
class QuickFilter(UUIDModel):
TYPE_CHOICES = [(t.value, t.value) for t in QuickFilterType]
team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)
name = models.CharField(m... | 43 | 1,575 |
posthog | posthog/models/repo_routing_rule.py | .py | from django.conf import settings
from django.db import models
from posthog.models.utils import UUIDModel
class RepoRoutingRule(UUIDModel):
team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="repo_routing_rules")
rule_text = models.TextField()
repository = models.CharField(max... | 21 | 771 |
posthog | posthog/models/js_snippet_versioning.py | .py | import os
import re
import json
import time
import hashlib
import threading
from collections import OrderedDict
from dataclasses import dataclass
from typing import Any, NotRequired, Optional, TypedDict
from django.conf import settings
from django.core.cache import cache
import boto3
import structlog
from botocore.ex... | 521 | 18,553 |
posthog | posthog/models/data_color_theme.py | .py | from django.db import models
from posthog.models.team import Team
from posthog.models.utils import RootTeamMixin
from posthog.rbac.decorators import field_access_control
class DataColorTheme(RootTeamMixin, models.Model):
team = models.ForeignKey(Team, on_delete=models.CASCADE, null=True, blank=True)
project ... | 24 | 928 |
posthog | posthog/models/core_event.py | .py | from django.core.exceptions import ValidationError
from django.db import models
from posthog.models.team import Team
from posthog.models.utils import UUIDModel
class CoreEvent(UUIDModel):
"""
A reusable event definition that can be shared across
Marketing analytics, Customer analytics, and Revenue analyt... | 86 | 2,705 |
posthog | posthog/models/organization_invite.py | .py | from datetime import timedelta
from typing import TYPE_CHECKING, Optional, cast
from django.db import models, transaction
from django.db.models.signals import pre_delete
from django.dispatch import receiver
from django.utils import timezone
import structlog
from rest_framework import exceptions
from posthog.constant... | 338 | 16,581 |
posthog | posthog/models/instance_setting.py | .py | import json
import time
from contextlib import contextmanager
from threading import Lock
from typing import Any
from django.db import models
from posthog.settings import CONSTANCE_CONFIG, CONSTANCE_DATABASE_PREFIX
class InstanceSetting(models.Model):
key = models.CharField(max_length=128, null=False, blank=Fals... | 99 | 3,504 |
posthog | posthog/models/organization.py | .py | import sys
from datetime import datetime, timedelta
from functools import cache as functools_cache
from typing import TYPE_CHECKING, Any, Literal, Optional, TypedDict, Union
from django.conf import settings
from django.contrib.postgres.fields import ArrayField
from django.core.cache import cache
from django.db import ... | 911 | 38,226 |
posthog | posthog/models/user_home_settings.py | .py | from django.db import models
from posthog.models.utils import RootTeamMixin, UUIDTModel
class UserHomeSettings(UUIDTModel, RootTeamMixin):
"""Stores personalized navigation settings such as pinned tabs and the homepage for a user within a team."""
user = models.ForeignKey(
"User",
on_delete=... | 28 | 882 |
posthog | posthog/models/__init__.py | .py | # Need to skip autoimporting because this file is severely prone to circular imports errors
# You should try and make them alphabetically sorted manually if possible
# isort: skip_file
from ..session_recordings.models.session_recording import SessionRecording
from ..session_recordings.models.session_recording_external_... | 194 | 6,987 |
posthog | posthog/models/onboarding_delegation.py | .py | from __future__ import annotations
from datetime import UTC, datetime
from typing import TYPE_CHECKING, Any, cast
from uuid import UUID
from django.db import transaction
import structlog
import posthoganalytics
from posthog.exceptions_capture import capture_exception
from posthog.models.user import OnboardingSkippe... | 286 | 12,105 |
posthog | posthog/models/user_push_token.py | .py | from django.db import models
from posthog.models.utils import UUIDModel
class UserPushToken(UUIDModel):
"""Per-user push notification token for a mobile device.
A user may register multiple tokens (one per device). Tokens are uploaded
by the mobile app after the user grants notification permission, and ... | 42 | 1,351 |
posthog | posthog/models/event_filter_config.py | .py | from django.conf import settings
from django.core.exceptions import ValidationError
from django.db import models
from posthog.models.team.team import Team
from posthog.models.utils import UUIDTModel
ALLOWED_FIELDS = {"event_name", "distinct_id"}
ALLOWED_OPERATORS = {"exact", "contains"}
NODE_TYPES = {"and", "or", "no... | 291 | 10,646 |
posthog | posthog/models/column_configuration.py | .py | from django.contrib.postgres.fields import ArrayField
from django.db import models
from django.utils import timezone
from posthog.models.utils import UUIDModel
class ColumnConfiguration(UUIDModel):
class Visibility(models.TextChoices):
PRIVATE = "private", "Private (only visible to creator)"
SHAR... | 45 | 1,953 |
posthog | posthog/models/data_deletion_request.py | .py | from collections.abc import Callable
from dataclasses import dataclass
from django.contrib.postgres.fields import ArrayField
from django.core.cache import cache
from django.core.exceptions import ValidationError
from django.db import models
from django.db.models import F
from django.utils import timezone
from posthog... | 1,072 | 48,965 |
posthog | posthog/models/event_ingestion_restriction_config.py | .py | import json
from django.contrib.postgres.fields import ArrayField
from django.db import models
from django.db.models.signals import post_delete, post_save, pre_save
from django.dispatch import receiver
from posthog.models.utils import UUIDTModel
from posthog.redis import get_client
from posthog.settings import PLUGIN... | 203 | 8,337 |
posthog | posthog/models/async_migration.py | .py | from django.db import models
# an enum, essentially
class MigrationStatus:
NotStarted = 0
Running = 1
CompletedSuccessfully = 2
Errored = 3
RolledBack = 4
Starting = 5 # only relevant for the UI
FailedAtStartup = 6
class AsyncMigrationError(models.Model):
id = models.BigAutoField(pr... | 70 | 2,632 |
posthog | posthog/models/signals.py | .py | from contextlib import contextmanager
from functools import wraps
from django.dispatch import Signal
from django.dispatch.dispatcher import receiver
is_muted = False
# Used for any model that requires an activity log of changes
# To use this, a model must either:
# 1. Include ModelActivityMixin in the model's inheri... | 53 | 1,516 |
posthog | posthog/models/share_password.py | .py | import secrets
from typing import Optional
from django.contrib.auth.hashers import check_password, make_password
from django.db import models
from posthog.models.user import User
def generate_default_password() -> str:
"""Generate a secure random password for new share passwords."""
return secrets.token_url... | 72 | 2,604 |
posthog | posthog/models/event_buffer.py | .py | from django.db import models
class EventBuffer(models.Model):
event = models.JSONField(null=True, blank=True)
process_at = models.DateTimeField()
locked = models.BooleanField()
| 8 | 191 |
posthog | posthog/models/organization_domain.py | .py | import secrets
from typing import TYPE_CHECKING, Any, Optional
from django.contrib.postgres.fields import ArrayField
from django.core.exceptions import ValidationError
from django.db import models, transaction
from django.db.models.signals import post_delete
from django.dispatch import receiver
from django.utils impor... | 419 | 19,273 |
posthog | posthog/models/project.py | .py | from functools import cached_property
from typing import TYPE_CHECKING, Optional, cast
from uuid import UUID
from django.core.validators import MinLengthValidator
from django.db import models, transaction
from posthog.models.utils import UpdatedMetaFields, sane_repr
if TYPE_CHECKING:
from posthog.models import T... | 106 | 4,021 |
posthog | posthog/models/role_external_reference.py | .py | from __future__ import annotations
from django.db import models
from django.db.models.functions import Lower
from posthog.models.utils import UUIDModel
class RoleExternalReference(UUIDModel):
"""Maps an external provider role/group to a PostHog role.
Organization-scoped: one external reference maps to exac... | 79 | 3,286 |
posthog | posthog/models/remote_config.py | .py | import os
import json
from typing import Any
from django.conf import settings
from django.db import models, transaction
from django.db.models.signals import post_delete, post_save
from django.dispatch.dispatcher import receiver
from django.utils import timezone
import requests
import structlog
from opentelemetry impo... | 594 | 26,175 |
posthog | posthog/models/github_integration_base.py | .py | """Base class for GitHub integrations (team-scoped and user-scoped).
Provides installation-token management and installation-authenticated GitHub API
operations that are shared between :class:`GitHubIntegration` (team-scoped) and
:class:`UserGitHubIntegration` (user-scoped).
"""
import time
import uuid
from collectio... | 2,029 | 90,568 |
posthog | posthog/models/sharing_configuration.py | .py | import secrets
from datetime import timedelta
from typing import TYPE_CHECKING, Any, cast
if TYPE_CHECKING:
from posthog.models.share_password import SharePassword
from django.conf import settings
from django.db import models, transaction
from django.utils import timezone
import structlog
from posthog.jwt impor... | 306 | 11,871 |
posthog | posthog/models/group_usage_metric.py | .py | from django.db import models
from posthog.hogql import ast
from posthog.models.utils import BytecodeModelMixin, UUIDModel
from posthog.rbac.decorators import field_access_control
class GroupUsageMetric(UUIDModel, BytecodeModelMixin):
"""
A usage metric rendered on a Customer Analytics profile.
Despite ... | 73 | 2,920 |
posthog | posthog/models/tagged_item.py | .py | from django.core.exceptions import ValidationError
from django.db import models
from posthog.models.activity_logging.model_activity import ModelActivityMixin, get_current_user, get_was_impersonated
from posthog.models.utils import UUIDTModel, build_partial_uniqueness_constraint, build_unique_relationship_check
RELATE... | 161 | 5,323 |
posthog | posthog/models/user_scene_personalisation.py | .py | from django.db import models
from posthog.models.utils import RootTeamMixin, UUIDTModel
class UserScenePersonalisation(UUIDTModel, RootTeamMixin):
scene = models.CharField(max_length=200)
dashboard = models.ForeignKey("dashboards.Dashboard", on_delete=models.CASCADE, null=True, blank=True)
team = models.... | 25 | 772 |
posthog | posthog/models/oauth.py | .py | import enum
from typing import TYPE_CHECKING, cast
from urllib.parse import urlparse
from django.conf import settings
from django.contrib.auth.signals import user_logged_out
from django.contrib.postgres.fields import ArrayField
from django.contrib.postgres.indexes import GinIndex
from django.core.exceptions import Val... | 1,008 | 47,718 |
posthog | posthog/models/materialized_column_slots.py | .py | from django.db import models
from posthog.models.event.sql import DMAT_STRING_COLUMN_COUNT
from posthog.models.team import Team
from posthog.models.utils import UUIDTModel
from products.event_definitions.backend.models import PropertyDefinition
# Single source of truth is the physical dmat_string pool size in event/... | 101 | 4,707 |
posthog | posthog/models/tag.py | .py | from django.db import models
from posthog.models.activity_logging.model_activity import ModelActivityMixin
from posthog.models.utils import RootTeamMixin, UUIDTModel
def tagify(tag: str):
return tag.strip().lower()
class Tag(ModelActivityMixin, UUIDTModel, RootTeamMixin):
name = models.CharField(max_length... | 20 | 498 |
posthog | posthog/models/user_integration.py | .py | import time
from datetime import datetime
from typing import TYPE_CHECKING, Any
from django.conf import settings
from django.db import models
import requests
import structlog
from posthog.egress.github.transport import github_request, raise_if_github_rate_limited
from posthog.egress.limiter.policies import Priority
... | 682 | 29,837 |
posthog | posthog/models/integration.py | .py | import re
import hmac
import json
import time
import base64
import hashlib
import secrets
from collections.abc import Iterable, Mapping
from dataclasses import dataclass
from datetime import datetime, timedelta
from typing import TYPE_CHECKING, Any, Literal, NamedTuple, NoReturn, Optional, Self, cast
from urllib.parse ... | 5,242 | 233,687 |
posthog | posthog/models/messaging.py | .py | import hashlib
from django.conf import settings
from django.db import models
from posthog.models.utils import UUIDTModel
def _hash_email(email: str, salt: str) -> str:
if not salt:
raise ValueError("Refusing to hash an email with an empty MessagingRecord salt")
return hashlib.sha256(f"{salt}_{email}... | 85 | 3,364 |
posthog | posthog/models/_deprecated_prompts.py | .py | from django.contrib.postgres.fields import ArrayField
from django.db import models
from django.utils import timezone
# DEPRECATED - DO NOT USE
class Prompt(models.Model):
step = models.IntegerField()
type = models.CharField(max_length=200) # tooltip, modal, etc
title = models.CharField(max_length=200)
... | 52 | 2,269 |
posthog | posthog/models/identity_provider_config.py | .py | from collections.abc import Collection
from typing import Any
from django.contrib.postgres.fields import ArrayField
from django.db import models, transaction
import structlog
from posthog.models.activity_logging.model_activity import ModelActivityMixin
from posthog.models.utils import UUIDModel
logger = structlog.g... | 164 | 6,404 |
posthog | posthog/models/global_rate_limit_threshold_config.py | .py | import json
from django.db import models, transaction
from django.db.models.signals import post_delete, post_save
from django.dispatch import receiver
from posthog.models.utils import UUIDModel
from posthog.redis import get_client
from posthog.settings import PLUGINS_RELOAD_REDIS_URL
# Single Redis key holding the J... | 89 | 3,783 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.