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 |
|---|---|---|---|---|---|
django-rest-framework | tests/test_filters.py | .py | import datetime
from importlib import reload as reload_module
import pytest
from django.core.exceptions import ImproperlyConfigured
from django.db import models
from django.db.models import CharField, Transform
from django.db.models.functions import Concat, Upper
from django.test import SimpleTestCase, TestCase
from d... | 1,067 | 41,018 |
django-rest-framework | tests/test_model_serializer.py | .py | """
The `ModelSerializer` and `HyperlinkedModelSerializer` classes are essentially
shortcuts for automatically creating serializers based on a given model class.
These tests deal with ensuring that we correctly map the model fields onto
an appropriate set of serializer fields for each case.
"""
import datetime
import ... | 1,501 | 57,251 |
django-rest-framework | tests/test_atomic_requests.py | .py | import unittest
from django.db import connection, connections, transaction
from django.http import Http404
from django.test import TestCase, TransactionTestCase, override_settings
from django.urls import path
from rest_framework import status
from rest_framework.exceptions import APIException
from rest_framework.resp... | 255 | 8,781 |
django-rest-framework | tests/test_decorators.py | .py | import sys
import pytest
from django.core.exceptions import ImproperlyConfigured
from django.test import TestCase
from rest_framework import status
from rest_framework.authentication import BasicAuthentication
from rest_framework.decorators import (
action, api_view, authentication_classes, content_negotiation_cl... | 502 | 17,002 |
django-rest-framework | tests/test_encoders.py | .py | import ipaddress
from datetime import date, datetime, timedelta, timezone
from decimal import Decimal
from uuid import uuid4
import pytest
from django.test import TestCase
from rest_framework.utils.encoders import JSONEncoder
from rest_framework.utils.serializer_helpers import ReturnList
utc = timezone.utc
class M... | 136 | 4,085 |
django-rest-framework | tests/test_fields.py | .py | import datetime
import math
import os
import re
import uuid
import warnings
from decimal import ROUND_DOWN, ROUND_UP, Decimal
from enum import auto
from unittest.mock import patch
from zoneinfo import ZoneInfo
import pytest
from django.core.exceptions import ValidationError as DjangoValidationError
from django.db.mode... | 2,965 | 98,737 |
django-rest-framework | tests/test_serializer_bulk_update.py | .py | """
Tests to cover bulk create and update using serializers.
"""
from django.test import TestCase
from rest_framework import serializers
class BulkCreateSerializerTests(TestCase):
"""
Creating multiple instances using serializers.
"""
def setUp(self):
class BookSerializer(serializers.Seriali... | 118 | 3,694 |
django-rest-framework | tests/test_htmlrenderer.py | .py | import django.template.loader
import pytest
from django.core.exceptions import ImproperlyConfigured, PermissionDenied
from django.http import Http404
from django.template import TemplateDoesNotExist, engines
from django.test import TestCase, override_settings
from django.urls import path
from rest_framework import sta... | 178 | 6,665 |
django-rest-framework | tests/test_viewsets.py | .py | from functools import wraps
import pytest
from django.db import models
from django.test import TestCase, override_settings
from django.urls import include, path
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.routers impor... | 343 | 11,764 |
django-rest-framework | tests/test_utils.py | .py | from unittest import mock
from django.test import TestCase, override_settings
from django.urls import path
from rest_framework.decorators import action
from rest_framework.routers import SimpleRouter
from rest_framework.serializers import ModelSerializer
from rest_framework.utils import json
from rest_framework.utils... | 277 | 8,707 |
django-rest-framework | tests/test_relations.py | .py | import uuid
import pytest
from _pytest.monkeypatch import MonkeyPatch
from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist
from django.test import override_settings
from django.urls import path
from django.utils.datastructures import MultiValueDict
from rest_framework import relations, serializ... | 521 | 20,702 |
django-rest-framework | tests/conftest.py | .py | import contextlib
import os
import dj_database_url
import django
import pytest
from django.apps import apps
from django.core import management
from django.core.management.color import no_style
from django.db import connection
@pytest.fixture
def reset_sequences():
"""
Reset all database sequences so PKs star... | 166 | 5,545 |
django-rest-framework | tests/importable/__init__.py | .py | """
This test "app" exists to ensure that parts of Django REST Framework can be
imported/invoked before Django itself has been fully initialized.
"""
from rest_framework import compat, serializers # noqa
# test initializing fields with lazy translations
class ExampleSerializer(serializers.Serializer):
charfield... | 17 | 750 |
django-rest-framework | tests/importable/test_installed.py | .py | from django.conf import settings
from tests import importable
def test_installed():
# ensure the test app hasn't been removed from the test suite
assert 'tests.importable' in settings.INSTALLED_APPS
def test_compat():
assert hasattr(importable, 'compat')
def test_serializer_fields_initialization():
... | 25 | 695 |
django-rest-framework | tests/schemas/test_get_schema_view.py | .py | from django.test import TestCase
from rest_framework import renderers
from rest_framework.schemas import get_schema_view, openapi
class GetSchemaViewTests(TestCase):
"""For the get_schema_view() helper."""
def test_openapi(self):
schema_view = get_schema_view(title="With OpenAPI")
assert isin... | 13 | 475 |
django-rest-framework | tests/schemas/test_managementcommand.py | .py | import io
import os
import tempfile
import pytest
from django.core.management import call_command
from django.test import TestCase
from django.test.utils import override_settings
from django.urls import path
from rest_framework.compat import uritemplate, yaml
from rest_framework.utils import json
from rest_framework.... | 84 | 2,630 |
django-rest-framework | tests/schemas/views.py | .py | import uuid
from datetime import timedelta
from django.core.validators import (
DecimalValidator, MaxLengthValidator, MaxValueValidator,
MinLengthValidator, MinValueValidator, RegexValidator
)
from django.db import models
from rest_framework import generics, permissions, serializers
from rest_framework.decora... | 251 | 7,533 |
django-rest-framework | tests/schemas/test_openapi.py | .py | import uuid
import warnings
import pytest
from django.db import models
from django.test import RequestFactory, TestCase, override_settings
from django.urls import path
from django.utils.safestring import SafeString
from django.utils.translation import gettext_lazy as _
from rest_framework import filters, generics, pa... | 1,366 | 48,305 |
django-rest-framework | tests/browsable_api/test_form_rendering.py | .py | from django.test import TestCase
from rest_framework import generics, renderers, serializers, status
from rest_framework.response import Response
from rest_framework.test import APIRequestFactory
from tests.models import BasicModel
factory = APIRequestFactory()
class BasicSerializer(serializers.ModelSerializer):
... | 85 | 2,795 |
django-rest-framework | tests/browsable_api/auth_urls.py | .py | from django.urls import include, path
from .views import MockView
urlpatterns = [
path('', MockView.as_view()),
path('auth/', include('rest_framework.urls', namespace='rest_framework')),
]
| 9 | 199 |
django-rest-framework | tests/browsable_api/no_auth_urls.py | .py | from django.urls import path
from .views import BasicModelWithUsersViewSet, MockView
urlpatterns = [
path('', MockView.as_view()),
path('basicviewset', BasicModelWithUsersViewSet.as_view({'get': 'list'})),
]
| 9 | 218 |
django-rest-framework | tests/browsable_api/serializers.py | .py | from rest_framework.serializers import ModelSerializer
from tests.models import BasicModelWithUsers
class BasicSerializer(ModelSerializer):
class Meta:
model = BasicModelWithUsers
fields = '__all__'
| 9 | 221 |
django-rest-framework | tests/browsable_api/views.py | .py | from rest_framework import authentication, renderers
from rest_framework.permissions import BasePermission
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from ..models import BasicModelWithUsers
from .serializers import BasicSerial... | 34 | 1,231 |
django-rest-framework | tests/browsable_api/test_browsable_nested_api.py | .py | from django.test import TestCase
from django.test.utils import override_settings
from django.urls import path
from rest_framework import serializers
from rest_framework.generics import ListCreateAPIView
from rest_framework.renderers import BrowsableAPIRenderer
class NestedSerializer(serializers.Serializer):
one ... | 41 | 1,294 |
django-rest-framework | tests/browsable_api/test_browsable_api.py | .py | from django.contrib.auth.models import User
from django.test import TestCase, override_settings
from rest_framework.permissions import IsAuthenticated
from rest_framework.test import APIClient
from .views import BasicModelWithUsersViewSet, OrganizationPermissions
@override_settings(ROOT_URLCONF='tests.browsable_api... | 108 | 3,971 |
django-rest-framework | tests/authentication/models.py | .py | from django.conf import settings
from django.db import models
class CustomToken(models.Model):
key = models.CharField(max_length=40, primary_key=True)
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
| 8 | 241 |
django-rest-framework | tests/authentication/test_authentication.py | .py | import base64
import pytest
from django.conf import settings
from django.contrib.auth.models import User
from django.http import HttpResponse
from django.test import TestCase, override_settings
from django.urls import include, path
from rest_framework import (
HTTP_HEADER_ENCODING, exceptions, permissions, render... | 639 | 23,599 |
django-rest-framework | tests/generic_relations/models.py | .py | from django.contrib.contenttypes.fields import (
GenericForeignKey, GenericRelation
)
from django.contrib.contenttypes.models import ContentType
from django.db import models
class Tag(models.Model):
"""
Tags have a descriptive slug, and are attached to an arbitrary object.
"""
tag = models.SlugFie... | 41 | 1,015 |
django-rest-framework | tests/generic_relations/test_generic_relations.py | .py | from django.test import TestCase
from rest_framework import serializers
from .models import Bookmark, Note, Tag
class TestGenericRelations(TestCase):
def setUp(self):
self.bookmark = Bookmark.objects.create(url='https://www.djangoproject.com/')
Tag.objects.create(tagged_item=self.bookmark, tag='... | 65 | 2,064 |
django-rest-framework | rest_framework/throttling.py | .py | """
Provides various throttling policies.
"""
import time
from django.core.cache import cache as default_cache
from django.core.exceptions import ImproperlyConfigured
from rest_framework.settings import api_settings
class BaseThrottle:
"""
Rate throttling of requests.
"""
def allow_request(self, re... | 251 | 8,065 |
django-rest-framework | rest_framework/reverse.py | .py | """
Provide urlresolver functions that return fully qualified URLs or view names
"""
from django.urls import NoReverseMatch
from django.urls import reverse as django_reverse
from django.utils.functional import lazy
from rest_framework.settings import api_settings
from rest_framework.utils.urls import replace_query_par... | 67 | 2,144 |
django-rest-framework | rest_framework/fields.py | .py | import contextlib
import copy
import datetime
import decimal
import functools
import inspect
import re
import uuid
import warnings
from collections.abc import Mapping
from enum import Enum
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.core.exceptions import Validati... | 1,979 | 71,938 |
django-rest-framework | rest_framework/metadata.py | .py | """
The metadata API is used to allow customization of how `OPTIONS` requests
are handled. We currently provide a single default implementation that returns
some fairly ad-hoc information about the view.
Future implementations might use JSON schema or other definitions in order
to return this information in a more sta... | 153 | 5,862 |
django-rest-framework | rest_framework/exceptions.py | .py | """
Handled exceptions raised by REST framework.
In addition, Django's built in 403 and 404 exceptions are handled.
(`django.http.Http404` and `django.core.exceptions.PermissionDenied`)
"""
import math
from django.http import JsonResponse
from django.utils.encoding import force_str
from django.utils.translation impor... | 265 | 8,159 |
django-rest-framework | rest_framework/authentication.py | .py | """
Provides various authentication policies.
"""
import base64
import binascii
from django.contrib.auth import authenticate, get_user_model
from django.middleware.csrf import CsrfViewMiddleware
from django.utils.translation import gettext_lazy as _
from rest_framework import HTTP_HEADER_ENCODING, exceptions
def ge... | 233 | 7,699 |
django-rest-framework | rest_framework/apps.py | .py | from django.apps import AppConfig
class RestFrameworkConfig(AppConfig):
name = 'rest_framework'
verbose_name = "Django REST framework"
def ready(self):
# Add System checks
from .checks import pagination_system_check # NOQA
| 11 | 255 |
django-rest-framework | rest_framework/request.py | .py | """
The Request class is used as a wrapper around the standard request object.
The wrapped request then offers a richer API, in particular :
- content automatically parsed according to `Content-Type` header,
and available as `request.data`
- full support of PUT method, including support for file uploads... | 454 | 15,288 |
django-rest-framework | rest_framework/filters.py | .py | """
Provides generic filtering backends that can be used to filter the results
returned by list views.
"""
import operator
from functools import reduce
from django.core.exceptions import FieldDoesNotExist, ImproperlyConfigured
from django.db import models
from django.db.models.constants import LOOKUP_SEP
from django.t... | 360 | 13,582 |
django-rest-framework | rest_framework/urlpatterns.py | .py | from django.urls import URLResolver, include, path, re_path, register_converter
from django.urls.converters import get_converters
from django.urls.resolvers import RoutePattern
from rest_framework.settings import api_settings
def _get_format_path_converter(allowed):
if allowed:
if len(allowed) == 1:
... | 119 | 4,401 |
django-rest-framework | rest_framework/__init__.py | .py | r"""
______ _____ _____ _____ __
| ___ \ ___/ ___|_ _| / _| | |
| |_/ / |__ \ `--. | | | |_ _ __ __ _ _ __ ___ _____ _____ _ __| |__
| /| __| `--. \ | | | _| '__/ _` | '_ ` _ \ / _ \ \ /\ / / _ \| '__| |/ /
| |\ \| |___/\__/ / | | | | | | | (_| | | |... | 25 | 821 |
django-rest-framework | rest_framework/generics.py | .py | """
Generic views that provide commonly needed behavior.
"""
from django.core.exceptions import ValidationError
from django.db.models.query import QuerySet
from django.http import Http404
from django.shortcuts import get_object_or_404 as _get_object_or_404
from rest_framework import mixins, views
from rest_framework.s... | 296 | 10,163 |
django-rest-framework | rest_framework/viewsets.py | .py | """
ViewSets are essentially just a type of class based view, that doesn't provide
any method handlers, such as `get()`, `post()`, etc... but instead has actions,
such as `list()`, `retrieve()`, `create()`, etc...
Actions are only bound to methods at the point of instantiating the views.
user_list = UserViewSet.a... | 254 | 9,206 |
django-rest-framework | rest_framework/serializers.py | .py | """
Serializers and ModelSerializers are similar to Forms and ModelForms.
Unlike forms, they are not constrained to dealing with HTML output, and
form encoded input.
Serialization in REST framework is a two-phase process:
1. Serializers marshal between complex types like model instances, and
python primitives.
2. The... | 1,766 | 70,833 |
django-rest-framework | rest_framework/views.py | .py | """
Provides an APIView class that is the base of all views in REST framework.
"""
from django.conf import settings
from django.core.exceptions import PermissionDenied
from django.db import connections, models
from django.http import Http404
from django.http.response import HttpResponseBase
from django.utils.cache impo... | 539 | 19,629 |
django-rest-framework | rest_framework/checks.py | .py | from django.core.checks import Tags, Warning, register
@register(Tags.compatibility)
def pagination_system_check(app_configs, **kwargs):
errors = []
# Use of default page size setting requires a default Paginator class
from rest_framework.settings import api_settings
if api_settings.PAGE_SIZE and not ... | 22 | 970 |
django-rest-framework | rest_framework/routers.py | .py | """
Routers provide a convenient and consistent way of automatically
determining the URL conf for your API.
They are used by simply instantiating a Router class, and then registering
all the required ViewSets with that router.
For example, you might have a `urls.py` that looks something like this:
router = route... | 391 | 13,923 |
django-rest-framework | rest_framework/urls.py | .py | """
Login and logout views for the browsable API.
Add these to your root URLconf if you're using the browsable API and
your API requires authentication:
urlpatterns = [
...
path('auth/', include('rest_framework.urls'))
]
You should make sure your authentication settings include `SessionAuthen... | 22 | 615 |
django-rest-framework | rest_framework/negotiation.py | .py | """
Content negotiation deals with selecting an appropriate renderer given the
incoming request. Typically this will be based on the request's Accept header.
"""
from django.http import Http404
from rest_framework import exceptions
from rest_framework.settings import api_settings
from rest_framework.utils.mediatypes ... | 98 | 4,032 |
django-rest-framework | rest_framework/status.py | .py | """
Descriptive HTTP status codes, for code readability.
See RFC 2616 - https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
And RFC 6585 - https://tools.ietf.org/html/rfc6585
And RFC 4918 - https://tools.ietf.org/html/rfc4918
"""
def is_informational(code):
return 100 <= code <= 199
def is_success(code):
... | 94 | 2,547 |
django-rest-framework | rest_framework/permissions.py | .py | """
Provides a set of pluggable permission policies.
"""
from django.http import Http404
from rest_framework import exceptions
SAFE_METHODS = ('GET', 'HEAD', 'OPTIONS')
class OperationHolderMixin:
def __and__(self, other):
return OperandHolder(AND, self, other)
def __or__(self, other):
retu... | 315 | 9,588 |
django-rest-framework | rest_framework/parsers.py | .py | """
Parsers are used to parse the content of incoming HTTP requests.
They give us a generic way of being able to handle various media types
on the request, such as form content or json encoded data.
"""
import codecs
import contextlib
from django.conf import settings
from django.core.files.uploadhandler import StopF... | 207 | 7,717 |
django-rest-framework | rest_framework/settings.py | .py | """
Settings for REST framework are all namespaced in the REST_FRAMEWORK setting.
For example your project's `settings.py` file might look like this:
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': [
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.TemplateHTMLRenderer',
],
... | 262 | 8,060 |
django-rest-framework | rest_framework/decorators.py | .py | """
The most important decorator in this module is `@api_view`, which is used
for writing function-based views with REST framework.
There are also various decorators for setting the API policies on function
based views, as well as the `@action` decorator, which is used to annotate
methods on viewsets that should be in... | 301 | 10,305 |
django-rest-framework | rest_framework/compat.py | .py | """
The `compat` module provides support for backwards compatibility with older
versions of Django/Python, and compatibility wrappers around optional packages.
"""
import django
from django.views.generic import View
def unicode_http_header(value):
# Coerce HTTP header value to unicode.
if isinstance(value, by... | 159 | 4,432 |
django-rest-framework | rest_framework/mixins.py | .py | """
Basic building blocks for generic class based views.
We don't bind behavior to http method handlers yet,
which allows mixin classes to be composed in interesting ways.
"""
from rest_framework import status
from rest_framework.response import Response
from rest_framework.settings import api_settings
class CreateM... | 96 | 2,936 |
django-rest-framework | rest_framework/pagination.py | .py | """
Pagination serializers determine the structure of the output that should
be used for paginated responses.
"""
import contextlib
from base64 import b64decode, b64encode
from collections import namedtuple
from urllib import parse
from django.core.paginator import InvalidPage
from django.core.paginator import Pagina... | 896 | 32,694 |
django-rest-framework | rest_framework/versioning.py | .py | import re
from django.utils.translation import gettext_lazy as _
from rest_framework import exceptions
from rest_framework.compat import unicode_http_header
from rest_framework.reverse import _reverse
from rest_framework.settings import api_settings
from rest_framework.templatetags.rest_framework import replace_query... | 187 | 6,801 |
django-rest-framework | rest_framework/relations.py | .py | import contextlib
import sys
from operator import attrgetter
from urllib import parse
from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist
from django.db.models import Manager
from django.db.models.query import QuerySet
from django.urls import NoReverseMatch, Resolver404, get_script_prefix, reso... | 586 | 21,238 |
django-rest-framework | rest_framework/test.py | .py | # Note that we import as `DjangoRequestFactory` and `DjangoClient` in order
# to make it harder for the user to import the wrong thing without realizing.
import io
from contextlib import contextmanager
from importlib import import_module
from django.conf import settings
from django.core.exceptions import ImproperlyCon... | 407 | 14,953 |
django-rest-framework | rest_framework/response.py | .py | """
The Response class in REST framework is similar to HTTPResponse, except that
it is initialized with unrendered data, instead of a pre-rendered string.
The appropriate renderer is called during Django's template response rendering.
"""
from http.client import responses
from django.template.response import SimpleTe... | 108 | 3,543 |
django-rest-framework | rest_framework/validators.py | .py | """
We perform uniqueness checks explicitly on the serializer class, rather
the using Django's `.full_clean()`.
This gives us better separation of concerns, allows us to use single-step
object creation, and makes it possible to switch between using the implicit
`ModelSerializer` class and an equivalent explicit `Seria... | 373 | 14,340 |
django-rest-framework | rest_framework/renderers.py | .py | """
Renderers are used to serialize a response into specific media types.
They give us a generic way of being able to handle various media types
on the response, such as JSON encoded data or HTML output.
REST framework also provides an HTML renderer that renders the browsable API.
"""
import contextlib
import dateti... | 944 | 36,921 |
django-rest-framework | rest_framework/management/commands/generateschema.py | .py | from django.core.management.base import BaseCommand
from django.utils.module_loading import import_string
from rest_framework import renderers
from rest_framework.schemas.openapi import SchemaGenerator
class Command(BaseCommand):
help = "Generates configured API schema for project."
def add_arguments(self, ... | 49 | 2,061 |
django-rest-framework | rest_framework/authtoken/admin.py | .py | from django.contrib import admin
from django.contrib.admin.utils import quote
from django.contrib.admin.views.main import ChangeList
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
f... | 54 | 1,943 |
django-rest-framework | rest_framework/authtoken/models.py | .py | import secrets
from django.conf import settings
from django.db import models
from django.utils.translation import gettext_lazy as _
class Token(models.Model):
"""
The default authorization token model.
"""
key = models.CharField(_("Key"), max_length=40, primary_key=True)
user = models.OneToOneFie... | 64 | 1,944 |
django-rest-framework | rest_framework/authtoken/apps.py | .py | from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class AuthTokenConfig(AppConfig):
name = 'rest_framework.authtoken'
verbose_name = _("Auth Token")
| 8 | 198 |
django-rest-framework | rest_framework/authtoken/serializers.py | .py | from django.contrib.auth import authenticate
from django.utils.translation import gettext_lazy as _
from rest_framework import serializers
class AuthTokenSerializer(serializers.Serializer):
username = serializers.CharField(
label=_("Username"),
write_only=True
)
password = serializers.Cha... | 43 | 1,384 |
django-rest-framework | rest_framework/authtoken/views.py | .py | from rest_framework import parsers, renderers
from rest_framework.authtoken.models import Token
from rest_framework.authtoken.serializers import AuthTokenSerializer
from rest_framework.response import Response
from rest_framework.views import APIView
class ObtainAuthToken(APIView):
throttle_classes = ()
permi... | 35 | 1,212 |
django-rest-framework | rest_framework/authtoken/management/commands/drf_create_token.py | .py | from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand, CommandError
from rest_framework.authtoken.models import Token
UserModel = get_user_model()
class Command(BaseCommand):
help = 'Create DRF Token for a given user'
def create_user_token(self, username, reset_... | 46 | 1,370 |
django-rest-framework | rest_framework/schemas/inspectors.py | .py | """
inspectors.py # Per-endpoint view introspection
See schemas.__init__.py for package overview.
"""
import re
from weakref import WeakKeyDictionary
from django.utils.encoding import smart_str
from rest_framework.settings import api_settings
from rest_framework.utils import formatting
class ViewInspector:
"... | 127 | 4,227 |
django-rest-framework | rest_framework/schemas/utils.py | .py | """
utils.py # Shared helper functions
See schemas.__init__.py for package overview.
"""
from django.db import models
from django.utils.translation import gettext_lazy as _
from rest_framework.mixins import RetrieveModelMixin
def is_list_view(path, method, view):
"""
Return True if the given path/met... | 42 | 1,195 |
django-rest-framework | rest_framework/schemas/__init__.py | .py | """
rest_framework.schemas
schemas:
__init__.py
generators.py # Top-down schema generation
inspectors.py # Per-endpoint view introspection
utils.py # Shared helper functions
views.py # Houses `SchemaView`, `APIView` subclass.
We expose a minimal "public" API directly from `schema... | 55 | 1,631 |
django-rest-framework | rest_framework/schemas/views.py | .py | """
views.py # Houses `SchemaView`, `APIView` subclass.
See schemas.__init__.py for package overview.
"""
from rest_framework import exceptions, renderers
from rest_framework.response import Response
from rest_framework.settings import api_settings
from rest_framework.views import APIView
class SchemaView(API... | 42 | 1,561 |
django-rest-framework | rest_framework/schemas/generators.py | .py | """
generators.py # Top-down schema generation
See schemas.__init__.py for package overview.
"""
import re
from importlib import import_module
from django.conf import settings
from django.contrib.admindocs.views import simplify_regex
from django.core.exceptions import PermissionDenied
from django.http import Http40... | 240 | 7,995 |
django-rest-framework | rest_framework/schemas/openapi.py | .py | import re
import warnings
from decimal import Decimal
from operator import attrgetter
from urllib.parse import urljoin
from django.core.validators import (
DecimalValidator, EmailValidator, MaxLengthValidator, MaxValueValidator,
MinLengthValidator, MinValueValidator, RegexValidator, URLValidator
)
from django.... | 722 | 26,897 |
django-rest-framework | rest_framework/utils/breadcrumbs.py | .py | from django.urls import get_script_prefix, resolve
def get_breadcrumbs(url, request=None):
"""
Given a url returns a list of breadcrumbs, which are each a
tuple of (name, url).
"""
from rest_framework.reverse import preserve_builtin_query_params
from rest_framework.views import APIView
de... | 54 | 2,039 |
django-rest-framework | rest_framework/utils/json.py | .py | """
Wrapper for the builtin json module that ensures compliance with the JSON spec.
REST framework should always import this wrapper module in order to maintain
spec-compliant encoding/decoding. Support for non-standard features should be
handled by users at the renderer and parser layer.
"""
import functools
import j... | 38 | 1,027 |
django-rest-framework | rest_framework/utils/timezone.py | .py | from datetime import datetime, timezone, tzinfo
def datetime_exists(dt):
"""Check if a datetime exists. Taken from: https://pytz-deprecation-shim.readthedocs.io/en/latest/migration.html"""
# There are no non-existent times in UTC, and comparisons between
# aware time zones always compare absolute times; i... | 26 | 1,086 |
django-rest-framework | rest_framework/utils/mediatypes.py | .py | """
Handling of media types, as found in HTTP Content-Type and Accept headers.
See https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7
"""
from django.utils.http import parse_header_parameters
def media_type_matches(lhs, rhs):
"""
Returns ``True`` if the media type in the first argument <= the
... | 82 | 2,490 |
django-rest-framework | rest_framework/utils/serializer_helpers.py | .py | import contextlib
from collections.abc import Mapping, MutableMapping
from django.utils.encoding import force_str
from rest_framework.utils import json
class ReturnDict(dict):
"""
Return object from `serializer.data` for the `Serializer` class.
Includes a backlink to the serializer instance for renderer... | 181 | 5,769 |
django-rest-framework | rest_framework/utils/humanize_datetime.py | .py | """
Helper functions that convert strftime formats into more readable representations.
"""
from rest_framework import ISO_8601
def datetime_formats(formats):
format = ', '.join(formats).replace(
ISO_8601,
'YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z]'
)
return humanize_strptime(format)
... | 48 | 1,281 |
django-rest-framework | rest_framework/utils/html.py | .py | """
Helpers for dealing with HTML input.
"""
import re
from django.utils.datastructures import MultiValueDict
def is_html_input(dictionary):
# MultiDict type datastructures are used to represent HTML form input,
# which may have more than one value for each key.
return hasattr(dictionary, 'getlist')
de... | 106 | 2,624 |
django-rest-framework | rest_framework/utils/model_meta.py | .py | """
Helper function for returning the field information that is associated
with a model class. This includes returning all the forward and reverse
relationships and their associated metadata.
Usage: `get_field_info(model)` returns a `FieldInfo` instance.
"""
from collections import namedtuple
FieldInfo = namedtuple('... | 157 | 5,068 |
django-rest-framework | rest_framework/utils/representation.py | .py | """
Helper functions for creating user-friendly representations
of serializer classes and serializer fields.
"""
import re
from django.db import models
from django.utils.encoding import force_str
from django.utils.functional import Promise
def manager_repr(value):
model = value.model
opts = model._meta
n... | 102 | 2,970 |
django-rest-framework | rest_framework/utils/urls.py | .py | from urllib import parse
from django.utils.encoding import force_str
def replace_query_param(url, key, val):
"""
Given a URL and a key/val pair, set or replace an item in the query
parameters of the URL, and return the new URL.
"""
(scheme, netloc, path, query, fragment) = parse.urlsplit(force_st... | 28 | 1,052 |
django-rest-framework | rest_framework/utils/encoders.py | .py | """
Helper classes for parsers.
"""
import contextlib
import datetime
import decimal
import ipaddress
import json # noqa
import uuid
from django.db.models.query import QuerySet
from django.utils import timezone
from django.utils.encoding import force_str
from django.utils.functional import Promise
class JSONEncode... | 82 | 2,799 |
django-rest-framework | rest_framework/utils/field_mapping.py | .py | """
Helper functions for mapping model fields to a dictionary of default
keyword arguments that should be used for their equivalent serializer fields.
"""
import inspect
from django.core import validators
from django.db import models
from django.utils.text import capfirst
from rest_framework.compat import postgres_fi... | 335 | 12,405 |
django-rest-framework | rest_framework/utils/formatting.py | .py | """
Utility functions to return a formatted name and description for a given view.
"""
import re
from django.utils.encoding import force_str
from django.utils.html import escape
from django.utils.safestring import mark_safe
from rest_framework.compat import apply_markdown
def remove_trailing_string(content, trailin... | 94 | 3,015 |
django-rest-framework | rest_framework/templatetags/rest_framework.py | .py | import re
from django import template
from django.template import loader
from django.urls import NoReverseMatch, reverse
from django.utils.encoding import iri_to_uri
from django.utils.html import escape, format_html, smart_urlquote
from django.utils.safestring import mark_safe
from rest_framework.compat import apply_... | 255 | 8,248 |
cognee | cognee_db_workers/_windows_openssl.py | .py | """Windows-only shim that makes ladybug's native extension importable.
Why it exists
-------------
ladybug's Windows wheels stopped vendoring OpenSSL in 0.19.0 — they are
repaired with ``delvewheel repair --exclude libssl-3-x64.dll --exclude
libcrypto-3-x64.dll`` — while ``ladybug/_lbug*.pyd`` still lists
``libssl-3-x... | 152 | 6,234 |
cognee | cognee_db_workers/__init__.py | .py | """Minimal subprocess-side machinery for running native DB clients (kuzu,
lancedb) in a dedicated child process without importing cognee.
This package must stay free of cognee imports so that a spawned worker has
a small memory footprint (just the native DB library + stdlib).
"""
from ._windows_openssl import ensure_... | 15 | 610 |
cognee | cognee_db_workers/lancedb_worker.py | .py | """LanceDB subprocess worker. Imports only ``lancedb`` + ``pyarrow`` + stdlib
+ harness/protocol. Must not import cognee.
"""
from __future__ import annotations
from .harness import (
DEFAULT_DISPATCH,
HandleRegistry,
HandleResult,
Request,
run_worker_loop,
)
from .lancedb_protocol import (
OP... | 245 | 8,121 |
cognee | cognee_db_workers/ladybug_migrate.py | .py | """Ladybug/Kuzu database version detection and migration.
Pure-stdlib module. Safe to import from the subprocess worker (no cognee
dependency). The CLI entry point and legacy import paths live at
``cognee/infrastructure/databases/graph/ladybug/ladybug_migrate.py``.
"""
from __future__ import annotations
import os
im... | 312 | 11,969 |
cognee | cognee_db_workers/kuzu_protocol.py | .py | """Op-codes exchanged between the Kuzu subprocess worker and its main-side
proxy. Pure stdlib.
"""
from __future__ import annotations
OP_OPEN_DATABASE = 1 # kwargs: database_path, buffer_pool_size, max_num_threads, max_db_size
OP_DB_INIT = 2 # handle_id = database
OP_DB_CLOSE = 3 # handle_id = database
OP_OPEN_CO... | 24 | 786 |
cognee | cognee_db_workers/kuzu_worker.py | .py | """Ladybug (formerly Kuzu) subprocess worker.
Imports only ``ladybug`` + stdlib + harness/protocol. Must not import cognee
— that would defeat the whole point of running the DB client in a separate
process. The module name retains the historical ``kuzu_worker`` spelling so
existing imports (and the ``test_worker_impor... | 221 | 7,606 |
cognee | cognee_db_workers/_kuzu_helpers.py | .py | """Tiny stdlib-only helpers shared between the Ladybug worker and the
local-mode adapter. Importable from either side without dragging in
``harness`` or ``cognee``.
Keep this module stdlib-only (apart from a lazy ``import ladybug`` inside
the function body). It's imported by both the cognee adapter (which runs in
the ... | 89 | 3,545 |
cognee | cognee_db_workers/harness.py | .py | """Generic subprocess harness: request/response dataclasses, queue event loop,
and a main-process Session that owns a Process + queues.
Stdlib only. Never import cognee from this module.
"""
from __future__ import annotations
import asyncio
import atexit
import concurrent.futures
import ctypes
import ctypes.util
imp... | 1,503 | 67,711 |
cognee | cognee_db_workers/lancedb_protocol.py | .py | """Op-codes exchanged between the LanceDB subprocess worker and the main-side
proxies. Pure stdlib.
"""
from __future__ import annotations
OP_CONNECT = 100 # kwargs: url, api_key
OP_TABLE_NAMES = 110 # no args; returns list[str]
# args: (name, schema_bytes, exist_ok). ``schema_bytes`` is Arrow IPC
# serialized (``... | 39 | 1,887 |
cognee | distributed/deploy/daytona_sandbox.py | .py | """
Cognee on Daytona — deploy Cognee API inside a Daytona sandbox.
Daytona provides secure, isolated cloud sandboxes with persistent volumes.
This script creates a sandbox, installs Cognee, and starts the API server,
streaming all output in real time.
Prerequisites:
pip install daytona
Set environment varia... | 165 | 5,415 |
cognee | distributed/deploy/modal_app.py | .py | """
Cognee on Modal — 1-click serverless deployment.
Deploys the Cognee FastAPI server as a Modal ASGI app with:
- Persistent volume for file-based databases (SQLite, LanceDB, Ladybug)
- Secret injection for LLM_API_KEY and other credentials
- Auto-scaling with configurable concurrency
Setup:
1. pip install modal... | 59 | 1,580 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.