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
readthedocs.org
readthedocs/rtd_tests/tests/test_gold.py
.py
from django.test import TestCase from django.urls import reverse from django_dynamic_fixture import fixture, get from readthedocs.gold.models import LEVEL_CHOICES, GoldUser from readthedocs.projects.models import Project from readthedocs.rtd_tests.utils import create_user class GoldViewTests(TestCase): def setUp...
59
2,148
readthedocs.org
readthedocs/rtd_tests/tests/test_resolver.py
.py
import django_dynamic_fixture as fixture from django.test import TestCase, override_settings from django_dynamic_fixture import get from readthedocs.builds.constants import EXTERNAL from readthedocs.builds.models import Version from readthedocs.core.resolver import Resolver from readthedocs.projects.constants import (...
1,094
41,122
readthedocs.org
readthedocs/rtd_tests/tests/test_extend.py
.py
from django.test import TestCase, override_settings from readthedocs.core.utils.extend import SettingsOverrideObject, get_override_class # Top level to ensure module name is correct class FooBase: def bar(self): return 1 @classmethod def baz(cls): return 1 class NewFoo(FooBase): de...
103
2,927
readthedocs.org
readthedocs/rtd_tests/tests/test_version_config.py
.py
from django.test import TestCase from django_dynamic_fixture import get from readthedocs.builds.constants import BUILD_STATE_BUILDING, BUILD_STATE_FINISHED from readthedocs.builds.models import Build, Version, BuildConfig from readthedocs.projects.models import Project class VersionConfigTests(TestCase): def set...
87
2,756
readthedocs.org
readthedocs/rtd_tests/tests/test_profile_views.py
.py
import itertools from unittest import mock from django.conf import settings from django.contrib.auth.models import User from django.test import TestCase, override_settings from django.urls import reverse from django_dynamic_fixture import get from rest_framework.authtoken.models import Token from readthedocs.audit.mo...
425
15,044
readthedocs.org
readthedocs/rtd_tests/tests/test_build_storage.py
.py
import os import shutil import tempfile from pathlib import Path import pytest from django.core.exceptions import SuspiciousFileOperation from django.test import TestCase, override_settings from readthedocs.builds.storage import BuildMediaFileSystemStorage files_dir = os.path.join(os.path.dirname(os.path.dirname(__f...
196
7,102
readthedocs.org
readthedocs/rtd_tests/tests/test_oauth_sync.py
.py
import django_dynamic_fixture as fixture import requests_mock from allauth.socialaccount.models import SocialAccount, SocialToken from allauth.socialaccount.providers.github.provider import GitHubProvider from django.contrib.auth.models import User from django.test import TestCase from readthedocs.oauth.constants impo...
316
12,003
readthedocs.org
readthedocs/rtd_tests/tests/test_integrations.py
.py
import django_dynamic_fixture as fixture from django.test import TestCase from rest_framework.test import APIClient from readthedocs.api.v2.views.integrations import GITHUB_SIGNATURE_HEADER from readthedocs.integrations.models import GitHubWebhook, HttpExchange, Integration from readthedocs.projects.models import Proj...
223
7,626
readthedocs.org
readthedocs/rtd_tests/tests/test_doc_builder.py
.py
import tempfile from unittest import mock from unittest.mock import patch import py import pytest from django.test import TestCase from django.test.utils import override_settings from readthedocs.config.tests.test_config import get_build_config from readthedocs.doc_builder.backends.mkdocs import BaseMkdocs from readt...
323
11,050
readthedocs.org
readthedocs/rtd_tests/tests/test_sync_versions.py
.py
from unittest import mock from django.conf import settings from django.contrib.auth.models import User from django.test import TestCase from django_dynamic_fixture import get from readthedocs.builds.constants import BRANCH, EXTERNAL, LATEST, STABLE, TAG from readthedocs.builds.models import ( Version, ) from read...
1,693
50,666
readthedocs.org
readthedocs/rtd_tests/tests/test_domains.py
.py
from unittest import mock import dns.resolver from django.conf import settings from django.test import TestCase, override_settings from django_dynamic_fixture import get from readthedocs.projects.forms import DomainForm from readthedocs.projects.models import Domain, Project from readthedocs.subscriptions.constants i...
270
8,485
readthedocs.org
readthedocs/rtd_tests/tests/test_unresolver.py
.py
import django_dynamic_fixture as fixture import pytest from django.test import override_settings from django_dynamic_fixture import get from readthedocs.builds.constants import EXTERNAL from readthedocs.builds.models import Version from readthedocs.core.unresolver import ( InvalidCustomDomainError, InvalidExte...
470
20,015
readthedocs.org
readthedocs/rtd_tests/tests/test_doc_building.py
.py
import os import uuid from unittest import mock from unittest.mock import Mock, PropertyMock, patch import pytest from django.test import TestCase, override_settings from django_dynamic_fixture import get from docker.errors import APIError as DockerAPIError from readthedocs.projects.models import APIProject from read...
433
15,392
readthedocs.org
readthedocs/rtd_tests/tests/test_redirects.py
.py
from django.test import TestCase from django.test.utils import override_settings from django_dynamic_fixture import fixture, get from readthedocs.builds.constants import LATEST from readthedocs.projects.constants import SINGLE_VERSION_WITHOUT_TRANSLATIONS from readthedocs.projects.models import Project from readthedoc...
185
5,798
readthedocs.org
readthedocs/rtd_tests/tests/projects/test_admin_actions.py
.py
from unittest import mock import django_dynamic_fixture as fixture from django import urls from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME from django.contrib.auth.models import User from django.test import TestCase from readthedocs.projects.models import Project class ProjectAdminActionsTest(TestCase...
78
2,628
readthedocs.org
readthedocs/rtd_tests/tests/projects/test_version_sorting.py
.py
from django.test import TestCase from django_dynamic_fixture import get from readthedocs.builds.constants import BRANCH, LATEST from readthedocs.builds.models import Version from readthedocs.projects.constants import REPO_TYPE_GIT from readthedocs.projects.models import Project from readthedocs.projects.templatetags.p...
141
4,379
readthedocs.org
readthedocs/vcs_support/base.py
.py
"""Base classes for VCS backends.""" import os import structlog from readthedocs.core.utils.filesystem import safe_rmtree from readthedocs.doc_builder.exceptions import BuildCancelled from readthedocs.doc_builder.exceptions import BuildUserError from readthedocs.projects.exceptions import RepositoryError log = str...
146
4,585
readthedocs.org
readthedocs/vcs_support/backends/__init__.py
.py
"""Listing of all the VCS backends.""" from . import git backend_cls = { "git": git.Backend, }
9
102
readthedocs.org
readthedocs/vcs_support/backends/git.py
.py
"""Git-related utilities.""" import re from typing import Iterable from urllib.parse import urlparse import structlog from django.conf import settings from readthedocs.builds.constants import BRANCH from readthedocs.builds.constants import EXTERNAL from readthedocs.builds.constants import STABLE from readthedocs.bui...
615
24,665
readthedocs.org
readthedocs/config/parser.py
.py
"""YAML parser for the RTD configuration file.""" import yaml __all__ = ("parse", "ParseError") class ParseError(Exception): """Parser related errors.""" def parse(stream): """ Take file-like object and return a project configuration. The file need be valid YAML and only contain mappings as docu...
29
690
readthedocs.org
readthedocs/config/notifications.py
.py
"""Notifications related to Read the Docs YAML config file.""" import textwrap from django.utils.translation import gettext_noop as _ from readthedocs.notifications.constants import ERROR from readthedocs.notifications.messages import Message from readthedocs.notifications.messages import registry from .exceptions ...
511
16,431
readthedocs.org
readthedocs/config/utils.py
.py
"""Shared functions for the config module.""" def list_to_dict(list_): """Transform a list to a dictionary with its indices as keys.""" dict_ = {str(i): element for i, element in enumerate(list_)} return dict_
8
224
readthedocs.org
readthedocs/config/exceptions.py
.py
from readthedocs.doc_builder.exceptions import BuildUserError class ConfigError(BuildUserError): GENERIC = "config:generic" DEFAULT_PATH_NOT_FOUND = "config:path:default-not-found" CONFIG_PATH_NOT_FOUND = "config:path:not-found" KEY_NOT_SUPPORTED_IN_VERSION = "config:key:not-supported-in-version" ...
51
2,873
readthedocs.org
readthedocs/config/models.py
.py
""" Models for the response of the configuration object. We make use of pydantic to define the models/dataclasses for all the options that the user can define in the configuration file. Pydantic does runtime type checking and validation, but we aren't using it yet, and instead we are doing the validation in a separat...
127
3,302
readthedocs.org
readthedocs/config/find.py
.py
"""Helper functions to search files.""" import os import re def find_one(path, filename_regex): """Find the first file in ``path`` that match ``filename_regex`` regex.""" _path = os.path.abspath(path) for filename in os.listdir(_path): if re.match(filename_regex, filename): return os....
15
362
readthedocs.org
readthedocs/config/config.py
.py
"""Build configuration for rtd.""" import copy import datetime import os import re from contextlib import contextmanager from functools import lru_cache import pytz from django.conf import settings from pydantic import BaseModel from readthedocs.config.utils import list_to_dict from readthedocs.core.utils.filesystem...
1,106
40,174
readthedocs.org
readthedocs/config/validation.py
.py
"""Validations for the RTD configuration file.""" import os from .exceptions import ConfigValidationError def validate_list(value): """Check if ``value`` is an iterable.""" if isinstance(value, (dict, str)): raise ConfigValidationError( message_id=ConfigValidationError.INVALID_LIST, ...
120
3,427
readthedocs.org
readthedocs/config/tests/test_yaml_loader.py
.py
from readthedocs.doc_builder.backends.mkdocs import ProxyPythonName, yaml_load_safely content = """ int: 3 float: !!float 3 function: !!python/name:python_function other_function: !!python/name:module.other.function unknown: !!python/module:python_module """ def test_yaml_load_safely(): expected = { "int...
29
879
readthedocs.org
readthedocs/config/tests/utils.py
.py
def apply_fs(tmpdir, contents): """ Create the directory structure specified in ``contents``. It's a dict of filenames as keys and the file contents as values. If the value is another dict, it's a subdirectory. """ for filename, content in contents.items(): if hasattr(content, "items"):...
15
480
readthedocs.org
readthedocs/config/tests/test_config.py
.py
import os import re import textwrap from collections import OrderedDict from contextlib import nullcontext as does_not_raise import pytest from django.conf import settings from django.test import override_settings from pytest import raises from readthedocs.config import ALL, PIP, SETUPTOOLS, UV, BuildConfigV2, load f...
2,571
88,446
readthedocs.org
readthedocs/config/tests/test_parser.py
.py
from io import StringIO from pytest import raises from readthedocs.config.parser import ParseError, parse def test_parse_empty_config_file(): buf = StringIO("") with raises(ParseError): parse(buf) def test_parse_invalid_yaml(): buf = StringIO("- - !asdf") with raises(ParseError): p...
70
1,305
readthedocs.org
readthedocs/config/tests/test_find.py
.py
import os from readthedocs.config.find import find_one from .utils import apply_fs def test_find_no_files(tmpdir): with tmpdir.as_cwd(): path = find_one(os.getcwd(), r"readthedocs.yml") assert path == "" def test_find_at_root(tmpdir): apply_fs(tmpdir, {"readthedocs.yml": "", "otherfile.txt": "...
19
468
readthedocs.org
readthedocs/config/tests/test_validation.py
.py
from pytest import raises from readthedocs.config.exceptions import ConfigValidationError from readthedocs.config.validation import ( validate_bool, validate_choice, validate_list, validate_path, validate_string, ) class TestValidateBool: def test_it_accepts_true(self): assert validat...
113
3,758
readthedocs.org
readthedocs/config/tests/test_utils.py
.py
from .utils import apply_fs def test_apply_fs_with_empty_contents(tmpdir): # Doesn't do anything if second parameter is empty. apply_fs(tmpdir, {}) assert tmpdir.listdir() == [] def test_apply_fs_create_empty_file(tmpdir): # Create empty file. apply_fs(tmpdir, {"file": ""}) assert len(tmpdir...
27
756
readthedocs.org
readthedocs/core/middleware.py
.py
import structlog from django.conf import settings from django.core.exceptions import TooManyFieldsSent from django.http import HttpResponse log = structlog.get_logger(__name__) class NullCharactersMiddleware: """ Block all requests that contains NULL characters (0x00) on their GET attributes. Requests ...
93
3,180
readthedocs.org
readthedocs/core/notifications.py
.py
"""Read the Docs notifications.""" import textwrap from django.utils.translation import gettext_lazy as _ from readthedocs.notifications.constants import TIP from readthedocs.notifications.constants import WARNING from readthedocs.notifications.messages import Message from readthedocs.notifications.messages import r...
57
1,885
readthedocs.org
readthedocs/core/logs.py
.py
import sys import warnings from io import StringIO import structlog from django_structlog.middlewares.request import RequestMiddleware from structlog.dev import _pad from structlog.dev import plain_traceback from structlog.processors import _figure_out_exc_info class ReadTheDocsRequestMiddleware(RequestMiddleware): ...
228
7,274
readthedocs.org
readthedocs/core/admin.py
.py
"""Django admin interface for core models.""" from datetime import timedelta from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from django.urls import reverse from django.utils import timezone from django.utils.html import format_html from dja...
132
4,412
readthedocs.org
readthedocs/core/static.py
.py
""" Read the Docs custom static finders. NOTE: I think we can probably remove it completely, since we are not storing these files anymore inside "media/" """ from django.contrib.staticfiles.finders import FileSystemFinder class SelectiveFileSystemFinder(FileSystemFinder): """ Add user media paths in ``media...
22
622
readthedocs.org
readthedocs/core/fields.py
.py
"""Shared model fields and defaults.""" import binascii import os def default_token(): """Generate default value for token field.""" return binascii.hexlify(os.urandom(20)).decode()
10
193
readthedocs.org
readthedocs/core/context_processors.py
.py
"""Template context processors for core app.""" from django.conf import settings def readthedocs_processor(request): """ Context processor to include global settings to templates. Note that we are not using the ``request`` object at all here. It's preferable to keep it like that since it's used from...
58
2,014
readthedocs.org
readthedocs/core/models.py
.py
"""Models for the core app.""" from django.contrib.auth.models import User from django.db import models from django.urls import reverse from django.utils.translation import gettext_lazy as _ from django_extensions.db.models import TimeStampedModel from simple_history import register from readthedocs.core.history impo...
80
2,414
readthedocs.org
readthedocs/core/querysets.py
.py
class NoReprQuerySet: """ Basic queryset to override `__repr__` function due to logging issues. This may be a temporary solution for now and it can be improved to detect if we are under DEBUG and/or on an interactive shell. https://github.com/readthedocs/readthedocs.org/issues/10954 https://gi...
15
554
readthedocs.org
readthedocs/core/apps.py
.py
"""App configurations for core app.""" import structlog from django.apps import AppConfig log = structlog.get_logger(__name__) class CoreAppConfig(AppConfig): name = "readthedocs.core" verbose_name = "Core" def ready(self): # Import `readthedocs.core.logs` to set up structlog import re...
23
587
readthedocs.org
readthedocs/core/filters.py
.py
"""Extended classes for django-filter.""" import structlog from django_filters import FilterSet from django_filters import ModelChoiceFilter from django_filters import views from django_filters.fields import ModelChoiceField log = structlog.get_logger(__name__) class ModelFilterSet(FilterSet): """ Filterse...
132
5,004
readthedocs.org
readthedocs/core/finders.py
.py
import os from debug_toolbar.apps import DebugToolbarConfig from django.contrib.staticfiles.finders import AppDirectoriesFinder class DebugToolbarFinder(AppDirectoriesFinder): """ Finder to copy the static files for `debug_toolbar` even if it's not installed. We want to do this because we run `collectst...
31
1,084
readthedocs.org
readthedocs/core/adapters.py
.py
"""Allauth overrides.""" import structlog from allauth.account.adapter import DefaultAccountAdapter from allauth.account.adapter import get_adapter as get_account_adapter from allauth.core.exceptions import ImmediateHttpResponse from allauth.socialaccount.adapter import DefaultSocialAccountAdapter from allauth.sociala...
163
6,607
readthedocs.org
readthedocs/core/signals.py
.py
"""Signal handling for core app.""" import requests import structlog from allauth.account.signals import email_confirmed from django.conf import settings from django.db.models.signals import post_save from django.db.models.signals import pre_delete from django.dispatch import Signal from django.dispatch import receive...
121
4,127
readthedocs.org
readthedocs/core/history.py
.py
from functools import partial import structlog from django import forms from django.db import models from django.utils.translation import gettext_lazy as _ from simple_history.admin import SimpleHistoryAdmin from simple_history.models import HistoricalRecords from simple_history.utils import update_change_reason log...
162
4,951
readthedocs.org
readthedocs/core/permissions.py
.py
"""Objects for User permission checks.""" from django.conf import settings from django.contrib.auth.models import User from django.db.models import Q from readthedocs.core.utils.extend import SettingsOverrideObject from readthedocs.organizations.constants import ADMIN_ACCESS from readthedocs.organizations.constants i...
198
7,449
readthedocs.org
readthedocs/core/settings.py
.py
"""Class based settings for complex settings inheritance.""" import inspect import sys class Settings: """Class-based settings wrapper.""" @classmethod def load_settings(cls, module_name): """ Export class variables and properties to module namespace. This will export and class...
27
804
readthedocs.org
readthedocs/core/mixins.py
.py
"""Common mixin classes for views.""" from django.contrib import messages from django.contrib.auth.mixins import LoginRequiredMixin from django.http import HttpResponseRedirect from vanilla import DeleteView from vanilla import ListView from readthedocs.core.tasks import delete_object from readthedocs.proxito.cache i...
103
3,396
readthedocs.org
readthedocs/core/unresolver.py
.py
import re from dataclasses import dataclass from enum import Enum from enum import auto from urllib.parse import ParseResult from urllib.parse import urlparse import structlog from django.conf import settings from django.db.models.functions import Length from readthedocs.builds.constants import EXTERNAL from readthed...
667
24,432
readthedocs.org
readthedocs/core/db.py
.py
""" Custom database routers. https://docs.djangoproject.com/en/4.0/topics/db/multi-db/#automatic-database-routing """ from collections import defaultdict class MapAppsRouter: """ Router to map Django applications to a specific database. :py:attr:`apps_to_db` is used to map an application to a database,...
33
1,011
readthedocs.org
readthedocs/core/forms.py
.py
"""Forms for core app.""" from dataclasses import dataclass import structlog from django import forms from django.conf import settings from django.contrib.auth.models import User from django.core.exceptions import NON_FIELD_ERRORS from django.forms.fields import CharField from django.utils.translation import gettext_...
320
10,501
readthedocs.org
readthedocs/core/resolver.py
.py
"""URL resolver for documentation.""" from functools import cache from urllib.parse import urlunparse import structlog from django.conf import settings from readthedocs.builds.constants import EXTERNAL from readthedocs.builds.constants import INTERNAL from readthedocs.core.utils.url import unsafe_join_url_path from ...
392
14,705
readthedocs.org
readthedocs/core/tasks.py
.py
"""Basic tasks.""" import math import redis import structlog from django.apps import apps from django.conf import settings from django.contrib.auth.models import User from django.core.mail import EmailMultiAlternatives from readthedocs.builds.utils import memcache_lock from readthedocs.core.history import set_change...
113
3,494
readthedocs.org
readthedocs/core/management/commands/collectstatic.py
.py
""" Override to send ``pre_collectstatic`` and ``post_collectstatic`` signal. ``post_collectstatic`` is used to purge the CDN of static files. """ from django.contrib.staticfiles.management.commands import collectstatic from readthedocs.core.signals import post_collectstatic from readthedocs.core.signals import pre_...
19
585
readthedocs.org
readthedocs/core/management/commands/contact_owners.py
.py
import sys from pathlib import Path import structlog from django.conf import settings from django.contrib.auth import get_user_model from django.core.management.base import BaseCommand from readthedocs.core.permissions import AdminPermission from readthedocs.core.utils.contact import contact_users from readthedocs.or...
208
6,851
readthedocs.org
readthedocs/core/tests/test_history.py
.py
from unittest import mock from django.contrib.auth.models import User from django.test import TestCase from django.urls import reverse from django_dynamic_fixture import get from readthedocs.projects.models import Project class TestHistoricalModels(TestCase): def setUp(self): self.user = get(User) ...
54
2,297
readthedocs.org
readthedocs/core/tests/test_homepage.py
.py
import django_dynamic_fixture as fixture from django.urls import reverse from django.contrib.auth.models import User from django.test import TestCase, override_settings class HomepageTest(TestCase): def test_homepage_auth(self): user = fixture.get( User, username="user", )...
49
1,501
readthedocs.org
readthedocs/core/tests/test_signup.py
.py
from unittest.mock import patch from allauth.account.models import EmailAddress from allauth.account.signals import email_confirmed from django.conf import settings from django.test import TestCase class TestNewsletterSignup(TestCase): def setUp(self): self.form_data = { "email": "test123@gma...
55
1,863
readthedocs.org
readthedocs/core/tests/test_user_admin_actions.py
.py
from unittest.mock import patch import django_dynamic_fixture as fixture from django import urls from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME from django.contrib.auth.models import User from django.test import TestCase class UserAdminActionsTest(TestCase): @classmethod def setUpTestData(cls)...
33
1,037
readthedocs.org
readthedocs/core/tests/test_permissions.py
.py
from django.contrib.auth.models import User from django.test import TestCase, override_settings from django_dynamic_fixture import get from readthedocs.core.permissions import AdminPermission from readthedocs.organizations.constants import ADMIN_ACCESS, READ_ONLY_ACCESS from readthedocs.organizations.models import Org...
99
3,760
readthedocs.org
readthedocs/core/tests/test_contact.py
.py
from unittest import mock from django.contrib.auth import get_user_model from django.test import TestCase from django_dynamic_fixture import get from readthedocs.core.utils.contact import contact_users User = get_user_model() class TestContactUsers(TestCase): def setUp(self): self.user = get(User, user...
59
1,798
readthedocs.org
readthedocs/core/tests/test_adapters.py
.py
from unittest import mock from allauth.core.exceptions import ImmediateHttpResponse from allauth.socialaccount.adapter import get_adapter as get_social_account_adapter from allauth.socialaccount.models import SocialAccount, SocialLogin from allauth.socialaccount.providers.github.provider import GitHubProvider from dja...
217
7,525
readthedocs.org
readthedocs/core/tests/test_signals.py
.py
import pytest from django.contrib.auth.models import User from django_dynamic_fixture import get from readthedocs.builds.models import Version from readthedocs.organizations.models import Organization, Team, TeamMember from readthedocs.projects.models import Project @pytest.mark.django_db class TestProjectOrganizati...
77
2,855
readthedocs.org
readthedocs/core/tests/test_db_utils.py
.py
import pytest from django.test import TestCase from django_dynamic_fixture import get from readthedocs.builds.models import Version from readthedocs.core.utils.db import delete_in_batches, raw_delete_in_batches from readthedocs.projects.models import Project class TestDeleteInBatches(TestCase): """Tests for the ...
342
15,111
readthedocs.org
readthedocs/core/tests/test_filesystem_utils.py
.py
from pathlib import Path from tempfile import mkdtemp import pytest from django.core.exceptions import SuspiciousFileOperation from django.test import TestCase, override_settings from readthedocs.core.utils.filesystem import ( assert_path_is_inside_docroot, safe_copytree, safe_open, safe_rmtree, ) fro...
220
7,669
readthedocs.org
readthedocs/core/utils/spam.py
.py
""" Spam fighting utilities. This is a proxy for the spam fighting utilities that are in the readthedocsext.spamfighting private module. """ from django.conf import settings from readthedocs.core.permissions import AdminPermission def get_spam_score(project): if "readthedocsext.spamfighting" in settings.INSTAL...
68
1,720
readthedocs.org
readthedocs/core/utils/filesystem.py
.py
""" File system utilities. Provides wrappers around common path operations with some security checks in place. """ import shutil from pathlib import Path import structlog from django.conf import settings from django.core.exceptions import SuspiciousFileOperation from readthedocs.doc_builder.exceptions import BuildU...
176
6,023
readthedocs.org
readthedocs/core/utils/admin.py
.py
import json from django.utils.safestring import mark_safe from pygments import highlight from pygments.formatters import HtmlFormatter from pygments.lexers import JsonLexer def pretty_json_field(instance, field): """ Display a pretty version of a JSON field in the admin. Thanks to PyDanny: https://www.p...
29
813
readthedocs.org
readthedocs/core/utils/extend.py
.py
"""Patterns for extending Read the Docs.""" import inspect from django.conf import settings from django.utils.module_loading import import_string def get_override_class(proxy_class, default_class=None): """ Determine which class to use in an override class. The `proxy_class` is the main class that is u...
81
2,827
readthedocs.org
readthedocs/core/utils/objects.py
.py
# Sentinel value to check if a default value was provided, # so we can differentiate when None is provided as a default value # and when it was not provided at all. _DEFAULT = object() def get_dotted_attribute(obj, attribute, default=_DEFAULT): """ Allow to get nested attributes from an object using a dot not...
23
827
readthedocs.org
readthedocs/core/utils/__init__.py
.py
"""Common utility functions.""" import re import structlog from django.conf import settings from django.core.mail import EmailMessage from django.core.mail import EmailMultiAlternatives from django.template.loader import render_to_string from django.utils.functional import keep_lazy from django.utils.safestring impor...
483
16,878
readthedocs.org
readthedocs/core/utils/users.py
.py
from django.contrib.auth.models import User def get_user_by_username_or_email(username_or_email): """Get a user by their username or email address.""" # SECURITY: Check for email address if the username contains an "@" symbol, # to prevent fetching a user with an username that matches # the email addr...
14
596
readthedocs.org
readthedocs/core/utils/contact.py
.py
import markdown import structlog from django.conf import settings from django.core.mail import send_mail from django.template import Context from django.template import Engine log = structlog.get_logger(__name__) # TODO: re-implement sending notifications to users. # This needs more thinking because the notificatio...
103
3,502
readthedocs.org
readthedocs/core/utils/url.py
.py
"""URL handling utilities.""" def unsafe_join_url_path(base, *args): """ Joins a base URL path with one or more path components. This does a simple join of the base path with the path components, inserting a slash between each component. The resulting path will always start with a slash. .. ...
22
696
readthedocs.org
readthedocs/core/utils/db.py
.py
from collections import Counter from itertools import batched def delete_in_batches( queryset, batch_size=50, start: int | None = None, end: int | None = None ) -> tuple[int, dict]: """ Delete a queryset in batches to avoid long transactions or big queries. When deleting a large number of records at ...
108
4,266
readthedocs.org
readthedocs/core/utils/requests.py
.py
import structlog log = structlog.get_logger(__name__) # noqa def is_suspicious_request(request) -> bool: """ Returns True if the request is suspicious. This function is used to detect bots and spammers, we use Cloudflare to detect them. """ # This header is set from Cloudflare, # it go...
26
740
readthedocs.org
readthedocs/core/utils/tasks/__init__.py
.py
"""Common task exports.""" from .permission_checks import ( # noqa for unused import user_id_matches, user_id_matches_or_superuser, ) from .public import PublicTask # noqa from .public import TaskNoPermission # noqa from .retrieve import TaskNotFound # noqa
10
271
readthedocs.org
readthedocs/core/utils/tasks/public.py
.py
"""Celery tasks with publicly viewable status.""" from celery import Task from celery import states from django.conf import settings __all__ = ( "PublicTask", "TaskNoPermission", ) STATUS_UPDATES_ENABLED = not settings.CELERY_TASK_ALWAYS_EAGER # pylint: disable=abstract-method # pylint: disable=broad-exce...
121
3,672
readthedocs.org
readthedocs/core/utils/tasks/retrieve.py
.py
"""Utilities for retrieving task data.""" __all__ = ("TaskNotFound",) class TaskNotFound(Exception): def __init__(self, task_id, *args, **kwargs): message = "No public task found with id {id}".format(id=task_id) super().__init__(message, *args, **kwargs)
10
278
readthedocs.org
readthedocs/core/utils/tasks/permission_checks.py
.py
"""Permission checks for tasks.""" __all__ = ( "user_id_matches", "user_id_matches_or_superuser", ) def user_id_matches(request, state, context): # pylint: disable=unused-argument user_id = context.get("user_id", None) if user_id is not None and request.user.is_authenticated: if request.user...
19
519
readthedocs.org
readthedocs/core/views/__init__.py
.py
""" Core views. Including the main homepage, documentation and header rendering, and server errors. """ import structlog from django.conf import settings from django.http import Http404 from django.http import JsonResponse from django.shortcuts import redirect from django.urls import reverse from django.views.generic...
171
5,820
readthedocs.org
readthedocs/core/views/hooks.py
.py
"""Views pertaining to builds.""" from dataclasses import dataclass from typing import Literal import structlog from readthedocs.api.v2.models import BuildAPIKey from readthedocs.builds.constants import EXTERNAL from readthedocs.builds.constants import EXTERNAL_VERSION_STATE_CLOSED from readthedocs.builds.constants ...
185
5,909
readthedocs.org
readthedocs/core/templatetags/privacy_tags.py
.py
"""Template tags to query projects by privacy.""" from django import template from readthedocs.core.permissions import AdminPermission from readthedocs.projects.models import Project register = template.Library() @register.filter def is_admin(user, project): return AdminPermission.is_admin(user, project) @r...
30
705
readthedocs.org
readthedocs/core/templatetags/core_tags.py
.py
"""Template tags for core app.""" import json from django import template from django.core.serializers.json import DjangoJSONEncoder from django.utils.safestring import mark_safe from readthedocs import __version__ from readthedocs.core.forms import RichSelect from readthedocs.core.resolver import Resolver from read...
112
2,833
readthedocs.org
readthedocs/core/templatetags/readthedocs/socialaccounts.py
.py
from allauth.socialaccount.adapter import get_adapter from allauth.socialaccount.providers.github.provider import GitHubProvider from django import forms from django import template from readthedocs.allauth.providers.githubapp.provider import GitHubAppProvider from readthedocs.oauth.utils import is_access_revoked as u...
44
1,226
readthedocs.org
readthedocs/api/mixins.py
.py
import functools import structlog from django.http import Http404 from django.utils.functional import cached_property from readthedocs.core.unresolver import UnresolverError from readthedocs.core.unresolver import unresolve from readthedocs.core.utils import get_cache_tag from readthedocs.proxito.cache import add_cac...
109
3,022
readthedocs.org
readthedocs/api/v2/admin.py
.py
from django.contrib import admin from rest_framework_api_key.admin import APIKeyModelAdmin from readthedocs.api.v2.models import BuildAPIKey @admin.register(BuildAPIKey) class BuildAPIKeyAdmin(APIKeyModelAdmin): raw_id_fields = ["project"] search_fields = [*APIKeyModelAdmin.search_fields, "project__slug"]
11
318
readthedocs.org
readthedocs/api/v2/utils.py
.py
"""Utility functions that are used by both views and celery tasks.""" import itertools import re import structlog from django.conf import settings from rest_framework.pagination import PageNumberPagination from readthedocs.builds.constants import BRANCH from readthedocs.builds.constants import INTERNAL from readthed...
316
10,571
readthedocs.org
readthedocs/api/v2/models.py
.py
from datetime import timedelta from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ from rest_framework_api_key.models import AbstractAPIKey from rest_framework_api_key.models import BaseAPIKeyManager from readthedocs.projects.models import Project cl...
67
2,370
readthedocs.org
readthedocs/api/v2/apps.py
.py
from django.apps import AppConfig class APIV2Config(AppConfig): name = "readthedocs.api.v2" verbose_name = "API V2"
7
126
readthedocs.org
readthedocs/api/v2/serializers.py
.py
"""Defines serializers for each of our models.""" from allauth.socialaccount.models import SocialAccount from django.core.exceptions import ObjectDoesNotExist from django.utils.translation import gettext as _ from generic_relations.relations import GenericRelatedField from rest_framework import serializers from readt...
429
14,428
readthedocs.org
readthedocs/api/v2/adapters.py
.py
from requests.adapters import HTTPAdapter from requests_toolbelt.adapters.host_header_ssl import HostHeaderSSLAdapter class TimeoutAdapter: """ Adapter to inject ``timeout`` to all the requests. Allows us to not wait forever when querying our API internally from the builders and make the build fail f...
31
852
readthedocs.org
readthedocs/api/v2/urls.py
.py
"""Define routes between URL paths and views/endpoints.""" from django.urls import include from django.urls import path from django.urls import re_path from rest_framework import routers from readthedocs.api.v2.views import core_views from readthedocs.api.v2.views import integrations from readthedocs.api.v2.views imp...
110
3,257
readthedocs.org
readthedocs/api/v2/client.py
.py
"""Simple client to access our API with Slumber credentials.""" import requests import structlog from django.conf import settings from rest_framework.renderers import JSONRenderer from slumber import API from slumber import serialize from urllib3.util.retry import Retry from .adapters import TimeoutHostHeaderSSLAdapt...
67
2,011
readthedocs.org
readthedocs/api/v2/permissions.py
.py
"""Defines access permissions for the API.""" from rest_framework import permissions from rest_framework_api_key.permissions import BaseHasAPIKey from rest_framework_api_key.permissions import KeyParser from readthedocs.api.v2.models import BuildAPIKey class IsOwner(permissions.BasePermission): """Custom permis...
93
2,630
readthedocs.org
readthedocs/api/v2/tasks.py
.py
from datetime import timedelta import structlog from django.utils import timezone from readthedocs.api.v2.models import BuildAPIKey from readthedocs.worker import app log = structlog.get_logger(__name__) @app.task(queue="web") def delete_old_revoked_build_api_keys(days=15): """ Delete revoked and expired ...
31
921