File djangorestframework-stubs-3.16.1.obscpio of Package python-djangorestframework-stubs
07070100000000000081A4000000000000000000000001687648C500000108000000000000000000000000000000000000002F00000000djangorestframework-stubs-3.16.1/.editorconfig# Check http://editorconfig.org for more information
# This is the main config file for this project:
root = true
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
indent_style = space
trim_trailing_whitespace = true
[*.{py, pyi}]
indent_size = 4
07070100000001000041ED000000000000000000000002687648C500000000000000000000000000000000000000000000002900000000djangorestframework-stubs-3.16.1/.github07070100000002000041ED000000000000000000000002687648C500000000000000000000000000000000000000000000003800000000djangorestframework-stubs-3.16.1/.github/ISSUE_TEMPLATE07070100000003000081A4000000000000000000000001687648C500000236000000000000000000000000000000000000003F00000000djangorestframework-stubs-3.16.1/.github/ISSUE_TEMPLATE/bug.md---
name: Bug
about: Create a report of something is not working
labels: 'bug'
---
# Bug report
<!--
Hi, thanks for submitting a bug. We appreciate that.
But, we will need some information about what's wrong to help you.
-->
## What's wrong
<!--
Describe what is not working.
Please, attach a traceback.
We would also appreciate a failing test case.
That is EXTREMELY helpful!
-->
## How is that should be
<!-- Describe how it should work. -->
## System information
- OS:
- `python` version:
- `django` version:
- `mypy` version:
- `django-stubs` version:
07070100000004000081A4000000000000000000000001687648C500000116000000000000000000000000000000000000003800000000djangorestframework-stubs-3.16.1/.github/dependabot.ymlversion: 2
updates:
- package-ecosystem: pip
directory: "/"
schedule:
interval: daily
time: "02:00"
open-pull-requests-limit: 10
- package-ecosystem: github-actions
directory: "/"
schedule:
interval: daily
time: "02:00"
open-pull-requests-limit: 10
07070100000005000081A4000000000000000000000001687648C50000020E000000000000000000000000000000000000004200000000djangorestframework-stubs-3.16.1/.github/pull_request_template.md# I have made things!
<!--
Hi, thanks for submitting a Pull Request. We appreciate it.
Please, fill in all the required information
to make our review and merging processes easier.
Cheers!
-->
## Related issues
<!--
Mark what issues this Pull Request closes or references.
Format is:
- Closes #issue-number
- Refs #issue-number
Example. Refs #0
Documentation: https://blog.github.com/2013-05-14-closing-issues-via-pull-requests/
-->
<!--
If you have any feedback, just write it here.
It can be whatever you want!
-->
07070100000006000041ED000000000000000000000002687648C500000000000000000000000000000000000000000000003300000000djangorestframework-stubs-3.16.1/.github/workflows07070100000007000081A4000000000000000000000001687648C500000293000000000000000000000000000000000000003F00000000djangorestframework-stubs-3.16.1/.github/workflows/release.ymlname: Release
on:
release:
types: [published]
jobs:
build-and-publish:
runs-on: ubuntu-latest
environment:
name: release
url: https://pypi.org/p/djangorestframework-stubs
permissions:
id-token: write
steps:
- name: Setup python to build package
uses: actions/setup-python@v5
with:
python-version: '3.12'
- name: Install build
run: python -m pip install build
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Build package
run: python -m build
- name: Publish to PyPI
uses: pypa/gh-action-pypi-publish@v1.12.4
07070100000008000081A4000000000000000000000001687648C500000CE0000000000000000000000000000000000000003C00000000djangorestframework-stubs-3.16.1/.github/workflows/test.ymlname: test
on:
push:
branches:
- master
pull_request:
workflow_dispatch:
schedule:
# 15:41 UTC every day
- cron: "41 15 * * *"
permissions:
contents: read
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
mypy-self-check:
timeout-minutes: 10
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
python-version: ['3.10', '3.11', '3.12', '3.13']
steps:
- uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
pip install -U pip "setuptools<79.0.0" wheel
SETUPTOOLS_ENABLE_FEATURES=legacy-editable pip install -r ./requirements.txt
- name: Run mypy on plugin code
run: mypy --strict mypy_drf_plugin
- name: Run mypy on scripts and utils
run: mypy --strict scripts
- name: Run mypy on stubs
run: mypy --cache-dir=/dev/null --no-incremental rest_framework-stubs
test:
timeout-minutes: 10
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
python-version: ['3.10', '3.11', '3.12', '3.13']
steps:
- uses: actions/checkout@v4
- name: Setup system dependencies
run: |
sudo apt-get update
sudo apt-get install binutils libproj-dev gdal-bin
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
pip install -U pip "setuptools<79.0.0" wheel
SETUPTOOLS_ENABLE_FEATURES=legacy-editable pip install -r ./requirements.txt
- name: Run tests
# Suppress errors from other packages due to https://github.com/typeddjango/pytest-mypy-plugins/issues/134
run: pytest --mypy-only-local-stub
stubtest:
timeout-minutes: 10
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ['3.13']
fail-fast: false
steps:
- uses: actions/checkout@v4
- name: Setup system dependencies
run: |
sudo apt-get update
sudo apt-get install binutils libproj-dev gdal-bin
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
pip install -U pip "setuptools<79.0.0" wheel
SETUPTOOLS_ENABLE_FEATURES=legacy-editable pip install -r ./requirements.txt
- name: Run stubtest
run: bash ./scripts/stubtest.sh
build-and-check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-tags: true
- uses: actions/setup-python@v5
with:
python-version: '3.13'
- name: Install dependencies
run: python3 -m pip install --upgrade build twine
- name: Build
run: |
python3 -m build --sdist --wheel .
- name: Check package metadata
run: |
twine check --strict dist/*
07070100000009000081A4000000000000000000000001687648C50000009E000000000000000000000000000000000000002C00000000djangorestframework-stubs-3.16.1/.gitignore*.egg-info
.DS_Store
.python-version
.idea/
.mypy_cache/
.pytest_cache/
.ruff_cache/
.venv/
__pycache__/
drf_source/
out/
pip-wheel-metadata/
stubgen/
build/
0707010000000A000081A4000000000000000000000001687648C500000343000000000000000000000000000000000000003900000000djangorestframework-stubs-3.16.1/.pre-commit-config.yaml# See https://pre-commit.com for more information
# See https://pre-commit.com/hooks.html for more hooks
default_language_version:
python: python3.12
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v5.0.0
hooks:
- id: check-yaml
- id: trailing-whitespace
- id: check-executables-have-shebangs
- id: debug-statements
- id: check-merge-conflict
- id: end-of-file-fixer
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.12.3
hooks:
- id: ruff
args: ["--fix", "--exit-non-zero-on-fix"]
- id: ruff-format
ci:
autofix_commit_msg: '[pre-commit.ci] auto fixes from pre-commit.com hooks'
autofix_prs: true
autoupdate_commit_msg: '[pre-commit.ci] pre-commit autoupdate'
autoupdate_schedule: weekly
submodules: false
0707010000000B000081A4000000000000000000000001687648C500001672000000000000000000000000000000000000003100000000djangorestframework-stubs-3.16.1/CONTRIBUTING.md# Contribution Guide
This project is open source and community driven. As such we encourage code contributions of all kinds. Some areas you can contribute in:
1. Improve the stubs
2. Sync stubs with the latest version of the DRF
3. Improve plugin code and extend its capabilities
4. Write tests
5. Update dependencies
6. Fix and remove things from our `scripts/stubtest/allowlist_todo.txt`
Type stubs in `.pyi` files should follow
[coding conventions from typeshed project](https://github.com/python/typeshed/blob/main/CONTRIBUTING.md#conventions).
## Tutorials
If you want to start working on this project, you will need to get familiar with python typings.
The Mypy documentation offers an excellent resource for this, as well as the python official documentation:
- [Mypy typing documentation](https://mypy.readthedocs.io/en/stable/#overview-type-system-reference)
- [Python official typing documentation](https://docs.python.org/3/library/typing.html)
- [Typing in Python](https://inventwithpython.com/blog/2019/11/24/type-hints-for-busy-python-programmers/) article
Additionally, the following resources might be useful:
- [How to write custom mypy plugins](https://mypy.readthedocs.io/en/stable/extending_mypy.html)
- [Typechecking Django and DRF](https://sobolevn.me/2019/08/typechecking-django-and-drf) guide
- [Testing mypy stubs, plugins, and types](https://sobolevn.me/2019/08/testing-mypy-types) guide
- [Awesome Python Typing](https://github.com/typeddjango/awesome-python-typing) list
## Dev setup
### Repository Setup
As a first step you will need to fork this repository and clone your fork locally.
In order to be able to continously sync your fork with the origin repository's master branch, you will need to set up an upstream master. To do so follow this [official github guide](https://docs.github.com/en/free-pro-team@latest/github/collaborating-with-issues-and-pull-requests/syncing-a-fork).
### Dependency Setup
After your repository is setup you will then need to create and activate a git ignored virtual env, e.g.:
```bash
python3 -m venv .venv
source .venv/bin/activate
```
Then install the dev requirements:
```bash
SETUPTOOLS_ENABLE_FEATURES=legacy-editable pip install -r ./requirements.txt
```
Finally, install the pre-commit hooks:
```bash
pre-commit install
```
### Testing and Linting
We use `mypy`, `pytest`, `ruff`, and `black` for quality control. All tools except pytest are executed using pre-commit when you make a commit.
To ensure there are not formatting or typing issues in the entire repository you can run:
```bash
pre-commit run --all-files
```
NOTE: This command will not only lint but also modify files - so make sure to commit whatever changes you've made before hand.
You can also run pre-commit per file or for a specific path, simply replace "--all-files" with a target (see [this guide](https://codeburst.io/tool-your-django-project-pre-commit-hooks-e1799d84551f) for more info).
To execute the unit tests, simply run:
```bash
pytest
```
### Testing stubs with `stubtest`
Run `bash ./scripts/stubtest.sh` to test that stubs and sources are in-line.
We have two special files to allow errors:
1. `scripts/stubtest/allowlist.txt` where we store things that we really don't care about: hacks, DRF internal utility modules, things that are handled by our plugin, things that are not representable by type system, etc
2. `scripts/stubtest/allowlist_todo.txt` where we store all errors there are right now. Basically, this is a TODO list: we need to work through this list and fix things (or move entries to real `allowlist.txt`). In the end, ideally we can remove this file
You might also want to disable `incremental` mode while working on `stubtest` changes.
This mode leads to several known problems (stubs do not show up or have strange errors).
**Important**: right now we only run `stubtest` on Python 3.12 (because it is the latest released version at the moment), any other versions might generate different outputs. Any work to create per-version allowlists is welcome.
## Submission Guidelines
The workflow for contributions is fairly simple:
1. fork and setup the repository as in the previous step.
2. create a local branch.
3. make whatever changes you want to contribute.
4. ensure your contribution does not introduce linting issues or breaks the tests by linting and testing the code.
5. make a pull request with an adequate description.
## Releasing `djangorestframework-stubs`
1. Open a pull request that updates `setup.py` (anyone can open this PR, not just maintainers):
- Increase `version=` value within `setup(...)`. Version number `major.minor.patch` is formed as follows:
`major.minor` version must match newest supported `djangorestframework` release.
`patch` is sequentially increasing for each stubs release. Reset to `0` if `major.minor` was updated.
- Update `django-stubs>=` dependency to point to latest `django-stubs` release.
- Use pull request title "Version x.y.z release" by convention.
2. Ensure the CI succeeds. A maintainer must merge this PR. If it's just a verison bump, no need
to wait for a second maintainer's approval.
3. Maintainers need to [сreate a new GitHub release](https://github.com/typeddjango/djangorestframework-stubs/releases/new):
- Under "Choose a tag" enter the new version number. Do NOT use `v` prefix.
- Click "Generate release notes".
- Delete all release notes lines containing `by @pre-commit-ci` or `by @dependabot`, as these
are irrelevant for our users.
4. Once you feel brave enough, click "Publish release".
5. Check that the [release workflow](https://github.com/typeddjango/djangorestframework-stubs/actions/workflows/release.yml) succeeds.
0707010000000C000081A4000000000000000000000001687648C500000433000000000000000000000000000000000000002D00000000djangorestframework-stubs-3.16.1/LICENSE.txtCopyright (c) Maxim Kurnikov.
All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
0707010000000D000081A4000000000000000000000001687648C50000091B000000000000000000000000000000000000002B00000000djangorestframework-stubs-3.16.1/README.md<img src="https://mypy-lang.org/static/mypy_light.svg" alt="mypy logo" width="300px"/>
# pep484 stubs for Django REST framework
[](https://github.com/typeddjango/djangorestframework-stubs/actions/workflows/test.yml)
[](https://mypy-lang.org/)
[](https://gitter.im/mypy-django/Lobby)
[](https://stackoverflow.com/questions/tagged/django-stubs?tab=Active)
Mypy stubs for [Django REST Framework](https://pypi.org/project/djangorestframework/).
Supports Python 3.10 and up.
## Installation
```bash
pip install djangorestframework-stubs[compatible-mypy]
```
To make mypy aware of the plugin, you need to add
```ini
[mypy]
plugins =
mypy_drf_plugin.main
```
in your `mypy.ini` file.
## FAQ
### Model instance is inferred as `Any` instead of my `Model` class
When subclassing `ModelSerializer`, add a [type argument](https://peps.python.org/pep-0484/#generics) to type-hint the related model class, for example:
```python
class MyModelSerializer(serializers.ModelSerializer[MyModel]):
class Meta:
model = MyModel
fields = ("id", "example")
```
Which means that methods where the model is being passed around will know the actual type of the model instead of being `Any`. The `instance` attribute on the above serializer will be `Union[MyModel, typing.Sequence[MyModel], None]`.
## To get help
We have Gitter here: <https://gitter.im/mypy-django/Lobby>
If you think you have more generic typing issue, please refer to <https://github.com/python/mypy> and their Gitter.
## Contributing
This project is open source and community driven. As such we encourage contributions big and small. You can contribute by doing any of the following:
1. Contribute code (e.g. improve stubs, add plugin capabilities, write tests etc) - to do so please follow the [contribution guide](./CONTRIBUTING.md).
2. Assist in code reviews and discussions in issues.
3. Identify bugs and issues and report these
You can always also reach out in gitter to discuss your contributions!
0707010000000E000081A4000000000000000000000001687648C500000267000000000000000000000000000000000000002A00000000djangorestframework-stubs-3.16.1/mypy.ini[mypy]
allow_redefinition = true
check_untyped_defs = true
incremental = true
strict_optional = true
show_traceback = true
warn_unused_ignores = true
warn_redundant_casts = true
warn_unused_configs = true
warn_unreachable = true
disallow_untyped_defs = true
disallow_incomplete_defs = true
disable_error_code = empty-body
# TODO: update our test error messages to match new mypy output
show_error_codes = false
force_uppercase_builtins = true
force_union_syntax = true
plugins =
mypy_django_plugin.main,
mypy_drf_plugin.main
[mypy.plugins.django-stubs]
django_settings_module = scripts.drf_tests_settings
0707010000000F000041ED000000000000000000000002687648C500000000000000000000000000000000000000000000003100000000djangorestframework-stubs-3.16.1/mypy_drf_plugin07070100000010000081A4000000000000000000000001687648C500000000000000000000000000000000000000000000003D00000000djangorestframework-stubs-3.16.1/mypy_drf_plugin/__init__.py07070100000011000041ED000000000000000000000002687648C500000000000000000000000000000000000000000000003500000000djangorestframework-stubs-3.16.1/mypy_drf_plugin/lib07070100000012000081A4000000000000000000000001687648C500000000000000000000000000000000000000000000004100000000djangorestframework-stubs-3.16.1/mypy_drf_plugin/lib/__init__.py07070100000013000081A4000000000000000000000001687648C500000A9A000000000000000000000000000000000000004200000000djangorestframework-stubs-3.16.1/mypy_drf_plugin/lib/fullnames.pyFIELD_FULLNAME = "rest_framework.fields.Field"
BASE_SERIALIZER_FULLNAME = "rest_framework.serializers.BaseSerializer"
SERIALIZER_FULLNAME = "rest_framework.serializers.Serializer"
LIST_SERIALIZER_FULLNAME = "rest_framework.serializers.ListSerializer"
MODEL_SERIALIZER_FULLNAME = "rest_framework.serializers.ModelSerializer"
SERIALIZER_FIELD_MAPPING = {
"django.db.models.fields.AutoField": "rest_framework.serializers.IntegerField",
"django.db.models.fields.BigIntegerField": "rest_framework.serializers.IntegerField",
"django.db.models.fields.BooleanField": "rest_framework.serializers.BooleanField",
"django.db.models.fields.CharField": "rest_framework.serializers.CharField",
"django.db.models.fields.CommaSeparatedIntegerField": "rest_framework.serializers.CharField",
"django.db.models.fields.DateField": "rest_framework.serializers.DateField",
"django.db.models.fields.DateTimeField": "rest_framework.serializers.DateTimeField",
"django.db.models.fields.DecimalField": "rest_framework.serializers.DecimalField",
"django.db.models.fields.DurationField": "rest_framework.serializers.DurationField",
"django.db.models.fields.EmailField": "rest_framework.serializers.EmailField",
"django.db.models.fields.Field": "rest_framework.serializers.ModelField",
"django.db.models.fields.FileField": "rest_framework.serializers.FileField",
"django.db.models.fields.FilePathField": "rest_framework.serializers.FilePathField",
"django.db.models.fields.FloatField": "rest_framework.serializers.FloatField",
"django.db.models.fields.GenericIPAddressField": "rest_framework.serializers.IPAddressField",
"django.db.models.fields.ImageField": "rest_framework.serializers.ImageField",
"django.db.models.fields.IntegerField": "rest_framework.serializers.IntegerField",
"django.db.models.fields.NullBooleanField": "rest_framework.serializers.BooleanField",
"django.db.models.fields.PositiveIntegerField": "rest_framework.serializers.IntegerField",
"django.db.models.fields.PositiveSmallIntegerField": "rest_framework.serializers.IntegerField",
"django.db.models.fields.SlugField": "rest_framework.serializers.SlugField",
"django.db.models.fields.SmallIntegerField": "rest_framework.serializers.IntegerField",
"django.db.models.fields.TextField": "rest_framework.serializers.CharField",
"django.db.models.fields.TimeField": "rest_framework.serializers.TimeField",
"django.db.models.fields.URLField": "rest_framework.serializers.URLField",
"django.db.models.fields.UUIDField": "rest_framework.serializers.UUIDField",
"django.db.models.fields.JSONField": "rest_framework.serializers.JSONField",
}
ID_TYPE = "builtins.object"
07070100000014000081A4000000000000000000000001687648C5000000A1000000000000000000000000000000000000004000000000djangorestframework-stubs-3.16.1/mypy_drf_plugin/lib/helpers.pyfrom typing import Any
from mypy.nodes import TypeInfo
def get_drf_metadata(info: TypeInfo) -> dict[str, Any]:
return info.metadata.setdefault("drf", {})
07070100000015000081A4000000000000000000000001687648C5000005B8000000000000000000000000000000000000003900000000djangorestframework-stubs-3.16.1/mypy_drf_plugin/main.pyfrom collections.abc import Callable
from mypy.nodes import TypeInfo
from mypy.plugin import ClassDefContext, Plugin
from mypy_drf_plugin.lib import fullnames, helpers
from mypy_drf_plugin.transformers import serializers
def transform_serializer_class(ctx: ClassDefContext) -> None:
sym = ctx.api.lookup_fully_qualified_or_none(fullnames.BASE_SERIALIZER_FULLNAME)
if sym is not None and isinstance(sym.node, TypeInfo):
helpers.get_drf_metadata(sym.node)["serializer_bases"][ctx.cls.fullname] = 1
serializers.make_meta_nested_class_inherit_from_any(ctx)
class NewSemanalDRFPlugin(Plugin):
def _get_currently_defined_serializers(self) -> dict[str, int]:
base_serializer_sym = self.lookup_fully_qualified(fullnames.BASE_SERIALIZER_FULLNAME)
if base_serializer_sym is not None and isinstance(base_serializer_sym.node, TypeInfo):
serializer_bases: dict[str, int] = base_serializer_sym.node.metadata.setdefault("drf", {}).setdefault(
"serializer_bases", {fullnames.BASE_SERIALIZER_FULLNAME: 1}
)
return serializer_bases
else:
return {}
def get_base_class_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None:
if fullname in self._get_currently_defined_serializers():
return transform_serializer_class
return None
def plugin(version: str) -> type[NewSemanalDRFPlugin]:
return NewSemanalDRFPlugin
07070100000016000041ED000000000000000000000002687648C500000000000000000000000000000000000000000000003E00000000djangorestframework-stubs-3.16.1/mypy_drf_plugin/transformers07070100000017000081A4000000000000000000000001687648C500000000000000000000000000000000000000000000004A00000000djangorestframework-stubs-3.16.1/mypy_drf_plugin/transformers/__init__.py07070100000018000081A4000000000000000000000001687648C500000163000000000000000000000000000000000000004D00000000djangorestframework-stubs-3.16.1/mypy_drf_plugin/transformers/serializers.pyfrom mypy.plugin import ClassDefContext
from mypy_django_plugin.lib import helpers as mypy_django_helpers
def make_meta_nested_class_inherit_from_any(ctx: ClassDefContext) -> None:
meta_node = mypy_django_helpers.get_nested_meta_node_for_current_class(ctx.cls.info)
if meta_node is None:
return None
meta_node.fallback_to_any = True
07070100000019000081A4000000000000000000000001687648C5000004AD000000000000000000000000000000000000003000000000djangorestframework-stubs-3.16.1/pyproject.toml[tool.ruff]
line-length = 120
target-version = "py310"
# See Rules in Ruff documentation: https://docs.astral.sh/ruff/rules/
[tool.ruff.lint]
select = [
"B", # bugbear
"E", # pycodestyle
"F", # pyflakes
"INP", # flake8-tidy-imports
"W", # pycodestyle
"I", # isort
"UP", # pyupgrade
"TID251", # Disallowed imports (flake8-tidy-imports.banned-api)
"PYI", # flake8-pyi
"RUF100", # Equivalent to flake8-noqa NQA103
"PGH004", # Equivalent to flake8-noqa NQA104
"PGH003", # Disallowed blanket `type: ignore` annotations.
]
ignore = ["PYI021", "PYI024", "PYI041", "PYI043"]
[tool.ruff.lint.per-file-ignores]
"*.pyi" = [
"B",
"E501",
"E741",
"E743",
"F403", # Use wildcard import
"F405",
"F822",
"F821",
"PGH003", # TODO fix these errors
]
"rest_framework-stubs/compat.pyi" = ["PYI042"]
[tool.ruff.lint.flake8-tidy-imports.banned-api]
"_typeshed.Self".msg = "Use typing_extensions.Self (PEP 673) instead."
[tool.ruff.lint.isort]
split-on-trailing-comma = false
extra-standard-library = ["_typeshed"]
[build-system]
requires = ["setuptools<79.0.0", "wheel"]
0707010000001A000081A4000000000000000000000001687648C5000000BF000000000000000000000000000000000000002C00000000djangorestframework-stubs-3.16.1/pytest.ini[pytest]
testpaths = ./tests
addopts =
--tb=native
-s
-v
--cache-clear
--mypy-ini-file=mypy.ini
--mypy-extension-hook=scripts.tests_extension_hook.django_plugin_hook
0707010000001B000081A4000000000000000000000001687648C5000001BE000000000000000000000000000000000000003200000000djangorestframework-stubs-3.16.1/requirements.txtwheel
pre-commit==4.2.0
pytest==8.4.1
pytest-mypy-plugins==3.2.0
djangorestframework==3.16.0
types-pytz==2025.2.0.20250516
types-requests==2.32.4.20250611
types-urllib3==1.26.25.14
types-Pygments==2.19.0.20250516
types-pyyaml==6.0.12.20250516
django-stubs[compatible-mypy] @ git+https://github.com/typeddjango/django-stubs
django-stubs-ext @ git+https://github.com/typeddjango/django-stubs#subdirectory=ext
-e .[compatible-mypy,coreapi,markdown]
0707010000001C000041ED000000000000000000000002687648C500000000000000000000000000000000000000000000003600000000djangorestframework-stubs-3.16.1/rest_framework-stubs0707010000001D000081A4000000000000000000000001687648C5000000E0000000000000000000000000000000000000004300000000djangorestframework-stubs-3.16.1/rest_framework-stubs/__init__.pyi__title__: str
__version__: str
__author__: str
__license__: str
__copyright__: str
VERSION: str
HTTP_HEADER_ENCODING: str
ISO_8601: str
default_app_config: str
class RemovedInDRF317Warning(PendingDeprecationWarning): ...
0707010000001E000081A4000000000000000000000001687648C50000004D000000000000000000000000000000000000003F00000000djangorestframework-stubs-3.16.1/rest_framework-stubs/apps.pyifrom django.apps import AppConfig
class RestFrameworkConfig(AppConfig): ...
0707010000001F000081A4000000000000000000000001687648C50000045B000000000000000000000000000000000000004900000000djangorestframework-stubs-3.16.1/rest_framework-stubs/authentication.pyifrom typing import Any
from django.contrib.auth import authenticate as authenticate
from django.db.models import Model
from django.middleware.csrf import CsrfViewMiddleware
from rest_framework.request import Request
def get_authorization_header(request: Request) -> bytes: ...
class CSRFCheck(CsrfViewMiddleware): ...
class BaseAuthentication:
def authenticate(self, request: Request) -> tuple[Any, Any] | None: ... # noqa: F811
def authenticate_header(self, request: Request) -> str | None: ...
class BasicAuthentication(BaseAuthentication):
www_authenticate_realm: str
def authenticate_credentials(
self, userid: str, password: str, request: Request | None = ...
) -> tuple[Any, None]: ...
class SessionAuthentication(BaseAuthentication):
def enforce_csrf(self, request: Request) -> None: ...
class TokenAuthentication(BaseAuthentication):
keyword: str
model: type[Model] | None
def get_model(self) -> type[Model]: ...
def authenticate_credentials(self, key: str) -> tuple[Any, Any]: ...
class RemoteUserAuthentication(BaseAuthentication):
header: str
07070100000020000041ED000000000000000000000002687648C500000000000000000000000000000000000000000000004000000000djangorestframework-stubs-3.16.1/rest_framework-stubs/authtoken07070100000021000081A4000000000000000000000001687648C500000018000000000000000000000000000000000000004D00000000djangorestframework-stubs-3.16.1/rest_framework-stubs/authtoken/__init__.pyidefault_app_config: str
07070100000022000081A4000000000000000000000001687648C5000000A8000000000000000000000000000000000000004A00000000djangorestframework-stubs-3.16.1/rest_framework-stubs/authtoken/admin.pyifrom django.contrib import admin
from django.contrib.admin.views.main import ChangeList
class TokenChangeList(ChangeList): ...
class TokenAdmin(admin.ModelAdmin): ...
07070100000023000081A4000000000000000000000001687648C500000049000000000000000000000000000000000000004900000000djangorestframework-stubs-3.16.1/rest_framework-stubs/authtoken/apps.pyifrom django.apps import AppConfig
class AuthTokenConfig(AppConfig): ...
07070100000024000041ED000000000000000000000002687648C500000000000000000000000000000000000000000000004B00000000djangorestframework-stubs-3.16.1/rest_framework-stubs/authtoken/management07070100000025000081A4000000000000000000000001687648C500000000000000000000000000000000000000000000005800000000djangorestframework-stubs-3.16.1/rest_framework-stubs/authtoken/management/__init__.pyi07070100000026000041ED000000000000000000000002687648C500000000000000000000000000000000000000000000005400000000djangorestframework-stubs-3.16.1/rest_framework-stubs/authtoken/management/commands07070100000027000081A4000000000000000000000001687648C500000000000000000000000000000000000000000000006100000000djangorestframework-stubs-3.16.1/rest_framework-stubs/authtoken/management/commands/__init__.pyi07070100000028000081A4000000000000000000000001687648C5000001C5000000000000000000000000000000000000006900000000djangorestframework-stubs-3.16.1/rest_framework-stubs/authtoken/management/commands/drf_create_token.pyifrom typing import Any
from django.contrib.auth.base_user import AbstractBaseUser
from django.core.management.base import BaseCommand
from rest_framework.authtoken.models import Token
UserModel: AbstractBaseUser
class Command(BaseCommand):
help: str
def create_user_token(self, username: str, reset_token: bool) -> Token: ...
def add_arguments(self, parser: Any) -> None: ...
def handle(self, *args: Any, **options: Any) -> None: ...
07070100000029000081A4000000000000000000000001687648C5000001F5000000000000000000000000000000000000004B00000000djangorestframework-stubs-3.16.1/rest_framework-stubs/authtoken/models.pyifrom typing import Any, ClassVar
from django.db import models
from django.db.models.manager import Manager
from typing_extensions import Self
class Token(models.Model):
key: models.CharField
user: models.OneToOneField
created: models.DateTimeField
objects: ClassVar[Manager[Self]]
@classmethod
def generate_key(cls) -> str: ...
class TokenProxy(Token):
# This is how drf defines this:
@property # type: ignore
def pk(self) -> Any: ... # type: ignore[override]
0707010000002A000081A4000000000000000000000001687648C5000000C4000000000000000000000000000000000000005000000000djangorestframework-stubs-3.16.1/rest_framework-stubs/authtoken/serializers.pyifrom rest_framework import serializers
class AuthTokenSerializer(serializers.Serializer):
username: serializers.CharField
password: serializers.CharField
token: serializers.CharField
0707010000002B000081A4000000000000000000000001687648C500000228000000000000000000000000000000000000004A00000000djangorestframework-stubs-3.16.1/rest_framework-stubs/authtoken/views.pyifrom typing import Any
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.serializers import Serializer
from rest_framework.views import APIView, AsView, GenericView
class ObtainAuthToken(APIView):
serializer_class: type[Serializer]
def post(self, request: Request, *args: Any, **kwargs: Any) -> Response: ...
def get_serializer_context(self) -> dict[str, Any]: ...
def get_serializer(self, *args: Any, **kwargs: Any) -> Serializer: ...
obtain_auth_token: AsView[GenericView]
0707010000002C000081A4000000000000000000000001687648C500000067000000000000000000000000000000000000004100000000djangorestframework-stubs-3.16.1/rest_framework-stubs/checks.pyifrom typing import Any
def pagination_system_check(app_configs: Any, **kwargs: Any) -> list[Any]: ...
0707010000002D000081A4000000000000000000000001687648C500000906000000000000000000000000000000000000004100000000djangorestframework-stubs-3.16.1/rest_framework-stubs/compat.pyifrom typing import Any, TypeAlias
from django.db.models import Q, QuerySet
try:
from django.contrib.postgres import fields as postgres_fields
except ImportError:
postgres_fields: TypeAlias = None # type: ignore[no-redef]
try:
import coreapi # type: ignore[import-untyped]
except ImportError:
coreapi: TypeAlias = None # type: ignore[no-redef]
try:
import uritemplate
except ImportError:
uritemplate: TypeAlias = None # type: ignore[no-redef]
try:
import coreschema # type: ignore[import-untyped]
except ImportError:
coreschema: TypeAlias = None # type: ignore[no-redef]
try:
import yaml
except ImportError:
yaml: TypeAlias = None # type: ignore[no-redef]
try:
import inflection # type: ignore[import-not-found,unused-ignore]
except ImportError:
inflection: TypeAlias = None # type: ignore[no-redef]
try:
import requests
except ImportError:
requests: TypeAlias = None # type: ignore[no-redef]
try:
import pygments
except ImportError:
pygments: TypeAlias = None # type: ignore[no-redef]
try:
import markdown
from markdown.preprocessors import Preprocessor
def apply_markdown(text: str) -> str: ...
class CodeBlockPreprocessor(Preprocessor):
pattern: Any
formatter: Any
def run(self, lines: list[str]) -> list[str]: ...
except ImportError:
apply_markdown: TypeAlias = None # type: ignore[no-redef]
markdown: TypeAlias = None # type: ignore[no-redef]
def pygments_css(style: Any) -> str | None: ...
def pygments_highlight(text: str, lang: str, style: Any) -> Any: ...
def md_filter_add_syntax_highlight(md: Any) -> bool: ...
def unicode_http_header(value: str | bytes) -> str: ...
def get_referenced_base_fields_from_q(q: Q) -> set[str]: ...
SHORT_SEPARATORS: tuple[str, str]
LONG_SEPARATORS: tuple[str, str]
INDENT_SEPARATORS: tuple[str, str]
__all__ = [
"coreapi",
"coreschema",
"requests",
"postgres_fields",
"QuerySet",
"uritemplate",
"yaml",
"inflection",
"pygments",
"markdown",
"apply_markdown",
"Preprocessor",
"CodeBlockPreprocessor",
"pygments_css",
"pygments_highlight",
"md_filter_add_syntax_highlight",
"unicode_http_header",
"SHORT_SEPARATORS",
"LONG_SEPARATORS",
"INDENT_SEPARATORS",
]
0707010000002E000081A4000000000000000000000001687648C500000C5A000000000000000000000000000000000000004500000000djangorestframework-stubs-3.16.1/rest_framework-stubs/decorators.pyiimport sys
from collections.abc import Callable, Mapping, Sequence
from typing import Any, Concatenate, Literal, Protocol, TypeAlias, TypeVar
from django.http import HttpRequest
from django.http.response import HttpResponseBase
from rest_framework.authentication import BaseAuthentication
from rest_framework.parsers import BaseParser
from rest_framework.permissions import _PermissionClass
from rest_framework.renderers import BaseRenderer
from rest_framework.request import Request
from rest_framework.schemas.inspectors import ViewInspector
from rest_framework.throttling import BaseThrottle
from rest_framework.views import APIView, AsView # noqa: F401
from typing_extensions import ParamSpec
_View = TypeVar("_View", bound=Callable[..., HttpResponseBase])
_P = ParamSpec("_P")
_RESP = TypeVar("_RESP", bound=HttpResponseBase)
_MixedCaseHttpMethod: TypeAlias = Literal[
"GET",
"POST",
"DELETE",
"PUT",
"PATCH",
"TRACE",
"HEAD",
"OPTIONS",
"get",
"post",
"delete",
"put",
"patch",
"trace",
"head",
"options",
]
if sys.version_info >= (3, 11):
from http import HTTPMethod
_HttpMethod: TypeAlias = _MixedCaseHttpMethod | HTTPMethod
else:
_HttpMethod: TypeAlias = _MixedCaseHttpMethod
class MethodMapper(dict):
def __init__(self, action: _View, methods: Sequence[str]) -> None: ...
def _map(self, method: str, func: _View) -> _View: ...
def get(self, func: _View) -> _View: ... # type: ignore
def post(self, func: _View) -> _View: ...
def put(self, func: _View) -> _View: ...
def patch(self, func: _View) -> _View: ...
def delete(self, func: _View) -> _View: ...
def head(self, func: _View) -> _View: ...
def options(self, func: _View) -> _View: ...
def trace(self, func: _View) -> _View: ...
class ViewSetAction(Protocol[_View]):
detail: bool
url_path: str
url_name: str
kwargs: Mapping[str, Any]
mapping: MethodMapper
__call__: _View
__name__: str
def api_view(
http_method_names: Sequence[str] | None = ...,
) -> Callable[[Callable[Concatenate[Request, _P], _RESP]], AsView[Callable[Concatenate[HttpRequest, _P], _RESP]]]: ...
def renderer_classes(renderer_classes: Sequence[BaseRenderer | type[BaseRenderer]]) -> Callable[[_View], _View]: ...
def parser_classes(parser_classes: Sequence[BaseParser | type[BaseParser]]) -> Callable[[_View], _View]: ...
def authentication_classes(
authentication_classes: Sequence[BaseAuthentication | type[BaseAuthentication]],
) -> Callable[[_View], _View]: ...
def throttle_classes(throttle_classes: Sequence[BaseThrottle | type[BaseThrottle]]) -> Callable[[_View], _View]: ...
def permission_classes(permission_classes: Sequence[_PermissionClass]) -> Callable[[_View], _View]: ...
def schema(view_inspector: ViewInspector | type[ViewInspector] | None) -> Callable[[_View], _View]: ...
def action(
methods: Sequence[_HttpMethod] | None = ...,
detail: bool = ...,
url_path: str | None = ...,
url_name: str | None = ...,
suffix: str | None = ...,
name: str | None = ...,
**kwargs: Any,
) -> Callable[[_View], ViewSetAction[_View]]: ...
0707010000002F000081A4000000000000000000000001687648C500000618000000000000000000000000000000000000004800000000djangorestframework-stubs-3.16.1/rest_framework-stubs/documentation.pyifrom collections.abc import Callable, Sequence
from typing import Any
from rest_framework.renderers import BaseRenderer
from rest_framework.schemas import SchemaGenerator
from rest_framework.urlpatterns import _AnyURL
def get_docs_view(
title: str | None = ...,
url: str | None = ...,
description: str | None = ...,
urlconf: str | None = ...,
renderer_classes: Sequence[type[BaseRenderer]] | None = ...,
public: bool = ...,
patterns: Sequence[_AnyURL] | None = ...,
generator_class: type[SchemaGenerator] = ...,
authentication_classes: Sequence[str] = ...,
permission_classes: Sequence[str] = ...,
) -> Callable[..., Any]: ...
def get_schemajs_view(
title: str | None = ...,
url: str | None = ...,
description: str | None = ...,
urlconf: str | None = ...,
renderer_classes: Sequence[type[BaseRenderer]] | None = ...,
public: bool = ...,
patterns: Sequence[_AnyURL] | None = ...,
generator_class: type[SchemaGenerator] = ...,
authentication_classes: Sequence[str] = ...,
permission_classes: Sequence[str] = ...,
) -> Callable[..., Any]: ...
def include_docs_urls(
title: str | None = ...,
url: str | None = ...,
description: str | None = ...,
urlconf: str | None = ...,
renderer_classes: Sequence[type[BaseRenderer]] | None = ...,
public: bool = ...,
patterns: Sequence[_AnyURL] | None = ...,
generator_class: type[SchemaGenerator] = ...,
authentication_classes: Sequence[str] = ...,
permission_classes: Sequence[str] = ...,
) -> Any: ...
07070100000030000081A4000000000000000000000001687648C500000C0F000000000000000000000000000000000000004500000000djangorestframework-stubs-3.16.1/rest_framework-stubs/exceptions.pyifrom collections.abc import Mapping, Sequence
from typing import Any, TypeAlias
from django.http import HttpRequest, JsonResponse
from django_stubs_ext import StrOrPromise
from rest_framework.renderers import BaseRenderer
from rest_framework.request import Request
from typing_extensions import Self, TypedDict
class ErrorDetail(str):
code: str | None
def __new__(cls, string: str, code: str | None = ...) -> Self: ...
_Detail: TypeAlias = ErrorDetail | list[_Detail] | dict[str, _Detail]
# NB! _APIExceptionInput doesn't technically handle Sequence/Mapping, but only list/tuple/dict.
# But since list/tuple are non-covariant types, we run into issues with union type compatibility for input params.
# So use the more relaxed Sequence/Mapping for now.
_APIExceptionInput: TypeAlias = (
_Detail | StrOrPromise | Sequence[_APIExceptionInput] | Mapping[str, _APIExceptionInput] | None
)
_ErrorCodes: TypeAlias = str | None | list[_ErrorCodes] | dict[str, _ErrorCodes]
class _FullDetailDict(TypedDict):
message: ErrorDetail
code: str | None
_ErrorFullDetails: TypeAlias = _FullDetailDict | list[_ErrorFullDetails] | dict[str, _ErrorFullDetails]
def _get_error_details(data: _APIExceptionInput, default_code: str | None = ...) -> _Detail: ...
def _get_codes(detail: _Detail) -> _ErrorCodes: ...
def _get_full_details(detail: _Detail) -> _ErrorFullDetails: ...
class APIException(Exception):
status_code: int
default_detail: _APIExceptionInput
default_code: str
detail: _Detail
def __init__(self, detail: _APIExceptionInput = ..., code: str | None = ...) -> None: ...
def get_codes(self) -> _ErrorCodes: ...
def get_full_details(self) -> _ErrorFullDetails: ...
class ValidationError(APIException):
# ValidationError wraps `detail` in a list if it's not already a list/dict.
detail: list[_Detail] | dict[str, _Detail]
class ParseError(APIException): ...
class AuthenticationFailed(APIException): ...
class NotAuthenticated(APIException): ...
class PermissionDenied(APIException): ...
class NotFound(APIException): ...
class MethodNotAllowed(APIException):
def __init__(self, method: str, detail: _APIExceptionInput = ..., code: str | None = ...) -> None: ...
class NotAcceptable(APIException):
available_renderers: Sequence[BaseRenderer] | None
def __init__(
self,
detail: _APIExceptionInput = ...,
code: str | None = ...,
available_renderers: Sequence[BaseRenderer] | None = ...,
) -> None: ...
class UnsupportedMediaType(APIException):
def __init__(self, media_type: str, detail: _APIExceptionInput = ..., code: str | None = ...) -> None: ...
class Throttled(APIException):
extra_detail_singular: str
extra_detail_plural: str
def __init__(self, wait: float | None = ..., detail: _APIExceptionInput = ..., code: str | None = ...) -> None: ...
def server_error(request: HttpRequest | Request, *args: Any, **kwargs: Any) -> JsonResponse: ...
def bad_request(request: HttpRequest | Request, exception: Exception, *args: Any, **kwargs: Any) -> JsonResponse: ...
07070100000031000081A4000000000000000000000001687648C5000061B3000000000000000000000000000000000000004100000000djangorestframework-stubs-3.16.1/rest_framework-stubs/fields.pyiimport datetime
import uuid
from _typeshed import Incomplete
from collections.abc import Callable, Generator, Iterable, Mapping, Sequence
from decimal import Decimal
from enum import Enum
from json import JSONDecoder, JSONEncoder
from re import Pattern
from typing import Any, ClassVar, Final, Generic, NoReturn, Protocol, TypeAlias, TypeVar
from django.core.files.base import File
from django.db import models
from django.forms import ImageField as DjangoImageField # noqa: F401
from django_stubs_ext import StrOrPromise
from rest_framework.serializers import BaseSerializer
from rest_framework.validators import Validator
from typing_extensions import Self
class _Empty(Enum):
sentinel = 0
empty: Final = _Empty.sentinel
class BuiltinSignatureError(Exception): ...
class CreateOnlyDefault:
requires_context: bool
default: Any
def __init__(self, default: Any) -> None: ...
def __call__(self, serializer_field: Field) -> Incomplete: ...
class CurrentUserDefault:
requires_context: bool
def __call__(self, serializer_field: Field) -> Incomplete: ...
class SkipField(Exception): ...
class Option(Protocol):
start_option_group: bool
end_option_group: bool
label: StrOrPromise
value: str
display_text: StrOrPromise
def is_simple_callable(obj: Callable) -> bool: ...
def get_attribute(instance: Any, attrs: list[str] | None) -> Any: ...
def to_choices_dict(choices: Iterable[Any]) -> dict: ...
def flatten_choices_dict(choices: dict[Any, Any]) -> dict: ...
def iter_options(
grouped_choices: dict, cutoff: int | None = ..., cutoff_text: StrOrPromise | None = ...
) -> Generator[Option, None, None]: ...
def get_error_detail(exc_info: Any) -> Any: ...
REGEX_TYPE: Pattern
NOT_READ_ONLY_WRITE_ONLY: str
NOT_READ_ONLY_REQUIRED: str
NOT_REQUIRED_DEFAULT: str
USE_READONLYFIELD: str
MISSING_ERROR_MESSAGE: str
_IN = TypeVar("_IN") # Instance Type
_VT = TypeVar("_VT") # Value Type
_DT = TypeVar("_DT") # Data Type
_RP = TypeVar("_RP") # Representation Type
class SupportsToPython(Protocol):
def to_python(self, value: Any) -> Any: ...
_DefaultInitial: TypeAlias = _VT | Callable[[], _VT] | None | _Empty
class Field(Generic[_VT, _DT, _RP, _IN]):
allow_null: bool
default: _VT | None
default_empty_html: Any
default_error_messages: ClassVar[dict[str, StrOrPromise]]
default_validators: Sequence[Validator[_VT]]
error_messages: dict[str, StrOrPromise]
field_name: str | None
help_text: StrOrPromise | None
initial: _VT | Callable[[], _VT] | None
label: StrOrPromise | None
parent: BaseSerializer
read_only: bool
required: bool
source: Callable | str | None
source_attrs: list[str]
style: dict[str, Any]
write_only: bool
def __init__(
self,
*,
read_only: bool = ...,
write_only: bool = ...,
required: bool | None = None,
default: _DefaultInitial[_VT] = ...,
initial: _DefaultInitial[_VT] = ...,
source: str | None = None,
label: StrOrPromise | None = None,
help_text: StrOrPromise | None = None,
style: dict[str, Any] | None = None,
error_messages: dict[str, StrOrPromise] | None = None,
validators: Sequence[Validator[_VT]] | None = ...,
allow_null: bool = ...,
) -> None: ...
def __class_getitem__(cls, *args: Any, **kwargs: Any) -> type[Self]: ...
def bind(self, field_name: str, parent: BaseSerializer) -> None: ...
@property
def validators(self) -> list[Validator[_VT]]: ...
@validators.setter
def validators(self, validators: list[Validator[_VT]]) -> None: ...
def get_validators(self) -> list[Validator[_VT]]: ...
def get_initial(self) -> _VT | None: ...
def get_value(self, dictionary: Mapping[Any, Any]) -> Any: ...
def get_attribute(self, instance: _IN) -> _RP | None: ...
def get_default(self) -> _VT | None: ...
def validate_empty_values(self, data: Any) -> tuple[bool, Any]: ...
def run_validation(self, data: Any = ...) -> Any: ...
def run_validators(self, value: Any) -> None: ...
def to_internal_value(self, data: _DT) -> _VT: ...
def to_representation(self, value: _VT) -> _RP: ...
def fail(self, key: str, **kwargs: Any) -> NoReturn: ...
@property
def root(self) -> BaseSerializer: ...
@property
def context(self) -> dict[str, Any]: ...
def __new__(cls, *args: Any, **kwargs: Any) -> Self: ...
def __deepcopy__(self, memo: Mapping[Any, Any]) -> Field: ...
class BooleanField(
Field[
bool,
str | bool | int,
bool,
Any,
]
):
TRUE_VALUES: set[str | bool | int]
FALSE_VALUES: set[str | bool | int | float]
NULL_VALUES: set[str | None]
class NullBooleanField(
Field[
bool | None,
str | bool | int | None,
bool,
Any,
]
):
TRUE_VALUES: set[str | bool | int]
FALSE_VALUES: set[str | bool | int | float]
NULL_VALUES: set[str | None]
class CharField(Field[str, str, str, Any]):
allow_blank: bool
trim_whitespace: bool
max_length: int | None
min_length: int | None
def __init__(
self,
*,
read_only: bool = ...,
write_only: bool = ...,
required: bool | None = None,
default: _DefaultInitial[StrOrPromise] = ...,
initial: _DefaultInitial[str] = ...,
source: str | None = None,
label: StrOrPromise | None = None,
help_text: StrOrPromise | None = None,
style: dict[str, Any] | None = None,
error_messages: dict[str, StrOrPromise] | None = None,
validators: Sequence[Validator[str]] | None = ...,
allow_null: bool = ...,
allow_blank: bool = ...,
trim_whitespace: bool = ...,
max_length: int = ...,
min_length: int | None = ...,
) -> None: ...
class EmailField(CharField): ...
class RegexField(CharField):
def __init__(
self,
regex: str | Pattern[str],
*,
read_only: bool = ...,
write_only: bool = ...,
required: bool | None = None,
default: _DefaultInitial[StrOrPromise] = ...,
initial: _DefaultInitial[str] = ...,
source: str | None = None,
label: StrOrPromise | None = None,
help_text: StrOrPromise | None = None,
style: dict[str, Any] | None = None,
error_messages: dict[str, StrOrPromise] | None = None,
validators: Sequence[Validator[str]] | None = ...,
allow_null: bool = ...,
allow_blank: bool = ...,
trim_whitespace: bool = ...,
max_length: int = ...,
min_length: int | None = ...,
) -> None: ...
class SlugField(CharField):
allow_unicode: bool
def __init__(
self,
allow_unicode: bool = ...,
*,
read_only: bool = ...,
write_only: bool = ...,
required: bool | None = None,
default: _DefaultInitial[StrOrPromise] = ...,
initial: _DefaultInitial[str] = ...,
source: str | None = None,
label: StrOrPromise | None = None,
help_text: StrOrPromise | None = None,
style: dict[str, Any] | None = None,
error_messages: dict[str, StrOrPromise] | None = None,
validators: Sequence[Validator[str]] | None = ...,
allow_null: bool = ...,
allow_blank: bool = ...,
trim_whitespace: bool = ...,
max_length: int = ...,
min_length: int | None = ...,
) -> None: ...
class URLField(CharField): ...
class UUIDField(Field[uuid.UUID, uuid.UUID | str | int, str, Any]):
valid_formats: Sequence[str]
uuid_format: str
def __init__(
self,
*,
format: str | None = ...,
read_only: bool = ...,
write_only: bool = ...,
required: bool | None = None,
default: _DefaultInitial[uuid.UUID] = ...,
initial: _DefaultInitial[uuid.UUID] = ...,
source: str | None = None,
label: StrOrPromise | None = None,
help_text: StrOrPromise | None = None,
style: dict[str, Any] | None = None,
error_messages: dict[str, StrOrPromise] | None = None,
validators: Sequence[Validator[uuid.UUID]] | None = ...,
allow_null: bool = ...,
) -> None: ...
class IPAddressField(CharField):
protocol: str
unpack_ipv4: bool
def __init__(
self,
protocol: str = ...,
*,
read_only: bool = ...,
write_only: bool = ...,
required: bool | None = None,
default: _DefaultInitial[str] = ...,
initial: _DefaultInitial[str] = ...,
source: str | None = None,
label: StrOrPromise | None = None,
help_text: StrOrPromise | None = None,
style: dict[str, Any] | None = None,
error_messages: dict[str, StrOrPromise] | None = None,
validators: Sequence[Validator[str]] | None = ...,
allow_null: bool = ...,
allow_blank: bool = ...,
trim_whitespace: bool = ...,
max_length: int = ...,
min_length: int | None = ...,
) -> None: ...
class IntegerField(Field[int, float | int | str, int, Any]):
MAX_STRING_LENGTH: int
re_decimal: Pattern
max_value: int | None
min_value: int | None
def __init__(
self,
*,
max_value: int = ...,
min_value: int = ...,
read_only: bool = ...,
write_only: bool = ...,
required: bool | None = None,
default: _DefaultInitial[int] = ...,
initial: _DefaultInitial[int] = ...,
source: str | None = None,
label: StrOrPromise | None = None,
help_text: StrOrPromise | None = None,
style: dict[str, Any] | None = None,
error_messages: dict[str, StrOrPromise] | None = None,
validators: Sequence[Validator[int]] | None = ...,
allow_null: bool = ...,
) -> None: ...
class FloatField(Field[float, float | int | str, str, Any]):
MAX_STRING_LENGTH: int
re_decimal: Pattern
max_value: float | None
min_value: float | None
def __init__(
self,
*,
max_value: float = ...,
min_value: float = ...,
read_only: bool = ...,
write_only: bool = ...,
required: bool | None = None,
default: _DefaultInitial[float] = ...,
initial: _DefaultInitial[float] = ...,
source: str | None = None,
label: StrOrPromise | None = None,
help_text: StrOrPromise | None = None,
style: dict[str, Any] | None = None,
error_messages: dict[str, StrOrPromise] | None = None,
validators: Sequence[Validator[float]] | None = ...,
allow_null: bool = ...,
) -> None: ...
class DecimalField(Field[Decimal, int | float | str | Decimal, str, Any]):
MAX_STRING_LENGTH: int
max_digits: int | None
decimal_places: int | None
coerce_to_string: bool | None
max_value: Decimal | int | float | None
min_value: Decimal | int | float | None
localize: bool
rounding: str | None
normalize_output: bool
max_whole_digits: int | None
def __init__(
self,
max_digits: int | None,
decimal_places: int | None,
coerce_to_string: bool | None = None,
max_value: Decimal | int | float | None = None,
min_value: Decimal | int | float | None = None,
localize: bool = ...,
rounding: str | None = None,
normalize_output: bool = ...,
*,
read_only: bool = ...,
write_only: bool = ...,
required: bool | None = None,
default: _DefaultInitial[Decimal] = ...,
initial: _DefaultInitial[Decimal] = ...,
source: str | None = None,
label: StrOrPromise | None = None,
help_text: StrOrPromise | None = None,
style: dict[str, Any] | None = None,
error_messages: dict[str, StrOrPromise] | None = None,
validators: Sequence[Validator[Decimal]] | None = ...,
allow_null: bool = ...,
) -> None: ...
def validate_precision(self, value: Decimal) -> Decimal: ...
def quantize(self, value: Decimal) -> Decimal: ...
class DateTimeField(Field[datetime.datetime, datetime.datetime | str, str, Any]):
datetime_parser: Callable[[str, str], datetime.datetime]
format: str | None
input_formats: Sequence[str]
timezone: datetime.tzinfo
def __init__(
self,
format: str | None | _Empty = ...,
input_formats: Sequence[str] | None = None,
default_timezone: datetime.tzinfo | None = ...,
*,
read_only: bool = ...,
write_only: bool = ...,
required: bool | None = None,
default: _DefaultInitial[datetime.datetime] = ...,
initial: _DefaultInitial[datetime.datetime] = ...,
source: str | None = None,
label: StrOrPromise | None = None,
help_text: StrOrPromise | None = None,
style: dict[str, Any] | None = None,
error_messages: dict[str, StrOrPromise] | None = None,
validators: Sequence[Validator[datetime.datetime]] | None = ...,
allow_null: bool = ...,
) -> None: ...
def enforce_timezone(self, value: datetime.datetime) -> datetime.datetime: ...
def default_timezone(self) -> str | None: ...
class DateField(Field[datetime.date, datetime.date | str, str, Any]):
datetime_parser: Callable[[str, str], datetime.datetime]
format: str | None
input_formats: Sequence[str]
def __init__(
self,
format: str | None | _Empty = ...,
input_formats: Sequence[str] | None = None,
*,
read_only: bool = ...,
write_only: bool = ...,
required: bool | None = None,
default: _DefaultInitial[datetime.date] = ...,
initial: _DefaultInitial[datetime.date] = ...,
source: str | None = None,
label: StrOrPromise | None = None,
help_text: StrOrPromise | None = None,
style: dict[str, Any] | None = None,
error_messages: dict[str, StrOrPromise] | None = None,
validators: Sequence[Validator[datetime.date]] | None = ...,
allow_null: bool = ...,
) -> None: ...
class TimeField(Field[datetime.time, datetime.time | str, str, Any]):
datetime_parser: Callable[[str, str], datetime.datetime]
format: str | None
input_formats: Sequence[str]
def __init__(
self,
format: str | None | _Empty = ...,
input_formats: Sequence[str] | None = None,
*,
read_only: bool = ...,
write_only: bool = ...,
required: bool | None = None,
default: _DefaultInitial[datetime.time] = ...,
initial: _DefaultInitial[datetime.time] = ...,
source: str | None = None,
label: StrOrPromise | None = None,
help_text: StrOrPromise | None = None,
style: dict[str, Any] | None = None,
error_messages: dict[str, StrOrPromise] | None = None,
validators: Sequence[Validator[datetime.time]] | None = ...,
allow_null: bool = ...,
) -> None: ...
class DurationField(Field[datetime.timedelta, datetime.timedelta | str, str, Any]):
max_value: datetime.timedelta | None
min_value: datetime.timedelta | None
def __init__(
self,
*,
max_value: datetime.timedelta | int | float = ...,
min_value: datetime.timedelta | int | float = ...,
read_only: bool = ...,
write_only: bool = ...,
required: bool | None = None,
default: _DefaultInitial[datetime.timedelta] = ...,
initial: _DefaultInitial[datetime.timedelta] = ...,
source: str | None = None,
label: StrOrPromise | None = None,
help_text: StrOrPromise | None = None,
style: dict[str, Any] | None = None,
error_messages: dict[str, StrOrPromise] | None = None,
validators: Sequence[Validator[datetime.timedelta]] | None = ...,
allow_null: bool = ...,
) -> None: ...
class ChoiceField(Field[str, str | int | tuple[str | int, str | int | tuple], str, Any]):
html_cutoff: int | None
html_cutoff_text: StrOrPromise | None
allow_blank: bool
grouped_choices: dict
choice_strings_to_values: dict[str, Any]
_choices: dict
def __init__(
self,
choices: Sequence[Any],
*,
read_only: bool = ...,
write_only: bool = ...,
required: bool | None = None,
default: _DefaultInitial[StrOrPromise | int] = ...,
initial: _DefaultInitial[str | int] = ...,
source: str | None = None,
label: StrOrPromise | None = None,
help_text: StrOrPromise | None = None,
style: dict[str, Any] | None = None,
error_messages: dict[str, StrOrPromise] | None = None,
validators: Sequence[Validator[Any]] | None = ...,
allow_null: bool = ...,
html_cutoff: int = ...,
html_cutoff_text: StrOrPromise = ...,
allow_blank: bool = ...,
) -> None: ...
def iter_options(self) -> Iterable[Option]: ...
def _get_choices(self) -> dict[Any, Any]: ...
def _set_choices(self, choices: Iterable[Any]) -> None: ...
choices = property(_get_choices, _set_choices)
class MultipleChoiceField(
ChoiceField,
Field[
str,
Sequence[str | int | tuple[str | int, str | int]],
Sequence[str | tuple[str | int, str | int]],
Any,
],
):
allow_empty: bool
def __init__(
self,
*,
choices: Sequence[Any],
read_only: bool = ...,
write_only: bool = ...,
required: bool | None = None,
default: _DefaultInitial[set[str | int] | set[str] | set[int]] = ...,
initial: _DefaultInitial[set[StrOrPromise | int] | set[StrOrPromise] | set[int]] = ...,
source: str | None = None,
label: StrOrPromise | None = None,
help_text: StrOrPromise | None = None,
style: dict[str, Any] | None = None,
error_messages: dict[str, StrOrPromise] | None = None,
validators: Sequence[Validator[Any]] | None = ...,
allow_null: bool = ...,
html_cutoff: int = ...,
html_cutoff_text: StrOrPromise = ...,
allow_blank: bool = ...,
allow_empty: bool = ...,
) -> None: ...
class FilePathField(ChoiceField):
def __init__(
self,
path: str,
match: str | None = None,
recursive: bool = ...,
allow_files: bool = ...,
allow_folders: bool = ...,
required: bool | None = None,
*,
read_only: bool = ...,
write_only: bool = ...,
default: _DefaultInitial[str] = ...,
initial: _DefaultInitial[str] = ...,
source: str | None = None,
label: StrOrPromise | None = None,
help_text: StrOrPromise | None = None,
style: dict[str, Any] | None = None,
error_messages: dict[str, StrOrPromise] | None = None,
validators: Sequence[Validator[Any]] | None = ...,
allow_null: bool = ...,
html_cutoff: int = ...,
html_cutoff_text: StrOrPromise = ...,
allow_blank: bool = ...,
) -> None: ...
class FileField(Field[File, File, str | None, Any]): # this field can return None without raising!
max_length: int
allow_empty_file: bool
use_url: bool
def __init__(
self,
*,
read_only: bool = ...,
write_only: bool = ...,
required: bool | None = None,
default: _DefaultInitial[File] = ...,
initial: _DefaultInitial[File] = ...,
source: str | None = None,
label: StrOrPromise | None = None,
help_text: StrOrPromise | None = None,
style: dict[str, Any] | None = None,
error_messages: dict[str, StrOrPromise] | None = None,
validators: Sequence[Validator[File]] | None = ...,
allow_null: bool = ...,
max_length: int = ...,
allow_empty_file: bool = ...,
use_url: bool = ...,
) -> None: ...
class ImageField(FileField):
_DjangoImageField: SupportsToPython
def __init__(
self,
*,
read_only: bool = ...,
write_only: bool = ...,
required: bool | None = None,
default: _DefaultInitial[File] = ...,
initial: _DefaultInitial[File] = ...,
source: str | None = None,
label: StrOrPromise | None = None,
help_text: StrOrPromise | None = None,
style: dict[str, Any] | None = None,
error_messages: dict[str, StrOrPromise] | None = None,
validators: Sequence[Validator[File]] | None = ...,
allow_null: bool = ...,
max_length: int = ...,
allow_empty_file: bool = ...,
use_url: bool = ...,
_DjangoImageField: type[SupportsToPython] = ...,
) -> None: ...
class _UnvalidatedField(Field): ...
class ListField(Field[list[Any], list[Any], list[Any], Any]):
child: Field
allow_empty: bool
max_length: int | None
min_length: int | None
def __init__(
self,
*,
read_only: bool = ...,
write_only: bool = ...,
required: bool | None = None,
default: _DefaultInitial[list[Any]] = ...,
initial: _DefaultInitial[list[Any]] = ...,
source: str | None = None,
label: StrOrPromise | None = None,
help_text: StrOrPromise | None = None,
style: dict[str, Any] | None = None,
error_messages: dict[str, StrOrPromise] | None = None,
validators: Sequence[Validator[list[Any]]] | None = ...,
allow_null: bool = ...,
child: Field = ...,
allow_empty: bool = ...,
max_length: int | None = ...,
min_length: int | None = ...,
) -> None: ...
def run_child_validation(self, data: list[Mapping[Any, Any]]) -> Any: ...
class DictField(Field[dict[Any, Any], dict[Any, Any], dict[Any, Any], Any]):
child: Field
allow_empty: bool
def __init__(
self,
*,
read_only: bool = ...,
write_only: bool = ...,
required: bool | None = None,
default: _DefaultInitial[dict[Any, Any]] = ...,
initial: _DefaultInitial[dict[Any, Any]] = ...,
source: str | None = None,
label: StrOrPromise | None = None,
help_text: StrOrPromise | None = None,
style: dict[str, Any] | None = None,
error_messages: dict[str, StrOrPromise] | None = None,
validators: Sequence[Validator[dict[Any, Any]]] | None = ...,
allow_null: bool = ...,
child: Field = ...,
allow_empty: bool = ...,
) -> None: ...
def run_child_validation(self, data: Any) -> Any: ...
class HStoreField(DictField):
child: CharField
class JSONField(Field[dict[str, Any] | list[dict[str, Any]], dict[str, Any] | list[dict[str, Any]], str, Any]):
binary: bool
encoder: type[JSONEncoder] | None
decoder: type[JSONDecoder] | None
def __init__(
self,
*,
read_only: bool = ...,
write_only: bool = ...,
required: bool | None = None,
default: _DefaultInitial[Mapping[Any, Any]] = ...,
initial: _DefaultInitial[Mapping[Any, Any]] = ...,
source: str | None = None,
label: StrOrPromise | None = None,
help_text: StrOrPromise | None = None,
style: dict[str, Any] | None = None,
error_messages: dict[str, StrOrPromise] | None = None,
validators: Sequence[Validator[Any]] | None = ...,
allow_null: bool = ...,
binary: bool = ...,
encoder: type[JSONEncoder] | None = ...,
decoder: type[JSONDecoder] | None = ...,
) -> None: ...
class ReadOnlyField(Field): ...
class HiddenField(Field): ...
class SerializerMethodField(Field):
method_name: str
def __init__(
self,
method_name: str | None = ...,
*,
read_only: bool = ...,
write_only: bool = ...,
required: bool | None = None,
default: Any = ...,
initial: Any = ...,
source: str | None = None,
label: StrOrPromise | None = None,
help_text: StrOrPromise | None = None,
style: dict[str, Any] | None = None,
error_messages: dict[str, StrOrPromise] | None = None,
validators: Sequence[Validator[Any]] | None = ...,
allow_null: bool = ...,
) -> None: ...
class ModelField(Field):
model_field: models.Field
max_length: int
def __init__(
self,
model_field: models.Field,
*,
read_only: bool = ...,
write_only: bool = ...,
required: bool | None = None,
default: Any = ...,
initial: Any = ...,
source: str | None = None,
label: StrOrPromise | None = None,
help_text: StrOrPromise | None = None,
style: dict[str, Any] | None = None,
error_messages: dict[str, StrOrPromise] | None = None,
validators: Sequence[Validator[Any]] | None = ...,
allow_null: bool = ...,
max_length: int = ...,
) -> None: ...
07070100000032000081A4000000000000000000000001687648C5000008BA000000000000000000000000000000000000004200000000djangorestframework-stubs-3.16.1/rest_framework-stubs/filters.pyifrom _typeshed import Incomplete
from collections.abc import Iterable, Mapping, Sequence
from typing import Any, TypeVar
from django.db.models import Model, QuerySet
from rest_framework.request import Request
from rest_framework.views import APIView
_MT = TypeVar("_MT", bound=Model)
def search_smart_split(search_terms: list[str]) -> list[str]: ...
class BaseFilterBackend:
def filter_queryset(self, request: Request, queryset: QuerySet[_MT], view: APIView) -> QuerySet[_MT]: ...
def get_schema_fields(self, view: APIView) -> list[Any]: ...
def get_schema_operation_parameters(self, view: APIView) -> list[dict[str, Incomplete]]: ...
class SearchFilter(BaseFilterBackend):
search_param: str
template: str
lookup_prefixes: dict[str, str]
search_title: str
search_description: str
def get_search_fields(self, view: APIView, request: Request) -> Incomplete: ...
def get_search_terms(self, request: Request) -> list[str]: ...
def construct_search(self, field_name: str, queryset: QuerySet) -> str: ...
def must_call_distinct(self, queryset: QuerySet, search_fields: Incomplete) -> bool: ...
def to_html(self, request: Request, queryset: QuerySet, view: APIView) -> str: ...
class OrderingFilter(BaseFilterBackend):
ordering_param: str
ordering_fields: Sequence[str] | None
ordering_title: str
ordering_description: str
template: str
def get_ordering(self, request: Request, queryset: QuerySet, view: APIView) -> Sequence[str] | None: ...
def get_default_ordering(self, view: APIView) -> Sequence[str] | None: ...
def get_default_valid_fields(
self, queryset: QuerySet, view: APIView, context: Mapping[str, Any] = ...
) -> list[tuple[str, str]]: ...
def get_valid_fields(
self, queryset: QuerySet, view: APIView, context: Mapping[str, Any] = ...
) -> list[tuple[str, str]]: ...
def remove_invalid_fields(
self, queryset: QuerySet, fields: Iterable[str], view: APIView, request: Request
) -> list[str]: ...
def get_template_context(self, request: Request, queryset: QuerySet, view: APIView) -> dict[str, Any]: ...
def to_html(self, request: Request, queryset: QuerySet, view: APIView) -> str: ...
07070100000033000081A4000000000000000000000001687648C5000011E0000000000000000000000000000000000000004300000000djangorestframework-stubs-3.16.1/rest_framework-stubs/generics.pyifrom _typeshed import Incomplete
from collections.abc import Sequence
from typing import Any, Protocol, TypeVar
from django.db.models import Manager, Model
from django.db.models.query import QuerySet
from rest_framework import mixins, views
from rest_framework.filters import BaseFilterBackend
from rest_framework.pagination import BasePagination
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.serializers import BaseSerializer
from typing_extensions import Self
_MT_co = TypeVar("_MT_co", bound=Model, covariant=True)
_MT_inv = TypeVar("_MT_inv", bound=Model)
def get_object_or_404(
queryset: type[_MT_co] | Manager[_MT_co] | QuerySet[_MT_co], *filter_args: Any, **filter_kwargs: Any
) -> _MT_co: ...
class UsesQuerySet(Protocol[_MT_co]):
def get_queryset(self) -> QuerySet[_MT_co]: ...
# Can't just use BaseFilterBackend because there's also things like django_filters.rest_framework.DjangoFilterBackend that are
# valid options but don't extend it
class BaseFilterProtocol(Protocol[_MT_inv]):
def filter_queryset(
self, request: Request, queryset: QuerySet[_MT_inv], view: views.APIView
) -> QuerySet[_MT_inv]: ...
def get_schema_fields(self, view: views.APIView) -> list[Any]: ...
def get_schema_operation_parameters(self, view: views.APIView) -> Incomplete: ...
class GenericAPIView(views.APIView, UsesQuerySet[_MT_co]):
queryset: QuerySet[_MT_co] | Manager[_MT_co] | None
serializer_class: type[BaseSerializer[_MT_co]] | None
lookup_field: str
lookup_url_kwarg: str | None
filter_backends: Sequence[type[BaseFilterBackend | BaseFilterProtocol[_MT_co]]]
pagination_class: type[BasePagination] | None
def __class_getitem__(cls, *args: Any, **kwargs: Any) -> type[Self]: ...
def get_object(self) -> _MT_co: ...
def get_serializer(self, *args: Any, **kwargs: Any) -> BaseSerializer[_MT_co]: ...
def get_serializer_class(self) -> type[BaseSerializer[_MT_co]]: ...
def get_serializer_context(self) -> dict[str, Any]: ...
def filter_queryset(self, queryset: QuerySet[_MT_co]) -> QuerySet[_MT_co]: ...
@property
def paginator(self) -> BasePagination | None: ...
def paginate_queryset(self, queryset: QuerySet[_MT_co] | Sequence[Any]) -> Sequence[Any] | None: ...
def get_paginated_response(self, data: Any) -> Response: ...
class CreateAPIView(mixins.CreateModelMixin, GenericAPIView[_MT_co]):
def post(self, request: Request, *args: Any, **kwargs: Any) -> Response: ...
class ListAPIView(mixins.ListModelMixin, GenericAPIView[_MT_co]):
def get(self, request: Request, *args: Any, **kwargs: Any) -> Response: ...
class RetrieveAPIView(mixins.RetrieveModelMixin, GenericAPIView[_MT_co]):
def get(self, request: Request, *args: Any, **kwargs: Any) -> Response: ...
class DestroyAPIView(mixins.DestroyModelMixin, GenericAPIView[_MT_co]):
def delete(self, request: Request, *args: Any, **kwargs: Any) -> Response: ...
class UpdateAPIView(mixins.UpdateModelMixin, GenericAPIView[_MT_co]):
def put(self, request: Request, *args: Any, **kwargs: Any) -> Response: ...
def patch(self, request: Request, *args: Any, **kwargs: Any) -> Response: ...
class ListCreateAPIView(mixins.ListModelMixin, mixins.CreateModelMixin, GenericAPIView[_MT_co]):
def get(self, request: Request, *args: Any, **kwargs: Any) -> Response: ...
def post(self, request: Request, *args: Any, **kwargs: Any) -> Response: ...
class RetrieveUpdateAPIView(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, GenericAPIView[_MT_co]):
def get(self, request: Request, *args: Any, **kwargs: Any) -> Response: ...
def put(self, request: Request, *args: Any, **kwargs: Any) -> Response: ...
def patch(self, request: Request, *args: Any, **kwargs: Any) -> Response: ...
class RetrieveDestroyAPIView(mixins.RetrieveModelMixin, mixins.DestroyModelMixin, GenericAPIView[_MT_co]):
def get(self, request: Request, *args: Any, **kwargs: Any) -> Response: ...
def delete(self, request: Request, *args: Any, **kwargs: Any) -> Response: ...
class RetrieveUpdateDestroyAPIView(
mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, GenericAPIView[_MT_co]
):
def get(self, request: Request, *args: Any, **kwargs: Any) -> Response: ...
def put(self, request: Request, *args: Any, **kwargs: Any) -> Response: ...
def patch(self, request: Request, *args: Any, **kwargs: Any) -> Response: ...
def delete(self, request: Request, *args: Any, **kwargs: Any) -> Response: ...
07070100000034000041ED000000000000000000000002687648C500000000000000000000000000000000000000000000004100000000djangorestframework-stubs-3.16.1/rest_framework-stubs/management07070100000035000081A4000000000000000000000001687648C500000000000000000000000000000000000000000000004E00000000djangorestframework-stubs-3.16.1/rest_framework-stubs/management/__init__.pyi07070100000036000041ED000000000000000000000002687648C500000000000000000000000000000000000000000000004A00000000djangorestframework-stubs-3.16.1/rest_framework-stubs/management/commands07070100000037000081A4000000000000000000000001687648C500000000000000000000000000000000000000000000005700000000djangorestframework-stubs-3.16.1/rest_framework-stubs/management/commands/__init__.pyi07070100000038000081A4000000000000000000000001687648C5000001CB000000000000000000000000000000000000005D00000000djangorestframework-stubs-3.16.1/rest_framework-stubs/management/commands/generateschema.pyifrom _typeshed import Incomplete
from typing import Any
from django.core.management.base import BaseCommand
OPENAPI_MODE: str
COREAPI_MODE: str
class Command(BaseCommand):
help: str
def get_mode(self) -> Incomplete: ...
def add_arguments(self, parser: Any) -> None: ...
def handle(self, *args: Any, **options: Any) -> None: ...
def get_renderer(self, format: str) -> Incomplete: ...
def get_generator_class(self) -> Incomplete: ...
07070100000039000081A4000000000000000000000001687648C5000002D6000000000000000000000000000000000000004300000000djangorestframework-stubs-3.16.1/rest_framework-stubs/metadata.pyifrom typing import Any
from rest_framework import serializers
from rest_framework.request import Request
from rest_framework.serializers import BaseSerializer
from rest_framework.utils.field_mapping import ClassLookupDict
from rest_framework.views import APIView
class BaseMetadata:
def determine_metadata(self, request: Request, view: APIView) -> Any: ...
class SimpleMetadata(BaseMetadata):
label_lookup: ClassLookupDict[type[serializers.Field], str]
def determine_actions(self, request: Request, view: APIView) -> dict[str, Any]: ...
def get_serializer_info(self, serializer: BaseSerializer) -> dict[str, dict[str, Any]]: ...
def get_field_info(self, field: serializers.Field) -> dict[str, Any]: ...
0707010000003A000081A4000000000000000000000001687648C5000004EC000000000000000000000000000000000000004100000000djangorestframework-stubs-3.16.1/rest_framework-stubs/mixins.pyifrom typing import Any, TypeVar
from django.db.models import Model
from rest_framework.generics import UsesQuerySet
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.serializers import BaseSerializer
_MT = TypeVar("_MT", bound=Model)
class CreateModelMixin:
def create(self, request: Request, *args: Any, **kwargs: Any) -> Response: ...
def perform_create(self: UsesQuerySet[_MT], serializer: BaseSerializer[_MT]) -> None: ...
def get_success_headers(self, data: Any) -> dict[str, str]: ...
class ListModelMixin:
def list(self, request: Request, *args: Any, **kwargs: Any) -> Response: ...
class RetrieveModelMixin:
def retrieve(self, request: Request, *args: Any, **kwargs: Any) -> Response: ...
class UpdateModelMixin:
def update(self, request: Request, *args: Any, **kwargs: Any) -> Response: ...
def perform_update(self: UsesQuerySet[_MT], serializer: BaseSerializer[_MT]) -> None: ...
def partial_update(self, request: Request, *args: Any, **kwargs: Any) -> Response: ...
class DestroyModelMixin:
def destroy(self, request: Request, *args: Any, **kwargs: Any) -> Response: ...
def perform_destroy(self: UsesQuerySet[_MT], instance: _MT) -> None: ...
0707010000003B000081A4000000000000000000000001687648C500000320000000000000000000000000000000000000004600000000djangorestframework-stubs-3.16.1/rest_framework-stubs/negotiation.pyifrom _typeshed import Incomplete
from collections.abc import Iterable
from rest_framework.parsers import BaseParser
from rest_framework.renderers import BaseRenderer
from rest_framework.request import Request
from rest_framework.settings import api_settings
class BaseContentNegotiation:
def select_parser(self, request: Request, parsers: Iterable[BaseParser]) -> BaseParser | None: ...
def select_renderer(
self, request: Request, renderers: Iterable[BaseRenderer], format_suffix: str | None = ...
) -> Incomplete: ...
class DefaultContentNegotiation(BaseContentNegotiation):
settings = api_settings
def filter_renderers(self, renderers: Iterable[BaseRenderer], format: str) -> list[BaseRenderer]: ...
def get_accept_list(self, request: Request) -> list[str]: ...
0707010000003C000081A4000000000000000000000001687648C5000013E7000000000000000000000000000000000000004500000000djangorestframework-stubs-3.16.1/rest_framework-stubs/pagination.pyifrom collections.abc import Callable, Sequence
from typing import Any, NamedTuple, TypeVar
from coreapi import Field as CoreAPIField # type: ignore[import-untyped]
from django.core.paginator import Page, Paginator
from django.db.models import Model, QuerySet
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.views import APIView
from typing_extensions import TypedDict
def _positive_int(integer_string: str, strict: bool = ..., cutoff: int | None = ...) -> int: ...
def _divide_with_ceil(a: int, b: int) -> int: ...
def _get_displayed_page_numbers(current: int, final: int) -> list[int | None]: ...
def _get_page_links(
page_numbers: Sequence[int | None], current: int, url_func: Callable[[int], str]
) -> list[PageLink]: ...
def _reverse_ordering(ordering_tuple: Sequence[str]) -> tuple[str, ...]: ...
class Cursor(NamedTuple):
offset: int
reverse: bool
position: int | None
class PageLink(NamedTuple):
url: str | None
number: int | None
is_active: bool
is_break: bool
class HtmlContext(TypedDict):
previous_url: str
next_url: str
class HtmlContextWithPageLinks(HtmlContext):
page_links: list[PageLink]
PAGE_BREAK: PageLink
_MT = TypeVar("_MT", bound=Model)
class BasePagination:
display_page_controls: bool
def get_paginated_response_schema(self, schema: dict[str, Any]) -> dict[str, Any]: ...
def get_paginated_response(self, data: Any) -> Response: ...
def get_results(self, data: dict[str, Any]) -> Any: ...
def get_schema_fields(self, view: APIView) -> list[Any]: ...
def get_schema_operation_parameters(self, view: APIView) -> list[Any]: ...
def paginate_queryset(
self, queryset: QuerySet[_MT], request: Request, view: APIView | None = ...
) -> list[_MT] | None: ...
def to_html(self) -> str: ...
class PageNumberPagination(BasePagination):
display_page_controls: bool
django_paginator_class: type[Paginator]
invalid_page_message: str
last_page_strings: Sequence[str]
max_page_size: int | None
page_query_description: str
page_query_param: str
page_size_query_description: str
page_size_query_param: str | None
page_size: int | None
page: Page | None
request: Request | None
template: str | None
def paginate_queryset(
self, queryset: QuerySet[_MT], request: Request, view: APIView | None = ...
) -> list[_MT] | None: ...
def get_paginated_response_schema(self, schema: dict[str, Any]) -> dict[str, Any]: ...
def get_schema_fields(self, view: APIView) -> list[CoreAPIField]: ...
def get_schema_operation_parameters(self, view: APIView) -> list[dict[str, Any]]: ...
def get_page_number(self, request: Request, paginator: Paginator) -> int | str: ...
def get_page_size(self, request: Request) -> int | None: ...
def get_next_link(self) -> str | None: ...
def get_previous_link(self) -> str | None: ...
def get_html_context(self) -> HtmlContextWithPageLinks: ...
class LimitOffsetPagination(BasePagination):
count: int | None
default_limit: int | None
limit_query_description: str
limit_query_param: str
limit: int | None
max_limit: int | None
offset_query_description: str
offset_query_param: str
offset: int | None
request: Request | None
template: str | None
def paginate_queryset(
self, queryset: QuerySet[_MT], request: Request, view: APIView | None = ...
) -> list[_MT] | None: ...
def get_limit(self, request: Request) -> int | None: ...
def get_offset(self, request: Request) -> int: ...
def get_next_link(self) -> str | None: ...
def get_previous_link(self) -> str | None: ...
def get_html_context(self) -> HtmlContextWithPageLinks: ...
def get_count(self, queryset: QuerySet | Sequence) -> int: ...
class CursorPagination(BasePagination):
base_url: str | None
cursor_query_description: str
cursor_query_param: str
cursor: Cursor | None
has_next: bool | None
has_previous: bool | None
invalid_cursor_message: str
max_page_size: int | None
next_position: str | None
offset_cutoff: int
ordering: str | list[str] | tuple[str, ...]
page_size_query_description: str
page_size_query_param: str | None
page_size: int | None
page: list[Any] | None
previous_position: str | None
template: str | None
def paginate_queryset(
self, queryset: QuerySet[_MT], request: Request, view: APIView | None = ...
) -> list[_MT] | None: ...
def get_page_size(self, request: Request) -> int | None: ...
def get_next_link(self) -> str | None: ...
def get_previous_link(self) -> str | None: ...
def get_html_context(self) -> HtmlContext: ...
def get_ordering(self, request: Request, queryset: QuerySet, view: APIView) -> tuple[str, ...]: ...
def decode_cursor(self, request: Request) -> Cursor | None: ...
def encode_cursor(self, cursor: Cursor) -> str: ...
def _get_position_from_instance(self, instance: Any, ordering: Sequence[str]) -> str: ...
0707010000003D000081A4000000000000000000000001687648C500000702000000000000000000000000000000000000004200000000djangorestframework-stubs-3.16.1/rest_framework-stubs/parsers.pyifrom collections.abc import Mapping
from typing import IO, Any, Generic, TypeVar
from django.core.files.uploadedfile import UploadedFile
from django.http.request import _ImmutableQueryDict
from django.utils.datastructures import MultiValueDict
from rest_framework.renderers import JSONRenderer
_Data = TypeVar("_Data")
_Files = TypeVar("_Files")
class DataAndFiles(Generic[_Data, _Files]):
data: _Data
files: _Files
def __init__(self, data: _Data, files: _Files) -> None: ...
class BaseParser:
media_type: str
def parse(
self, stream: IO[Any], media_type: str | None = ..., parser_context: Mapping[str, Any] | None = ...
) -> Mapping[Any, Any] | DataAndFiles: ...
class JSONParser(BaseParser):
renderer_class: type[JSONRenderer]
strict: bool
def parse(
self, stream: IO[Any], media_type: str | None = ..., parser_context: Mapping[str, Any] | None = ...
) -> dict[str, Any]: ...
class FormParser(BaseParser):
def parse(
self, stream: IO[Any], media_type: str | None = ..., parser_context: Mapping[str, Any] | None = ...
) -> _ImmutableQueryDict: ...
class MultiPartParser(BaseParser):
def parse(
self, stream: IO[Any], media_type: str | None = ..., parser_context: Mapping[str, Any] | None = ...
) -> DataAndFiles[_ImmutableQueryDict, MultiValueDict]: ...
class FileUploadParser(BaseParser):
errors: dict[str, str]
def parse(
self, stream: IO[Any], media_type: str | None = ..., parser_context: Mapping[str, Any] | None = ...
) -> DataAndFiles[None, Mapping[str, UploadedFile]]: ...
def get_filename(self, stream: IO[Any], media_type: str | None, parser_context: Mapping[str, Any]) -> str: ...
def get_encoded_filename(self, filename_parm: Mapping[str, Any]) -> str: ...
0707010000003E000081A4000000000000000000000001687648C500000BE9000000000000000000000000000000000000004600000000djangorestframework-stubs-3.16.1/rest_framework-stubs/permissions.pyifrom _typeshed import Incomplete
from collections.abc import Sequence
from typing import Any, Protocol, TypeAlias
from django.db.models import Model, QuerySet
from rest_framework.request import Request
from rest_framework.views import APIView
SAFE_METHODS: Sequence[str]
class _SupportsHasPermission(Protocol):
def has_permission(self, request: Request, view: APIView) -> bool: ...
def has_object_permission(self, request: Request, view: APIView, obj: Any) -> bool: ...
# https://github.com/python/mypy/issues/12392
_PermissionClass: TypeAlias = type[BasePermission] | OperandHolder | SingleOperandHolder
class OperationHolderMixin:
def __and__(self, other: _PermissionClass) -> OperandHolder: ...
def __or__(self, other: _PermissionClass) -> OperandHolder: ...
def __rand__(self, other: _PermissionClass) -> OperandHolder: ...
def __ror__(self, other: _PermissionClass) -> OperandHolder: ...
def __invert__(self) -> SingleOperandHolder: ...
class SingleOperandHolder(OperationHolderMixin):
operator_class: _SupportsHasPermission
op1_class: _PermissionClass
def __init__(self, operator_class: _SupportsHasPermission, op1_class: _PermissionClass) -> None: ...
def __call__(self, *args: Incomplete, **kwargs: Incomplete) -> _SupportsHasPermission: ...
class OperandHolder(OperationHolderMixin):
operator_class: _SupportsHasPermission
op1_class: _PermissionClass
op2_class: _PermissionClass
def __init__(
self, operator_class: _SupportsHasPermission, op1_class: _PermissionClass, op2_class: _PermissionClass
) -> None: ...
def __call__(self, *args: Incomplete, **kwargs: Incomplete) -> _SupportsHasPermission: ...
class AND(_SupportsHasPermission):
def __init__(self, op1: _SupportsHasPermission, op2: _SupportsHasPermission) -> None: ...
class OR(_SupportsHasPermission):
def __init__(self, op1: _SupportsHasPermission, op2: _SupportsHasPermission) -> None: ...
class NOT(_SupportsHasPermission):
def __init__(self, op1: _SupportsHasPermission) -> None: ...
class BasePermissionMetaclass(OperationHolderMixin, type): ... # type: ignore[misc,unused-ignore]
class BasePermission(metaclass=BasePermissionMetaclass):
def has_permission(self, request: Request, view: APIView) -> bool: ...
def has_object_permission(self, request: Request, view: APIView, obj: Any) -> bool: ...
class AllowAny(BasePermission): ...
class IsAuthenticated(BasePermission): ...
class IsAdminUser(BasePermission): ...
class IsAuthenticatedOrReadOnly(BasePermission): ...
class DjangoModelPermissions(BasePermission):
perms_map: dict[str, list[str]]
authenticated_users_only: bool
def get_required_permissions(self, method: str, model_cls: type[Model]) -> list[str]: ...
def _queryset(self, view: APIView) -> QuerySet: ...
class DjangoModelPermissionsOrAnonReadOnly(DjangoModelPermissions): ...
class DjangoObjectPermissions(DjangoModelPermissions):
def get_required_object_permissions(self, method: str, model_cls: type[Model]) -> list[str]: ...
0707010000003F000081A4000000000000000000000001687648C500001BB9000000000000000000000000000000000000004400000000djangorestframework-stubs-3.16.1/rest_framework-stubs/relations.pyifrom collections.abc import Callable, Iterable, Mapping, Sequence
from typing import Any, TypeVar
from django.db.models import Manager, Model, QuerySet
from django_stubs_ext import StrOrPromise
from rest_framework.fields import Field, Option
from rest_framework.request import Request
from rest_framework.validators import Validator
from typing_extensions import Self
def method_overridden(method_name: str, klass: type, instance: Model) -> bool: ...
class ObjectValueError(ValueError): ...
class ObjectTypeError(TypeError): ...
class Hyperlink(str):
def __new__(cls, url: str, obj: Any) -> Self: ...
def __getnewargs__(self) -> tuple[str, str]: ... # type: ignore[override]
@property
def name(self) -> str: ...
is_hyperlink: bool
obj: Any
class PKOnlyObject:
pk: Any
def __init__(self, pk: Any) -> None: ...
MANY_RELATION_KWARGS: Sequence[str]
_MT = TypeVar("_MT", bound=Model)
_DT = TypeVar("_DT") # Data Type
_PT = TypeVar("_PT") # Primitive Type
class RelatedField(Field[_MT, _DT, _PT, Any]):
queryset: QuerySet[_MT] | Manager[_MT] | None
html_cutoff: int | None
html_cutoff_text: str | None
def __init__(
self,
*,
many: bool = ...,
allow_empty: bool = ...,
queryset: QuerySet[_MT] | Manager[_MT] | None = ...,
html_cutoff: int | None = ...,
html_cutoff_text: str = ...,
read_only: bool = ...,
write_only: bool = ...,
required: bool | None = None,
default: Any = ...,
initial: Any = ...,
source: str | None = None,
label: StrOrPromise | None = ...,
help_text: StrOrPromise | None = None,
allow_null: bool = ...,
validators: Sequence[Validator[_MT]] | None = ...,
error_messages: dict[str, StrOrPromise] | None = ...,
style: dict[str, str] | None = ...,
) -> None: ...
# mypy doesn't accept the typing below, although its accurate to what this class is doing, hence the ignore
def __new__(cls, *args: Any, **kwargs: Any) -> RelatedField[_MT, _DT, _PT] | ManyRelatedField: ... # type: ignore
@classmethod
def many_init(cls, *args: Any, **kwargs: Any) -> ManyRelatedField: ...
def get_queryset(self) -> QuerySet[_MT]: ...
def use_pk_only_optimization(self) -> bool: ...
def get_choices(self, cutoff: int | None = ...) -> dict: ...
@property
def choices(self) -> dict: ...
@property
def grouped_choices(self) -> dict: ...
def iter_options(self) -> Iterable[Option]: ...
def get_attribute(self, instance: _MT) -> _PT | None: ...
def display_value(self, instance: _MT) -> str: ...
class StringRelatedField(RelatedField[_MT, _MT, str]): ...
class PrimaryKeyRelatedField(RelatedField[_MT, _MT, Any]):
pk_field: str | None
def __init__(
self,
*,
many: bool = ...,
allow_empty: bool = ...,
queryset: QuerySet[_MT] | Manager[_MT] | None = ...,
html_cutoff: int | None = ...,
html_cutoff_text: str = ...,
read_only: bool = ...,
write_only: bool = ...,
required: bool | None = None,
default: Any = ...,
initial: Any = ...,
source: str | None = None,
label: StrOrPromise | None = ...,
help_text: StrOrPromise | None = None,
allow_null: bool = ...,
validators: Sequence[Validator[_MT]] | None = ...,
error_messages: dict[str, StrOrPromise] | None = ...,
style: dict[str, str] | None = ...,
pk_field: str | Field | None = ...,
) -> None: ...
class HyperlinkedRelatedField(RelatedField[_MT, str, Hyperlink]):
reverse: Callable
lookup_field: str
lookup_url_kwarg: str
format: str | None
view_name: str | None
def __init__(
self,
view_name: str | None = ...,
*,
many: bool = ...,
allow_empty: bool = ...,
queryset: QuerySet[_MT] | Manager[_MT] | None = ...,
html_cutoff: int | None = ...,
html_cutoff_text: str = ...,
read_only: bool = ...,
write_only: bool = ...,
required: bool | None = None,
default: Any = ...,
initial: Any = ...,
source: str | None = None,
label: StrOrPromise | None = ...,
help_text: StrOrPromise | None = None,
allow_null: bool = ...,
validators: Sequence[Validator[_MT]] | None = ...,
error_messages: dict[str, StrOrPromise] | None = ...,
style: dict[str, str] | None = ...,
lookup_field: str | None = ...,
lookup_url_kwarg: str | None = ...,
format: str | None = ...,
) -> None: ...
def get_object(self, view_name: str, view_args: list[Any], view_kwargs: dict[str, Any]) -> _MT: ...
def get_url(self, obj: Model, view_name: str, request: Request, format: str | None) -> str | None: ...
class HyperlinkedIdentityField(HyperlinkedRelatedField): ...
class SlugRelatedField(RelatedField[_MT, str, str]):
slug_field: str | None
def __init__(
self,
slug_field: str,
*,
many: bool = ...,
allow_empty: bool = ...,
queryset: QuerySet[_MT] | Manager[_MT] | None = ...,
html_cutoff: int | None = ...,
html_cutoff_text: str = ...,
read_only: bool = ...,
write_only: bool = ...,
required: bool | None = None,
default: _DT = ...,
initial: _MT | Callable[[Any], _MT] = ...,
source: str | None = None,
label: StrOrPromise | None = ...,
help_text: StrOrPromise | None = None,
allow_null: bool = ...,
validators: Sequence[Validator[_MT]] | None = ...,
error_messages: dict[str, StrOrPromise] | None = ...,
style: dict[str, str] | None = ...,
) -> None: ...
def to_internal_value(self, data: Any) -> _MT: ...
def to_representation(self, obj: _MT) -> str: ...
class ManyRelatedField(Field[Sequence[Any], Sequence[Any], list[Any], Any]):
default_empty_html: list[object]
html_cutoff: int | None
html_cutoff_text: str | None
child_relation: RelatedField
allow_empty: bool
def __init__(
self,
child_relation: RelatedField = ...,
*,
read_only: bool = ...,
write_only: bool = ...,
required: bool | None = None,
default: Sequence[Any] = ...,
initial: Sequence[Any] | Callable[[Any], Sequence[Any]] = ...,
source: str | None = None,
label: StrOrPromise | None = ...,
help_text: str | None = ...,
style: dict[str, str] | None = ...,
error_messages: dict[str, StrOrPromise] | None = ...,
validators: Sequence[Validator[Sequence[Any]]] | None = ...,
allow_null: bool = ...,
allow_empty: bool = ...,
) -> None: ...
def get_value(self, dictionary: Mapping[Any, Any]) -> list[Any]: ...
def get_choices(self, cutoff: int | None = ...) -> dict: ...
@property
def choices(self) -> dict: ...
@property
def grouped_choices(self) -> dict: ...
def iter_options(self) -> Iterable[Option]: ...
07070100000040000081A4000000000000000000000001687648C500001281000000000000000000000000000000000000004400000000djangorestframework-stubs-3.16.1/rest_framework-stubs/renderers.pyifrom _typeshed import Incomplete
from collections.abc import Iterable, Mapping, Sequence
from json import JSONEncoder
from typing import Any, ClassVar
from django import forms
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.serializers import BaseSerializer
from rest_framework.utils.field_mapping import ClassLookupDict
from rest_framework.views import APIView
def zero_as_none(value: Any) -> Any | None: ...
class BaseRenderer:
media_type: str
format: str
charset: str | None
render_style: str
def render(
self, data: Any, accepted_media_type: str | None = ..., renderer_context: Mapping[str, Any] | None = ...
) -> Any: ...
class JSONRenderer(BaseRenderer):
encoder_class: ClassVar[type[JSONEncoder]]
ensure_ascii: ClassVar[bool]
compact: ClassVar[bool]
strict: ClassVar[bool]
def get_indent(self, accepted_media_type: str, renderer_context: Mapping[str, Any]) -> int | None: ...
class TemplateHTMLRenderer(BaseRenderer):
template_name: str | None
exception_template_names: Sequence[str]
def resolve_template(self, template_names: Iterable[str]) -> Any: ...
def get_template_context(self, data: Any, renderer_context: Mapping[str, Any]) -> Incomplete: ...
def get_template_names(self, response: Response, view: APIView) -> list[str]: ...
def get_exception_template(self, response: Response) -> Any: ...
class StaticHTMLRenderer(TemplateHTMLRenderer): ...
class HTMLFormRenderer(BaseRenderer):
template_pack: str
base_template: str
default_style: ClassLookupDict
def render_field(self, field: Incomplete, parent_style: Mapping[str, Any]) -> str: ...
class BrowsableAPIRenderer(BaseRenderer):
"""
HTML renderer used to self-document the API.
"""
template: str
filter_template: str
code_style: str
form_renderer_class: type[BaseRenderer]
def get_default_renderer(self, view: APIView) -> BaseRenderer: ...
def get_content(
self, renderer: BaseRenderer, data: Any, accepted_media_type: str, renderer_context: Mapping[str, Any]
) -> str: ...
def show_form_for_method(self, view: APIView, method: str, request: Request, obj: Any) -> bool: ...
def _get_serializer(
self,
serializer_class: type[BaseSerializer],
view_instance: APIView,
request: Request,
*args: Incomplete,
**kwargs: Incomplete,
) -> BaseSerializer: ...
def get_rendered_html_form(self, data: Any, view: APIView, method: str, request: Request) -> Any: ...
def render_form_for_serializer(self, serializer: BaseSerializer) -> Any: ...
def get_raw_data_form(self, data: Any, view: APIView, method: str, request: Request) -> forms.Form | None: ...
def get_name(self, view: APIView) -> str: ...
def get_description(self, view: APIView, status_code: int) -> str: ...
def get_breadcrumbs(self, request: Request) -> list[tuple[str, str]]: ...
def get_extra_actions(self, view: APIView) -> dict[str, str] | None: ...
def get_filter_form(self, data: Any, view: APIView, request: Request) -> Any | None: ...
def get_context(
self, data: Any, accepted_media_type: str | None, renderer_context: Mapping[str, Any]
) -> dict[str, Any]: ...
class AdminRenderer(BrowsableAPIRenderer):
def get_result_url(self, result: Mapping[str, Any], view: APIView) -> str | None: ...
class DocumentationRenderer(BaseRenderer):
template: str
error_template: str
code_style: str
languages: Sequence[str]
def get_context(self, data: Any, request: Request) -> dict[str, Any]: ...
class SchemaJSRenderer(BaseRenderer):
template: str
class MultiPartRenderer(BaseRenderer):
BOUNDARY: str
class CoreJSONRenderer(BaseRenderer): ...
class _BaseOpenAPIRenderer:
media_type: str
charset: Any
format: str
def __init__(self) -> None: ...
def render(self, data: Any, media_type: Any | None = ..., renderer_context: Any | None = ...) -> Incomplete: ...
def get_schema(self, instance: Any) -> dict[str, Any]: ...
def get_parameters(self, link: Incomplete) -> dict[str, Any]: ...
def get_operation(self, link: Incomplete, name: Incomplete, tag: Incomplete) -> dict[str, Any]: ...
def get_paths(self, document: Incomplete) -> dict[str, Any]: ...
def get_structure(self, data: Any) -> dict[str, Any]: ...
class JSONOpenAPIRenderer(_BaseOpenAPIRenderer):
encoder_class: ClassVar[type[JSONEncoder]]
ensure_ascii: ClassVar[bool]
class OpenAPIRenderer(_BaseOpenAPIRenderer): ...
class CoreAPIOpenAPIRenderer(_BaseOpenAPIRenderer): ...
class CoreAPIJSONOpenAPIRenderer(_BaseOpenAPIRenderer):
ensure_ascii: ClassVar[bool]
07070100000041000081A4000000000000000000000001687648C500000D6C000000000000000000000000000000000000004200000000djangorestframework-stubs-3.16.1/rest_framework-stubs/request.pyifrom _typeshed import Incomplete
from collections.abc import Iterator, Sequence
from contextlib import AbstractContextManager, contextmanager
from types import TracebackType
from typing import Any
from django.contrib.auth.base_user import AbstractBaseUser
from django.contrib.auth.models import AnonymousUser, _User
from django.http import HttpRequest
from django.http.request import _ImmutableQueryDict
from rest_framework.authentication import BaseAuthentication
from rest_framework.authtoken.models import Token
from rest_framework.negotiation import BaseContentNegotiation
from rest_framework.parsers import BaseParser
from rest_framework.renderers import BaseRenderer
from rest_framework.versioning import BaseVersioning
from rest_framework.views import APIView
from typing_extensions import Self
def is_form_media_type(media_type: str) -> bool: ...
class override_method(AbstractContextManager[Request]):
def __init__(self, view: APIView, request: Request, method: str) -> None: ...
def __enter__(self) -> Request: ...
def __exit__(
self,
exc_type: type[BaseException] | None,
exc_value: BaseException | None,
traceback: TracebackType | None,
) -> bool | None: ...
class WrappedAttributeError(Exception): ...
@contextmanager
def wrap_attributeerrors() -> Iterator[None]: ...
class Empty: ...
def clone_request(request: Request, method: str) -> Request: ...
class ForcedAuthentication:
force_user: AnonymousUser | AbstractBaseUser | None
force_token: str | None
def __init__(self, force_user: AnonymousUser | AbstractBaseUser | None, force_token: str | None) -> None: ...
def authenticate(self, request: Request) -> tuple[AnonymousUser | AbstractBaseUser | None, Any | None]: ...
class Request(HttpRequest):
parsers: Sequence[BaseParser] | None
authenticators: Sequence[BaseAuthentication | ForcedAuthentication] | None
negotiator: BaseContentNegotiation | None
accepted_renderer: BaseRenderer
accepted_media_type: str
parser_context: dict[str, Any]
version: str | None
versioning_scheme: BaseVersioning | None
_request: HttpRequest
def __init__(
self,
request: HttpRequest,
parsers: Sequence[BaseParser] | None = ...,
authenticators: Sequence[BaseAuthentication] | None = ...,
negotiator: BaseContentNegotiation | None = ...,
parser_context: dict[str, Any] | None = ...,
) -> None: ...
def __class_getitem__(cls, *args: Any, **kwargs: Any) -> type[Self]: ...
@property
def content_type(self) -> str: ... # type: ignore[override]
@property
def stream(self) -> Any: ...
@property
def query_params(self) -> _ImmutableQueryDict: ...
@property
def data(self) -> dict[str, Any]: ...
@property
def user(self) -> _User | AnonymousUser: ...
@user.setter
def user(self, value: _User | AnonymousUser) -> None: ...
@property
def auth(self) -> Token | Any: ...
@auth.setter
def auth(self, value: Token | Any) -> None: ...
@property
def successful_authenticator(self) -> BaseAuthentication | ForcedAuthentication | None: ...
def __getattr__(self, attr: str) -> Any: ...
@property
def POST(self) -> _ImmutableQueryDict: ... # type: ignore[override]
@property
def FILES(self) -> Incomplete: ... # type: ignore[override]
def force_plaintext_errors(self, value: Any) -> None: ...
07070100000042000081A4000000000000000000000001687648C5000005A3000000000000000000000000000000000000004300000000djangorestframework-stubs-3.16.1/rest_framework-stubs/response.pyifrom collections.abc import Mapping
from typing import Any
from django.core.handlers.wsgi import WSGIRequest
from django.template.base import Template
from django.template.response import SimpleTemplateResponse
from django.test.utils import ContextList
from django.urls import ResolverMatch
from rest_framework.renderers import BaseRenderer
from rest_framework.request import Request
from rest_framework.test import APIClient
from typing_extensions import Self
class Response(SimpleTemplateResponse):
data: Any
exception: bool
content_type: str | None
accepted_renderer: BaseRenderer
accepted_media_type: str
_request: Request
def __init__(
self,
data: Any = ...,
status: int | None = ...,
template_name: str | None = ...,
headers: Mapping[str, str] | None = ...,
exception: bool = ...,
content_type: str | None = ...,
) -> None: ...
def __class_getitem__(cls, *args: Any, **kwargs: Any) -> type[Self]: ...
@property
def rendered_content(self) -> Any: ...
def render(self) -> Any: ...
@property
def status_text(self) -> str: ...
class _MonkeyPatchedResponse(Response):
client: APIClient
context: ContextList | dict[str, Any]
redirect_chain: list[tuple[str, int]]
request: dict[str, Any]
wsgi_request: WSGIRequest
resolver_match: ResolverMatch
templates: list[Template]
def json(self) -> Any: ...
07070100000043000081A4000000000000000000000001687648C5000002A1000000000000000000000000000000000000004200000000djangorestframework-stubs-3.16.1/rest_framework-stubs/reverse.pyifrom collections.abc import Callable, Mapping, Sequence
from typing import Any
from django.http import HttpRequest
def preserve_builtin_query_params(url: str, request: HttpRequest | None = ...) -> str: ...
def reverse(
viewname: str,
args: Sequence[Any] | None = ...,
kwargs: Mapping[str, Any] | None = ...,
request: HttpRequest | None = ...,
format: str | None = ...,
**extra: Any,
) -> str: ...
def _reverse(
viewname: str,
args: Sequence[Any] | None = ...,
kwargs: Mapping[str, Any] | None = ...,
request: HttpRequest | None = ...,
format: str | None = ...,
**extra: Any,
) -> str: ...
reverse_lazy: Callable[..., str]
07070100000044000081A4000000000000000000000001687648C500000A41000000000000000000000000000000000000004200000000djangorestframework-stubs-3.16.1/rest_framework-stubs/routers.pyifrom collections.abc import Callable, Iterable, Mapping
from typing import Any, NamedTuple
from rest_framework import views
from rest_framework.renderers import BaseRenderer
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.schemas import SchemaGenerator
from rest_framework.schemas.views import SchemaView
from rest_framework.urlpatterns import _AnyURL
from rest_framework.viewsets import ViewSetMixin
class Route(NamedTuple):
url: str
mapping: dict[str, str]
name: str
detail: bool
initkwargs: dict[str, Any]
class DynamicRoute(NamedTuple):
url: str
name: str
detail: bool
initkwargs: dict[str, Any]
def escape_curly_brackets(url_path: str) -> str: ...
def flatten(list_of_lists: Iterable[Iterable[Any]]) -> Iterable[Any]: ...
class BaseRouter:
registry: list[tuple[str, type[ViewSetMixin], str]]
def register(
self, prefix: str, viewset: type[ViewSetMixin], basename: str | None = ..., base_name: str | None = ...
) -> None: ...
def is_already_registered(self, new_basename: str) -> bool: ...
def get_default_basename(self, viewset: type[ViewSetMixin]) -> str: ...
def get_urls(self) -> list[_AnyURL]: ...
@property
def urls(self) -> list[_AnyURL]: ...
class SimpleRouter(BaseRouter):
routes: list[Route | DynamicRoute]
trailing_slash: str
def __init__(self, trailing_slash: bool = ..., use_regex_path: bool = ...) -> None: ...
def get_routes(self, viewset: type[ViewSetMixin]) -> list[Route]: ...
def _get_dynamic_route(self, route: DynamicRoute, action: Any) -> Route: ...
def get_method_map(self, viewset: type[ViewSetMixin], method_map: Mapping[str, str]) -> dict[str, str]: ...
def get_lookup_regex(self, viewset: type[ViewSetMixin], lookup_prefix: str = ...) -> str: ...
class APIRootView(views.APIView):
_ignore_model_permissions: bool
api_root_dict: dict[str, str] | None
def get(self, request: Request, *args: Any, **kwargs: Any) -> Response: ...
class DefaultRouter(SimpleRouter):
include_root_view: bool
include_format_suffixes: bool
root_view_name: str
default_schema_renderers: Any
APIRootView: type[APIRootView]
APISchemaView: type[SchemaView]
SchemaGenerator: type[SchemaGenerator]
root_renderers: list[type[BaseRenderer]]
def __init__(
self,
trailing_slash: bool = True,
use_regex_path: bool = True,
*,
root_renderers: list[type[BaseRenderer]] = ...,
) -> None: ...
def get_api_root_view(self, api_urls: Any | None = ...) -> Callable: ...
07070100000045000041ED000000000000000000000002687648C500000000000000000000000000000000000000000000003E00000000djangorestframework-stubs-3.16.1/rest_framework-stubs/schemas07070100000046000081A4000000000000000000000001687648C5000003CD000000000000000000000000000000000000004B00000000djangorestframework-stubs-3.16.1/rest_framework-stubs/schemas/__init__.pyifrom collections.abc import Callable, Sequence
from typing import Any
from rest_framework.renderers import BaseRenderer
from rest_framework.urlpatterns import _AnyURL
from . import coreapi as coreapi
from . import openapi as openapi
from .coreapi import AutoSchema as AutoSchema
from .coreapi import ManualSchema as ManualSchema
from .coreapi import SchemaGenerator as SchemaGenerator
from .generators import BaseSchemaGenerator
from .inspectors import DefaultSchema as DefaultSchema
def get_schema_view(
title: str | None = ...,
url: str | None = ...,
description: str | None = ...,
urlconf: str | None = ...,
renderer_classes: Sequence[type[BaseRenderer]] | None = ...,
public: bool = ...,
patterns: Sequence[_AnyURL] | None = ...,
generator_class: type[BaseSchemaGenerator] = ...,
authentication_classes: Sequence[str] = ...,
permission_classes: Sequence[str] = ...,
version: str | None = ...,
) -> Callable[..., Any]: ...
07070100000047000081A4000000000000000000000001687648C500000B19000000000000000000000000000000000000004A00000000djangorestframework-stubs-3.16.1/rest_framework-stubs/schemas/coreapi.pyifrom _typeshed import Incomplete
from collections import Counter
from collections.abc import Iterable, Sequence
from typing import Any
from rest_framework.compat import coreapi
from rest_framework.fields import Field
from rest_framework.request import Request
from rest_framework.urlpatterns import _AnyURL
from rest_framework.views import APIView
from .generators import BaseSchemaGenerator as BaseSchemaGenerator
from .inspectors import ViewInspector as ViewInspector
def common_path(paths: Iterable[str]) -> str: ...
def is_custom_action(action: str) -> bool: ...
def distribute_links(obj: Any) -> None: ...
INSERT_INTO_COLLISION_FMT: str
class LinkNode(dict):
links: list[Any]
methods_counter: Counter
def __init__(self) -> None: ...
def get_available_key(self, preferred_key: str) -> str: ...
def insert_into(target: LinkNode, keys: Sequence[str], value: Any) -> None: ...
class SchemaGenerator(BaseSchemaGenerator):
default_mapping: dict[str, str]
coerce_method_names: dict[str, str] | None
def __init__(
self,
urlconf: str | None = ...,
title: str | None = ...,
description: str | None = ...,
version: str | None = ...,
patterns: Sequence[_AnyURL] | None = ...,
url: str | None = ...,
endpoints: Sequence[tuple[str, str, Any]] | None = ...,
) -> None: ...
def get_links(self, request: Request | None = ...) -> LinkNode | None: ...
def get_schema(self, request: Request | None = ..., public: bool = ...) -> coreapi.Document | None: ...
def get_keys(self, subpath: Any, method: Any, view: APIView) -> list[str]: ...
def determine_path_prefix(self, paths: list[str]) -> str: ...
def field_to_schema(field: Field) -> Incomplete: ...
class AutoSchema(ViewInspector):
def __init__(self, manual_fields: list[coreapi.Field] | None = ...) -> None: ...
def get_link(self, path: str, method: str, base_url: str) -> coreapi.Link: ...
def get_path_fields(self, path: str, method: str) -> list[coreapi.Field]: ...
def get_serializer_fields(self, path: str, method: str) -> list[coreapi.Field]: ...
def get_pagination_fields(self, path: str, method: str) -> dict[str, Any]: ...
def get_filter_fields(self, path: str, method: str) -> list[dict[str, Any]]: ...
def get_manual_fields(self, path: str, method: str) -> list[coreapi.Field]: ...
@staticmethod
def update_fields(fields: list[coreapi.Field], update_with: list[coreapi.Field]) -> list[coreapi.Field]: ...
def get_encoding(self, path: str, method: str) -> str: ...
class ManualSchema(ViewInspector):
def __init__(self, fields: list[coreapi.Field], description: str = ..., encoding: str | None = ...) -> None: ...
def get_link(self, path: str, method: str, base_url: str) -> coreapi.Link: ...
def is_enabled() -> bool: ...
07070100000048000081A4000000000000000000000001687648C50000085E000000000000000000000000000000000000004D00000000djangorestframework-stubs-3.16.1/rest_framework-stubs/schemas/generators.pyifrom _typeshed import Incomplete
from collections.abc import Iterable, Sequence
from types import ModuleType
from typing import Any, TypeAlias
from django.db.models.base import Model
from rest_framework.compat import coreapi
from rest_framework.request import Request
from rest_framework.urlpatterns import _AnyURL
from rest_framework.views import APIView
def common_path(paths: Iterable[str]) -> str: ...
def get_pk_name(model: type[Model]) -> str: ...
def is_api_view(callback: Any) -> bool: ...
def endpoint_ordering(endpoint: tuple[Incomplete, Incomplete, Incomplete]) -> tuple[int]: ...
_APIEndpoint: TypeAlias = tuple[str, str, Any]
class EndpointEnumerator:
patterns: Sequence[_AnyURL] | None
def __init__(
self,
patterns: Sequence[_AnyURL] | None = ...,
urlconf: str | ModuleType | None = ...,
) -> None: ...
def get_api_endpoints(self, patterns: Iterable[_AnyURL] | None = ..., prefix: str = ...) -> list[_APIEndpoint]: ...
def get_path_from_regex(self, path_regex: str) -> str: ...
def should_include_endpoint(self, path: str, callback: Any) -> bool: ...
def get_allowed_methods(self, callback: Any) -> list[str]: ...
class BaseSchemaGenerator:
endpoint_inspector_cls: type[EndpointEnumerator]
coerce_path_pk: bool | None
patterns: Sequence[_AnyURL] | None
urlconf: str | None
title: str | None
description: str | None
version: str | None
url: str | None
endpoints: Sequence[_APIEndpoint] | None
def __init__(
self,
title: str | None = ...,
url: str | None = ...,
description: str | None = ...,
patterns: Sequence[_AnyURL] | None = ...,
urlconf: str | None = ...,
version: str | None = ...,
) -> None: ...
def create_view(self, callback: Any, method: str, request: Request | None = ...) -> Any: ...
def coerce_path(self, path: str, method: str, view: APIView) -> str: ...
def get_schema(self, request: Request | None = ..., public: bool = ...) -> coreapi.Document | None: ...
def has_view_permissions(self, path: str, method: str, view: APIView) -> bool: ...
07070100000049000081A4000000000000000000000001687648C50000024D000000000000000000000000000000000000004D00000000djangorestframework-stubs-3.16.1/rest_framework-stubs/schemas/inspectors.pyifrom _typeshed import Incomplete
from collections.abc import Mapping
from re import Pattern
from typing import Any
class ViewInspector:
header_regex: Pattern
instance_schemas: Mapping[str, Any]
def __init__(self) -> None: ...
def __get__(self, instance: Any, owner: Any) -> Incomplete: ...
def __set__(self, instance: Any, other: Any) -> None: ...
@property
def view(self) -> Incomplete: ...
@view.setter
def view(self, value: Any) -> None: ...
def get_description(self, path: Any, method: Any) -> str: ...
class DefaultSchema(ViewInspector): ...
0707010000004A000081A4000000000000000000000001687648C500000DEF000000000000000000000000000000000000004A00000000djangorestframework-stubs-3.16.1/rest_framework-stubs/schemas/openapi.pyifrom collections.abc import Sequence
from typing import Any
from rest_framework.fields import Field
from rest_framework.pagination import BasePagination
from rest_framework.request import Request
from rest_framework.serializers import BaseSerializer
from typing_extensions import TypedDict
from .generators import BaseSchemaGenerator as BaseSchemaGenerator
from .inspectors import ViewInspector as ViewInspector
# OpenAPI requires its own typings. Below are minimal typing.
# TODO: evaluate using a 3rd party typing package for this, e.g.: https://github.com/meeshkan/openapi-typed
class DRFOpenAPIInfo(TypedDict, total=False):
title: str
version: str
description: str
class ExternalDocumentationObject(TypedDict, total=False):
description: str
url: str
class DRFOpenAPISchema(TypedDict, total=False):
openapi: str
info: DRFOpenAPIInfo
paths: dict[str, dict[str, Any]]
components: dict[str, dict[str, Any]]
security: list[dict[str, list[Any]]]
tags: list[dict[str, Any]]
externalDocs: ExternalDocumentationObject
servers: list[dict[str, Any]]
class SchemaGenerator(BaseSchemaGenerator):
def get_info(self) -> DRFOpenAPIInfo: ...
def check_duplicate_operation_id(self, paths: dict[str, dict[str, Any]]) -> None: ...
def get_schema(self, request: Request = ..., public: bool = ...) -> DRFOpenAPISchema: ... # type: ignore[override]
class AutoSchema(ViewInspector):
operation_id_base: str | None
component_name: str | None
request_media_types: list[str]
response_media_types: list[str]
method_mapping: dict[str, str]
def __init__(
self, tags: Sequence[str] = ..., operation_id_base: str | None = ..., component_name: str | None = ...
) -> None: ...
def get_operation(self, path: str, method: str) -> dict[str, Any]: ...
def get_component_name(self, serializer: BaseSerializer) -> str: ...
def get_components(self, path: str, method: str) -> dict[str, Any]: ...
def get_operation_id_base(self, path: str, method: str, action: Any) -> str: ...
def get_operation_id(self, path: str, method: str) -> str: ...
def get_path_parameters(self, path: str, method: str) -> list[dict[str, Any]]: ...
def get_filter_parameters(self, path: str, method: str) -> list[dict[str, Any]]: ...
def allows_filters(self, path: str, method: str) -> bool: ...
def get_pagination_parameters(self, path: str, method: str) -> list[dict[str, Any]]: ...
def map_choicefield(self, field: Field) -> dict[str, Any]: ...
def map_field(self, field: Field) -> dict[str, Any]: ...
def map_serializer(self, serializer: BaseSerializer) -> dict[str, Any]: ...
def map_field_validators(self, field: Any, schema: Any) -> None: ...
def get_field_name(self, field: Field) -> str: ...
def get_paginator(self) -> type[BasePagination] | None: ...
def map_parsers(self, path: str, method: str) -> list[str]: ...
def map_renderers(self, path: str, method: str) -> list[str]: ...
def get_serializer(self, path: str, method: str) -> BaseSerializer | None: ...
def get_request_serializer(self, path: str, method: str) -> BaseSerializer | None: ...
def get_response_serializer(self, path: str, method: str) -> BaseSerializer | None: ...
def get_reference(self, serializer: BaseSerializer) -> dict[str, str]: ...
def get_request_body(self, path: str, method: str) -> dict[str, Any]: ...
def get_responses(self, path: str, method: str) -> dict[str, Any]: ...
def get_tags(self, path: str, method: str) -> list[str]: ...
0707010000004B000081A4000000000000000000000001687648C500000105000000000000000000000000000000000000004800000000djangorestframework-stubs-3.16.1/rest_framework-stubs/schemas/utils.pyifrom django.db.models import Model
from rest_framework.fields import Field
from rest_framework.views import APIView
def is_list_view(path: str, method: str, view: APIView) -> bool: ...
def get_pk_description(model: type[Model], model_field: Field) -> str: ...
0707010000004C000081A4000000000000000000000001687648C50000019B000000000000000000000000000000000000004800000000djangorestframework-stubs-3.16.1/rest_framework-stubs/schemas/views.pyifrom typing import Any
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.schemas import SchemaGenerator
from rest_framework.views import APIView
class SchemaView(APIView):
_ignore_model_permissions: bool
public: bool
schema_generator: SchemaGenerator | None
def get(self, request: Request, *args: Any, **kwargs: Any) -> Response: ...
0707010000004D000081A4000000000000000000000001687648C500003113000000000000000000000000000000000000004600000000djangorestframework-stubs-3.16.1/rest_framework-stubs/serializers.pyifrom _typeshed import Incomplete
from collections.abc import Iterable, Iterator, Mapping, MutableMapping, Sequence
from typing import Any, ClassVar, Literal, NoReturn, TypeVar
from django.db import models
from django.db.models import Manager, Model, QuerySet
from django.utils.functional import cached_property
from django_stubs_ext import StrOrPromise
from rest_framework.exceptions import APIException as APIException
from rest_framework.exceptions import AuthenticationFailed as AuthenticationFailed
from rest_framework.exceptions import ErrorDetail as ErrorDetail
from rest_framework.exceptions import MethodNotAllowed as MethodNotAllowed
from rest_framework.exceptions import NotAcceptable as NotAcceptable
from rest_framework.exceptions import NotAuthenticated as NotAuthenticated
from rest_framework.exceptions import NotFound as NotFound
from rest_framework.exceptions import ParseError as ParseError
from rest_framework.exceptions import PermissionDenied as PermissionDenied
from rest_framework.exceptions import Throttled as Throttled
from rest_framework.exceptions import UnsupportedMediaType as UnsupportedMediaType
from rest_framework.exceptions import ValidationError as ValidationError
from rest_framework.fields import BooleanField as BooleanField
from rest_framework.fields import CharField as CharField
from rest_framework.fields import ChoiceField as ChoiceField
from rest_framework.fields import CreateOnlyDefault as CreateOnlyDefault
from rest_framework.fields import CurrentUserDefault as CurrentUserDefault
from rest_framework.fields import DateField as DateField
from rest_framework.fields import DateTimeField as DateTimeField
from rest_framework.fields import DecimalField as DecimalField
from rest_framework.fields import DictField as DictField
from rest_framework.fields import DurationField as DurationField
from rest_framework.fields import EmailField as EmailField
from rest_framework.fields import Field as Field
from rest_framework.fields import FileField as FileField
from rest_framework.fields import FilePathField as FilePathField
from rest_framework.fields import FloatField as FloatField
from rest_framework.fields import HiddenField as HiddenField
from rest_framework.fields import HStoreField as HStoreField
from rest_framework.fields import ImageField as ImageField
from rest_framework.fields import IntegerField as IntegerField
from rest_framework.fields import IPAddressField as IPAddressField
from rest_framework.fields import JSONField as JSONField
from rest_framework.fields import ListField as ListField
from rest_framework.fields import ModelField as ModelField
from rest_framework.fields import MultipleChoiceField as MultipleChoiceField
from rest_framework.fields import NullBooleanField as NullBooleanField
from rest_framework.fields import ReadOnlyField as ReadOnlyField
from rest_framework.fields import RegexField as RegexField
from rest_framework.fields import SerializerMethodField as SerializerMethodField
from rest_framework.fields import SkipField as SkipField
from rest_framework.fields import SlugField as SlugField
from rest_framework.fields import TimeField as TimeField
from rest_framework.fields import URLField as URLField
from rest_framework.fields import UUIDField as UUIDField
from rest_framework.fields import _DefaultInitial
from rest_framework.fields import empty as empty
from rest_framework.relations import Hyperlink as Hyperlink
from rest_framework.relations import HyperlinkedIdentityField as HyperlinkedIdentityField
from rest_framework.relations import HyperlinkedRelatedField as HyperlinkedRelatedField
from rest_framework.relations import ManyRelatedField as ManyRelatedField
from rest_framework.relations import PrimaryKeyRelatedField as PrimaryKeyRelatedField
from rest_framework.relations import RelatedField as RelatedField
from rest_framework.relations import SlugRelatedField as SlugRelatedField
from rest_framework.relations import StringRelatedField as StringRelatedField
from rest_framework.utils.model_meta import FieldInfo, RelationInfo
from rest_framework.utils.serializer_helpers import BindingDict, BoundField, ReturnDict, ReturnList
from rest_framework.validators import BaseUniqueForValidator, UniqueTogetherValidator, Validator
from typing_extensions import Self
LIST_SERIALIZER_KWARGS: Sequence[str]
LIST_SERIALIZER_KWARGS_REMOVE: Sequence[str]
ALL_FIELDS: str
_MT = TypeVar("_MT", bound=Model) # Model Type
_IN = TypeVar("_IN") # Instance Type
class BaseSerializer(Field[Any, Any, Any, _IN]):
partial: bool
many: bool
instance: _IN | None
initial_data: Any
_context: dict[str, Any]
def __new__(cls, *args: Any, **kwargs: Any) -> Self: ...
def __class_getitem__(cls, *args: Incomplete, **kwargs: Incomplete) -> Incomplete: ...
def __init__(
self,
instance: _IN | None = ...,
data: Any = ...,
*,
partial: bool = ...,
many: bool = ...,
allow_empty: bool = ...,
context: dict[str, Any] = ...,
read_only: bool = ...,
write_only: bool = ...,
required: bool | None = None,
default: Any = ...,
initial: Any = ...,
source: str | None = None,
label: StrOrPromise | None = None,
help_text: StrOrPromise | None = None,
style: dict[str, Any] | None = None,
error_messages: dict[str, StrOrPromise] | None = None,
validators: Sequence[Validator[Any]] | None = ...,
allow_null: bool = ...,
) -> None: ...
@classmethod
def many_init(cls, *args: Any, **kwargs: Any) -> BaseSerializer: ...
def is_valid(self, *, raise_exception: bool = ...) -> bool: ...
@property
def data(self) -> Any: ...
@property
def errors(self) -> Iterable[Any]: ...
@property
def validated_data(self) -> Any: ...
def update(self, instance: _IN, validated_data: Any) -> _IN: ...
def create(self, validated_data: Any) -> _IN: ...
def save(self, **kwargs: Any) -> _IN: ...
def to_representation(self, instance: _IN) -> Any: ...
class SerializerMetaclass(type):
def __new__(cls, name: Any, bases: Any, attrs: Any) -> Incomplete: ...
@classmethod
def _get_declared_fields(cls, bases: Sequence[type], attrs: dict[str, Any]) -> dict[str, Field]: ...
def as_serializer_error(exc: Exception) -> dict[str, list[ErrorDetail]]: ...
class Serializer(BaseSerializer[_IN], metaclass=SerializerMetaclass):
_declared_fields: dict[str, Field]
default_error_messages: ClassVar[dict[str, StrOrPromise]]
def get_initial(self) -> Any: ...
def set_value(self, dictionary: MutableMapping[str, Any], keys: Sequence[str], value: Any) -> None: ...
@cached_property
def fields(self) -> BindingDict: ...
def get_fields(self) -> dict[str, Field]: ...
def to_representation(self, instance: _IN) -> dict[str, Any]: ...
def validate(self, attrs: Any) -> Any: ...
def __iter__(self) -> Iterator[BoundField]: ...
def __getitem__(self, key: str) -> BoundField: ...
def _read_only_defaults(self) -> dict[str, Any]: ...
@property
def _writable_fields(self) -> list[Field]: ...
@property
def _readable_fields(self) -> list[Field]: ...
@property
def data(self) -> ReturnDict: ...
@property
def errors(self) -> ReturnDict: ...
class ListSerializer(BaseSerializer[_IN]):
child: Field | BaseSerializer | None
many: bool
default_error_messages: ClassVar[dict[str, StrOrPromise]]
allow_empty: bool | None
def __init__(
self,
instance: _IN | None = ...,
data: Any = ...,
partial: bool = ...,
context: dict[str, Any] = ...,
allow_empty: bool = ...,
child: Field | BaseSerializer | None = ...,
read_only: bool = ...,
write_only: bool = ...,
required: bool | None = None,
default: Any = ...,
initial: Any = ...,
source: str | None = None,
label: StrOrPromise | None = None,
help_text: StrOrPromise | None = None,
style: dict[str, Any] | None = None,
error_messages: dict[str, StrOrPromise] | None = None,
validators: Sequence[Validator[list[Any]]] | None = ...,
allow_null: bool = ...,
min_length: int | None = ...,
max_length: int | None = ...,
) -> None: ...
def run_child_validation(self, data: Any) -> Any: ...
def to_representation(self, data: Manager[Any] | Iterable[Any]) -> list[Any]: ... # type: ignore[override]
def get_initial(self) -> list[Mapping[Any, Any]]: ...
def validate(self, attrs: Any) -> Any: ...
@property
def data(self) -> ReturnList: ...
@property
def errors(self) -> ReturnList: ...
def raise_errors_on_nested_writes(method_name: str, serializer: BaseSerializer, validated_data: Any) -> None: ...
class ModelSerializer(Serializer[_MT]):
serializer_field_mapping: dict[type[models.Field], type[Field]]
serializer_related_field: type[RelatedField]
serializer_related_to_field: type[RelatedField]
serializer_url_field: type[RelatedField]
serializer_choice_field: type[Field]
url_field_name: str | None
instance: _MT | Sequence[_MT] | None # type: ignore[assignment]
class Meta:
model: type[_MT] # type: ignore
fields: Sequence[str] | Literal["__all__"]
read_only_fields: Sequence[str] | None
exclude: Sequence[str] | None
depth: int | None
extra_kwargs: dict[str, dict[str, Any]]
def __init__(
self,
instance: None | _MT | Sequence[_MT] | QuerySet[_MT] | Manager[_MT] = ...,
data: Any = ...,
*,
partial: bool = ...,
many: bool = ...,
context: dict[str, Any] = ...,
read_only: bool = ...,
write_only: bool = ...,
required: bool | None = None,
default: _DefaultInitial[_MT | Sequence[_MT]] = ...,
initial: _DefaultInitial[_MT | Sequence[_MT]] = ...,
source: str | None = None,
label: StrOrPromise | None = None,
help_text: StrOrPromise | None = None,
style: dict[str, Any] | None = None,
error_messages: dict[str, StrOrPromise] | None = None,
validators: Sequence[Validator[_MT]] | None = ...,
allow_null: bool = ...,
allow_empty: bool = ...,
) -> None: ...
def update(self, instance: _MT, validated_data: Any) -> _MT: ...
def create(self, validated_data: Any) -> _MT: ...
def save(self, **kwargs: Any) -> _MT: ...
def get_field_names(self, declared_fields: Mapping[str, Field], info: FieldInfo) -> list[str]: ...
def get_default_field_names(self, declared_fields: Mapping[str, Field], model_info: FieldInfo) -> list[str]: ...
def build_field(
self, field_name: str, info: FieldInfo, model_class: type[_MT], nested_depth: int
) -> tuple[type[Field], dict[str, Any]]: ...
def build_standard_field(
self, field_name: str, model_field: models.Field
) -> tuple[type[Field], dict[str, Any]]: ...
def build_relational_field(
self, field_name: str, relation_info: RelationInfo
) -> tuple[type[Field], dict[str, Any]]: ...
def build_nested_field(
self, field_name: str, relation_info: RelationInfo, nested_depth: int
) -> tuple[type[Field], dict[str, Any]]: ...
def build_property_field(self, field_name: str, model_class: type[_MT]) -> tuple[type[Field], dict[str, Any]]: ...
def build_url_field(self, field_name: str, model_class: type[_MT]) -> tuple[type[Field], dict[str, Any]]: ...
def build_unknown_field(self, field_name: str, model_class: type[_MT]) -> NoReturn: ...
def include_extra_kwargs(
self, kwargs: MutableMapping[str, Any], extra_kwargs: MutableMapping[str, Any]
) -> MutableMapping[str, Any]: ...
def get_extra_kwargs(self) -> dict[str, Any]: ...
def get_unique_together_constraints(self, model: _MT) -> Iterator[tuple[set[tuple[str, ...]], Manager[_MT]]]: ...
def get_uniqueness_extra_kwargs(
self, field_names: Iterable[str], declared_fields: Mapping[str, Field], extra_kwargs: dict[str, Any]
) -> tuple[dict[str, Any], dict[str, HiddenField]]: ...
def _get_model_fields(
self, field_names: Iterable[str], declared_fields: Mapping[str, Field], extra_kwargs: MutableMapping[str, Any]
) -> dict[str, models.Field]: ...
def get_unique_together_validators(self) -> list[UniqueTogetherValidator]: ...
def get_unique_for_date_validators(self) -> list[BaseUniqueForValidator]: ...
class HyperlinkedModelSerializer(ModelSerializer[_MT]): ...
0707010000004E000081A4000000000000000000000001687648C50000103E000000000000000000000000000000000000004300000000djangorestframework-stubs-3.16.1/rest_framework-stubs/settings.pyifrom collections.abc import Callable, Mapping, Sequence
from typing import Any
from typing_extensions import TypedDict
class DefaultsSettings(TypedDict, total=False):
DEFAULT_RENDERER_CLASSES: Sequence[str]
DEFAULT_PARSER_CLASSES: Sequence[str]
DEFAULT_AUTHENTICATION_CLASSES: Sequence[str]
DEFAULT_PERMISSION_CLASSES: Sequence[str]
DEFAULT_THROTTLE_CLASSES: Sequence[str]
DEFAULT_CONTENT_NEGOTIATION_CLASS: str
DEFAULT_METADATA_CLASS: str
DEFAULT_VERSIONING_CLASS: str | None
DEFAULT_PAGINATION_CLASS: str | None
DEFAULT_FILTER_BACKENDS: Sequence[str]
DEFAULT_SCHEMA_CLASS: str
DEFAULT_THROTTLE_RATES: dict[str, float | int | None]
NUM_PROXIES: int | None
PAGE_SIZE: int | None
SEARCH_PARAM: str
ORDERING_PARAM: str
DEFAULT_VERSION: str | None
ALLOWED_VERSIONS: str | None
VERSION_PARAM: str
UNAUTHENTICATED_USER: str
UNAUTHENTICATED_TOKEN: str | None
VIEW_NAME_FUNCTION: str
VIEW_DESCRIPTION_FUNCTION: str
EXCEPTION_HANDLER: str | Callable[[Any, Any], Any]
NON_FIELD_ERRORS_KEY: str
TEST_REQUEST_RENDERER_CLASSES: Sequence[str]
TEST_REQUEST_DEFAULT_FORMAT: str
URL_FORMAT_OVERRIDE: str
FORMAT_SUFFIX_KWARG: str
URL_FIELD_NAME: str
DATE_FORMAT: str
DATE_INPUT_FORMATS: Sequence[str]
DATETIME_FORMAT: str
DATETIME_INPUT_FORMATS: Sequence[str]
TIME_FORMAT: str
TIME_INPUT_FORMATS: Sequence[str]
UNICODE_JSON: bool
COMPACT_JSON: bool
STRICT_JSON: bool
COERCE_DECIMAL_TO_STRING: bool
UPLOADED_FILES_USE_URL: bool
HTML_SELECT_CUTOFF: int
HTML_SELECT_CUTOFF_TEXT: str
SCHEMA_COERCE_PATH_PK: bool
SCHEMA_COERCE_METHOD_NAMES: dict[str, str]
DEFAULTS: DefaultsSettings
IMPORT_STRINGS: Sequence[str]
REMOVED_SETTINGS: Sequence[str]
def perform_import(val: Any | None, setting_name: str) -> Any | None: ...
def import_from_string(val: Any | None, setting_name: str) -> Any: ...
class APISettings:
defaults: DefaultsSettings
import_strings: Sequence[str]
def __init__(
self,
user_settings: DefaultsSettings | None = ...,
defaults: DefaultsSettings | None = ...,
import_strings: Sequence[str] | None = ...,
) -> None: ...
@property
def user_settings(self) -> Mapping[str, Any]: ...
def __getattr__(self, attr: str) -> Any: ...
def __check_user_settings(self, user_settings: Mapping[str, Any]) -> Mapping[str, Any]: ...
def reload(self) -> None: ...
class _Settings(APISettings):
DEFAULT_RENDERER_CLASSES: Sequence[str]
DEFAULT_PARSER_CLASSES: Sequence[str]
DEFAULT_AUTHENTICATION_CLASSES: Sequence[str]
DEFAULT_PERMISSION_CLASSES: Sequence[str]
DEFAULT_THROTTLE_CLASSES: Sequence[str]
DEFAULT_CONTENT_NEGOTIATION_CLASS: str
DEFAULT_METADATA_CLASS: str
DEFAULT_VERSIONING_CLASS: str | None
DEFAULT_PAGINATION_CLASS: str | None
DEFAULT_FILTER_BACKENDS: Sequence[str]
DEFAULT_SCHEMA_CLASS: str
DEFAULT_THROTTLE_RATES: dict[str, float | int | None]
NUM_PROXIES: int | None
PAGE_SIZE: int | None
SEARCH_PARAM: str
ORDERING_PARAM: str
DEFAULT_VERSION: str | None
ALLOWED_VERSIONS: str | None
VERSION_PARAM: str
UNAUTHENTICATED_USER: str
UNAUTHENTICATED_TOKEN: str | None
VIEW_NAME_FUNCTION: str
VIEW_DESCRIPTION_FUNCTION: str
EXCEPTION_HANDLER: str | Callable[[Any, Any], Any]
NON_FIELD_ERRORS_KEY: str
TEST_REQUEST_RENDERER_CLASSES: Sequence[str]
TEST_REQUEST_DEFAULT_FORMAT: str
URL_FORMAT_OVERRIDE: str
FORMAT_SUFFIX_KWARG: str
URL_FIELD_NAME: str
DATE_FORMAT: str
DATE_INPUT_FORMATS: Sequence[str]
DATETIME_FORMAT: str
DATETIME_INPUT_FORMATS: Sequence[str]
TIME_FORMAT: str
TIME_INPUT_FORMATS: Sequence[str]
UNICODE_JSON: bool
COMPACT_JSON: bool
STRICT_JSON: bool
COERCE_DECIMAL_TO_STRING: bool
UPLOADED_FILES_USE_URL: bool
HTML_SELECT_CUTOFF: int
HTML_SELECT_CUTOFF_TEXT: str
SCHEMA_COERCE_PATH_PK: bool
SCHEMA_COERCE_METHOD_NAMES: dict[str, str]
api_settings: _Settings
def reload_api_settings(*args: Any, **kwargs: Any) -> None: ...
0707010000004F000081A4000000000000000000000001687648C500000AD8000000000000000000000000000000000000004100000000djangorestframework-stubs-3.16.1/rest_framework-stubs/status.pyifrom typing import Literal
def is_informational(code: int) -> bool: ...
def is_success(code: int) -> bool: ...
def is_redirect(code: int) -> bool: ...
def is_client_error(code: int) -> bool: ...
def is_server_error(code: int) -> bool: ...
HTTP_100_CONTINUE: Literal[100]
HTTP_101_SWITCHING_PROTOCOLS: Literal[101]
HTTP_102_PROCESSING: Literal[102]
HTTP_103_EARLY_HINTS: Literal[103]
HTTP_200_OK: Literal[200]
HTTP_201_CREATED: Literal[201]
HTTP_202_ACCEPTED: Literal[202]
HTTP_203_NON_AUTHORITATIVE_INFORMATION: Literal[203]
HTTP_204_NO_CONTENT: Literal[204]
HTTP_205_RESET_CONTENT: Literal[205]
HTTP_206_PARTIAL_CONTENT: Literal[206]
HTTP_207_MULTI_STATUS: Literal[207]
HTTP_208_ALREADY_REPORTED: Literal[208]
HTTP_226_IM_USED: Literal[226]
HTTP_300_MULTIPLE_CHOICES: Literal[300]
HTTP_301_MOVED_PERMANENTLY: Literal[301]
HTTP_302_FOUND: Literal[302]
HTTP_303_SEE_OTHER: Literal[303]
HTTP_304_NOT_MODIFIED: Literal[304]
HTTP_305_USE_PROXY: Literal[305]
HTTP_306_RESERVED: Literal[306]
HTTP_307_TEMPORARY_REDIRECT: Literal[307]
HTTP_308_PERMANENT_REDIRECT: Literal[308]
HTTP_400_BAD_REQUEST: Literal[400]
HTTP_401_UNAUTHORIZED: Literal[401]
HTTP_402_PAYMENT_REQUIRED: Literal[402]
HTTP_403_FORBIDDEN: Literal[403]
HTTP_404_NOT_FOUND: Literal[404]
HTTP_405_METHOD_NOT_ALLOWED: Literal[405]
HTTP_406_NOT_ACCEPTABLE: Literal[406]
HTTP_407_PROXY_AUTHENTICATION_REQUIRED: Literal[407]
HTTP_408_REQUEST_TIMEOUT: Literal[408]
HTTP_409_CONFLICT: Literal[409]
HTTP_410_GONE: Literal[410]
HTTP_411_LENGTH_REQUIRED: Literal[411]
HTTP_412_PRECONDITION_FAILED: Literal[412]
HTTP_413_REQUEST_ENTITY_TOO_LARGE: Literal[413]
HTTP_414_REQUEST_URI_TOO_LONG: Literal[414]
HTTP_415_UNSUPPORTED_MEDIA_TYPE: Literal[415]
HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE: Literal[416]
HTTP_417_EXPECTATION_FAILED: Literal[417]
HTTP_418_IM_A_TEAPOT: Literal[418]
HTTP_421_MISDIRECTED_REQUEST: Literal[421]
HTTP_422_UNPROCESSABLE_ENTITY: Literal[422]
HTTP_423_LOCKED: Literal[423]
HTTP_424_FAILED_DEPENDENCY: Literal[424]
HTTP_425_TOO_EARLY: Literal[425]
HTTP_426_UPGRADE_REQUIRED: Literal[426]
HTTP_428_PRECONDITION_REQUIRED: Literal[428]
HTTP_429_TOO_MANY_REQUESTS: Literal[429]
HTTP_431_REQUEST_HEADER_FIELDS_TOO_LARGE: Literal[431]
HTTP_451_UNAVAILABLE_FOR_LEGAL_REASONS: Literal[451]
HTTP_500_INTERNAL_SERVER_ERROR: Literal[500]
HTTP_501_NOT_IMPLEMENTED: Literal[501]
HTTP_502_BAD_GATEWAY: Literal[502]
HTTP_503_SERVICE_UNAVAILABLE: Literal[503]
HTTP_504_GATEWAY_TIMEOUT: Literal[504]
HTTP_505_HTTP_VERSION_NOT_SUPPORTED: Literal[505]
HTTP_506_VARIANT_ALSO_NEGOTIATES: Literal[506]
HTTP_507_INSUFFICIENT_STORAGE: Literal[507]
HTTP_508_LOOP_DETECTED: Literal[508]
HTTP_509_BANDWIDTH_LIMIT_EXCEEDED: Literal[509]
HTTP_510_NOT_EXTENDED: Literal[510]
HTTP_511_NETWORK_AUTHENTICATION_REQUIRED: Literal[511]
07070100000050000041ED000000000000000000000002687648C500000000000000000000000000000000000000000000004300000000djangorestframework-stubs-3.16.1/rest_framework-stubs/templatetags07070100000051000081A4000000000000000000000001687648C500000000000000000000000000000000000000000000005000000000djangorestframework-stubs-3.16.1/rest_framework-stubs/templatetags/__init__.pyi07070100000052000081A4000000000000000000000001687648C5000007D8000000000000000000000000000000000000005600000000djangorestframework-stubs-3.16.1/rest_framework-stubs/templatetags/rest_framework.pyifrom _typeshed import Incomplete
from typing import Any
from django import template
from django.contrib.auth.base_user import AbstractBaseUser
from django.contrib.auth.models import AnonymousUser
from rest_framework.request import Request
register: Any
class_re: Any
def highlight_code(parser: Any, token: Any) -> Incomplete: ...
class CodeNode(template.Node):
style: str
lang: Any
nodelist: Any
def __init__(self, lang: Any, code: Any) -> None: ...
def render(self, context: Any) -> Incomplete: ...
def with_location(fields: Any, location: Any) -> Incomplete: ...
def form_for_link(link: Any) -> Incomplete: ...
def render_markdown(markdown_text: Any) -> Incomplete: ...
def get_pagination_html(pager: Any) -> Incomplete: ...
def render_form(serializer: Any, template_pack: Any | None = ...) -> Incomplete: ...
def render_field(field: Any, style: Any) -> Incomplete: ...
def optional_login(request: Request) -> Incomplete: ...
def optional_docs_login(request: Request) -> Incomplete: ...
def optional_logout(request: Request, user: AnonymousUser | AbstractBaseUser, csrf_token: str) -> Incomplete: ...
def add_query_param(request: Request, key: str, val: Any) -> Incomplete: ...
def as_string(value: Any) -> str: ...
def as_list_of_strings(value: Any) -> list[str]: ...
def add_class(value: Any, css_class: Any) -> Incomplete: ...
def format_value(value: Any) -> Incomplete: ...
def items(value: Any) -> Incomplete: ...
def data(value: Any) -> Incomplete: ...
def schema_links(section: Any, sec_key: Any | None = ...) -> Incomplete: ...
def add_nested_class(value: Any) -> Incomplete: ...
TRAILING_PUNCTUATION: Any
WRAPPING_PUNCTUATION: Any
word_split_re: Any
simple_url_re: Any
simple_url_2_re: Any
simple_email_re: Any
def smart_urlquote_wrapper(matched_url: Any) -> Incomplete: ...
def urlize_quoted_links(
text: Any, trim_url_limit: Any | None = ..., nofollow: bool = ..., autoescape: bool = ...
) -> Incomplete: ...
def break_long_headers(header: Any) -> Incomplete: ...
07070100000053000081A4000000000000000000000001687648C5000017CE000000000000000000000000000000000000003F00000000djangorestframework-stubs-3.16.1/rest_framework-stubs/test.pyifrom _typeshed import Incomplete
from collections.abc import Iterable, Mapping
from typing import Any, TypeAlias
import coreapi # type: ignore[import-untyped]
import requests
import urllib3
from django.contrib.auth.base_user import AbstractBaseUser
from django.contrib.auth.models import AnonymousUser
from django.http import HttpRequest
from django.test import testcases
from django.test.client import Client as DjangoClient
from django.test.client import ClientHandler
from django.test.client import RequestFactory as DjangoRequestFactory
from rest_framework.authtoken.models import Token
from rest_framework.request import Request
from rest_framework.response import _MonkeyPatchedResponse
_GetDataType: TypeAlias = (
Mapping[str, str | bytes | float | Iterable[str | bytes | float]]
| Iterable[tuple[str, str | bytes | float | Iterable[str | bytes | float]]]
| None
)
def force_authenticate(
request: HttpRequest, user: AnonymousUser | AbstractBaseUser | None = ..., token: Token | None = ...
) -> None: ...
class HeaderDict(urllib3._collections.HTTPHeaderDict):
def get_all(self, key: Any, default: Any) -> Incomplete: ...
class MockOriginalResponse:
msg: Any
closed: bool
def __init__(self, headers: Any) -> None: ...
def isclosed(self) -> bool: ...
def close(self) -> None: ...
class DjangoTestAdapter(requests.adapters.HTTPAdapter):
app: Any
factory: Any
def __init__(self) -> None: ...
def get_environ(self, request: Request) -> Incomplete: ...
def send(self, request: Request, *args: Any, **kwargs: Any) -> requests.Response: ... # type: ignore[override]
def close(self) -> None: ...
class RequestsClient(requests.Session): ...
class CoreAPIClient(coreapi.Client):
def __init__(self, *args: Any, **kwargs: Any) -> None: ...
@property
def session(self) -> Incomplete: ...
class APIRequestFactory(DjangoRequestFactory):
renderer_classes_list: Any
default_format: Any
enforce_csrf_checks: Any
renderer_classes: Any
def __init__(self, enforce_csrf_checks: bool = ..., **defaults: Any) -> None: ...
def request(self, **kwargs: Any) -> Request: ... # type: ignore[override]
def get(self, path: str, data: _GetDataType = ..., **extra: Any) -> Request: ... # type: ignore[override]
def post( # type: ignore[override]
self, path: str, data: Any | None = ..., format: str | None = ..., content_type: str | None = ..., **extra: Any
) -> Request: ...
def put( # type: ignore[override]
self, path: str, data: Any | None = ..., format: str | None = ..., content_type: str | None = ..., **extra: Any
) -> Request: ...
def patch( # type: ignore[override]
self, path: str, data: Any | None = ..., format: str | None = ..., content_type: str | None = ..., **extra: Any
) -> Request: ...
def delete( # type: ignore[override]
self, path: str, data: Any | None = ..., format: str | None = ..., content_type: str | None = ..., **extra: Any
) -> Request: ...
def options( # type: ignore[override]
self,
path: str,
data: dict[str, str] | str | None = ...,
format: str | None = ...,
content_type: Any | None = ...,
**extra: Any,
) -> Request: ...
def generic( # type: ignore[override]
self, method: str, path: str, data: str = ..., content_type: str = ..., secure: bool = ..., **extra: Any
) -> Request: ...
class ForceAuthClientHandler(ClientHandler):
def __init__(self, *args: Any, **kwargs: Any) -> None: ...
def get_response(self, request: Request) -> _MonkeyPatchedResponse: ... # type: ignore[override]
class APIClient(APIRequestFactory, DjangoClient):
def credentials(self, **kwargs: Any) -> None: ...
def force_authenticate(
self, user: AnonymousUser | AbstractBaseUser | None = ..., token: Token | None = ...
) -> None: ...
def request(self, **kwargs: Any) -> _MonkeyPatchedResponse: ... # type: ignore[override]
def get(self, path: str, data: _GetDataType = ..., follow: bool = ..., **extra: Any) -> _MonkeyPatchedResponse: ... # type: ignore[override]
def post( # type: ignore[override]
self,
path: str,
data: Any | None = ...,
format: str | None = ...,
content_type: str | None = ...,
follow: bool = ...,
**extra: Any,
) -> _MonkeyPatchedResponse: ...
def put( # type: ignore[override]
self,
path: str,
data: Any | None = ...,
format: str | None = ...,
content_type: str | None = ...,
follow: bool = ...,
**extra: Any,
) -> _MonkeyPatchedResponse: ...
def patch( # type: ignore[override]
self,
path: str,
data: Any | None = ...,
format: str | None = ...,
content_type: str | None = ...,
follow: bool = ...,
**extra: Any,
) -> _MonkeyPatchedResponse: ...
def delete( # type: ignore[override]
self,
path: str,
data: Any | None = ...,
format: str | None = ...,
content_type: str | None = ...,
follow: bool = ...,
**extra: Any,
) -> _MonkeyPatchedResponse: ...
def options( # type: ignore[override]
self,
path: str,
data: dict[str, str] | str = ...,
format: str | None = ...,
content_type: Any | None = ...,
follow: bool = ...,
**extra: Any,
) -> _MonkeyPatchedResponse: ...
def logout(self) -> None: ...
class APITransactionTestCase(testcases.TransactionTestCase):
client_class: type[APIClient]
client: APIClient
class APITestCase(testcases.TestCase):
client_class: type[APIClient]
client: APIClient
class APISimpleTestCase(testcases.SimpleTestCase):
client_class: type[APIClient]
client: APIClient
class APILiveServerTestCase(testcases.LiveServerTestCase):
client_class: type[APIClient]
client: APIClient
def cleanup_url_patterns(cls: type[URLPatternsTestCase]) -> None: ...
class URLPatternsTestCase(testcases.SimpleTestCase): ...
07070100000054000081A4000000000000000000000001687648C500000472000000000000000000000000000000000000004500000000djangorestframework-stubs-3.16.1/rest_framework-stubs/throttling.pyifrom collections.abc import Callable
from typing import Any
from django.core.cache.backends.base import BaseCache
from rest_framework.request import Request
from rest_framework.views import APIView
class BaseThrottle:
def allow_request(self, request: Request, view: APIView) -> bool: ...
def get_ident(self, request: Request) -> str: ...
def wait(self) -> float | None: ...
class SimpleRateThrottle(BaseThrottle):
cache: BaseCache
cache_format: str
history: list[Any]
key: str | None
now: float
rate: str | None
scope: str | None
THROTTLE_RATES: dict[str, str | None]
timer: Callable[..., float]
def __init__(self) -> None: ...
def get_cache_key(self, request: Request, view: APIView) -> str | None: ...
def get_rate(self) -> str | None: ...
def parse_rate(self, rate: str | None) -> tuple[int | None, int | None]: ...
def throttle_failure(self) -> bool: ...
def throttle_success(self) -> bool: ...
class AnonRateThrottle(SimpleRateThrottle): ...
class UserRateThrottle(SimpleRateThrottle): ...
class ScopedRateThrottle(SimpleRateThrottle):
scope_attr: str
07070100000055000081A4000000000000000000000001687648C50000022A000000000000000000000000000000000000004600000000djangorestframework-stubs-3.16.1/rest_framework-stubs/urlpatterns.pyifrom collections.abc import Iterable, Sequence
from typing import TypeAlias
from django.urls.resolvers import URLPattern, URLResolver
_AnyURL: TypeAlias = URLPattern | URLResolver
def apply_suffix_patterns(
urlpatterns: Iterable[_AnyURL],
suffix_pattern: str,
suffix_required: bool,
suffix_route: str | None = ...,
) -> list[URLResolver | URLPattern]: ...
def format_suffix_patterns(
urlpatterns: Iterable[_AnyURL],
suffix_required: bool = ...,
allowed: Sequence[str] | None = ...,
) -> list[URLResolver | URLPattern]: ...
07070100000056000081A4000000000000000000000001687648C500000059000000000000000000000000000000000000003F00000000djangorestframework-stubs-3.16.1/rest_framework-stubs/urls.pyifrom rest_framework.urlpatterns import _AnyURL
app_name: str
urlpatterns: list[_AnyURL]
07070100000057000041ED000000000000000000000002687648C500000000000000000000000000000000000000000000003C00000000djangorestframework-stubs-3.16.1/rest_framework-stubs/utils07070100000058000081A4000000000000000000000001687648C500000000000000000000000000000000000000000000004900000000djangorestframework-stubs-3.16.1/rest_framework-stubs/utils/__init__.pyi07070100000059000081A4000000000000000000000001687648C500000085000000000000000000000000000000000000004C00000000djangorestframework-stubs-3.16.1/rest_framework-stubs/utils/breadcrumbs.pyifrom _typeshed import Incomplete
from typing import Any
def get_breadcrumbs(url: Any, request: Any | None = ...) -> Incomplete: ...
0707010000005A000081A4000000000000000000000001687648C5000000EF000000000000000000000000000000000000004900000000djangorestframework-stubs-3.16.1/rest_framework-stubs/utils/encoders.pyiimport datetime
import json
from yaml import Dumper, ScalarNode
class JSONEncoder(json.JSONEncoder): ...
class CustomScalar:
@classmethod
def represent_timedelta(cls, dumper: Dumper, data: datetime.timedelta) -> ScalarNode: ...
0707010000005B000081A4000000000000000000000001687648C5000004C3000000000000000000000000000000000000004E00000000djangorestframework-stubs-3.16.1/rest_framework-stubs/utils/field_mapping.pyifrom _typeshed import Incomplete
from collections.abc import Iterator, MutableMapping, Sequence
from typing import Any, Generic, TypeVar
from django.db import models
from rest_framework.validators import UniqueValidator
NUMERIC_FIELD_TYPES: Sequence[type[models.Field]]
_K = TypeVar("_K", bound=type)
_V = TypeVar("_V")
class ClassLookupDict(Generic[_K, _V]):
mapping: MutableMapping[type[_K], _V]
def __init__(self, mapping: MutableMapping[type[_K], _V]) -> None: ...
def __getitem__(self, key: _K) -> _V: ...
def __setitem__(self, key: _K, value: _V) -> None: ...
def needs_label(model_field: models.Field, field_name: str) -> bool: ...
def get_detail_view_name(model: models.Model) -> str: ...
def get_unique_validators(field_name: str, model_field: models.Field) -> Iterator[UniqueValidator]: ...
def get_field_kwargs(field_name: str, model_field: models.Field) -> dict[str, Any]: ...
def get_relation_kwargs(field_name: str, relation_info: Incomplete) -> dict[str, Any]: ...
def get_nested_relation_kwargs(relation_info: Incomplete) -> dict[str, Any]: ...
def get_url_kwargs(model_field: models.Model) -> dict[str, Any]: ...
def get_unique_error_message(model_field: models.Field) -> str: ...
0707010000005C000081A4000000000000000000000001687648C5000001F2000000000000000000000000000000000000004B00000000djangorestframework-stubs-3.16.1/rest_framework-stubs/utils/formatting.pyifrom _typeshed import Incomplete
from typing import Any
def remove_trailing_string(content: str, trailing: str) -> str: ...
def dedent(content: str | bytes) -> str: ...
def camelcase_to_spaces(content: str) -> str: ...
def markup_description(description: str) -> str: ...
class lazy_format:
format_string: str
result: str
args: Any
kwargs: Any
def __init__(self, format_string: str, *args: Any, **kwargs: Any) -> None: ...
def __mod__(self, value: Incomplete) -> str: ...
0707010000005D000081A4000000000000000000000001687648C500000120000000000000000000000000000000000000004500000000djangorestframework-stubs-3.16.1/rest_framework-stubs/utils/html.pyifrom _typeshed import Incomplete
from typing import Any
def is_html_input(dictionary: Any) -> Incomplete: ...
def parse_html_list(dictionary: Any, prefix: str = ..., default: Any | None = ...) -> Incomplete: ...
def parse_html_dict(dictionary: Any, prefix: str = ...) -> Incomplete: ...
0707010000005E000081A4000000000000000000000001687648C500000110000000000000000000000000000000000000005200000000djangorestframework-stubs-3.16.1/rest_framework-stubs/utils/humanize_datetime.pyifrom _typeshed import Incomplete
from typing import Any
def datetime_formats(formats: Any) -> Incomplete: ...
def date_formats(formats: Any) -> Incomplete: ...
def time_formats(formats: Any) -> Incomplete: ...
def humanize_strptime(format_string: Any) -> Incomplete: ...
0707010000005F000081A4000000000000000000000001687648C5000006DD000000000000000000000000000000000000004500000000djangorestframework-stubs-3.16.1/rest_framework-stubs/utils/json.pyifrom collections.abc import Callable
from json import JSONDecoder, JSONEncoder
from typing import IO, Any, NoReturn
def strict_constant(o: Any) -> NoReturn: ...
def dump(
obj: Any,
fp: IO[str],
*,
skipkeys: bool = False,
ensure_ascii: bool = True,
check_circular: bool = True,
allow_nan: bool = True,
cls: type[JSONEncoder] | None = None,
indent: int | str | None = None,
separators: tuple[str, str] | None = None,
default: Callable[[Any], Any] | None = None,
sort_keys: bool = False,
**kw: Any,
) -> None: ...
def dumps(
obj: Any,
*,
skipkeys: bool = False,
ensure_ascii: bool = True,
check_circular: bool = True,
allow_nan: bool = True,
cls: type[JSONEncoder] | None = None,
indent: int | str | None = None,
separators: tuple[str, str] | None = None,
default: Callable[[Any], Any] | None = None,
sort_keys: bool = False,
**kw: Any,
) -> str: ...
def load(
fp: IO[str],
*,
cls: type[JSONDecoder] | None = None,
object_hook: Callable[[dict[str, Any]], Any] | None = None,
parse_float: Callable[[str], Any] | None = None,
parse_int: Callable[[str], Any] | None = None,
parse_constant: Callable[[str], Any] | None = None,
object_pairs_hook: Callable[[list[tuple[str, Any]]], Any] | None = None,
**kw: Any,
) -> Any: ...
def loads(
s: str,
*,
cls: type[JSONDecoder] | None = None,
object_hook: Callable[[dict[str, Any]], Any] | None = None,
parse_float: Callable[[str], Any] | None = None,
parse_int: Callable[[str], Any] | None = None,
parse_constant: Callable[[str], Any] | None = None,
object_pairs_hook: Callable[[list[tuple[str, Any]]], Any] | None = None,
**kw: Any,
) -> Any: ...
07070100000060000081A4000000000000000000000001687648C50000017E000000000000000000000000000000000000004B00000000djangorestframework-stubs-3.16.1/rest_framework-stubs/utils/mediatypes.pyifrom _typeshed import Incomplete
from typing import Any
def media_type_matches(lhs: Any, rhs: Any) -> Incomplete: ...
def order_by_precedence(media_type_lst: Any) -> Incomplete: ...
class _MediaType:
orig: Any
def __init__(self, media_type_str: Any) -> None: ...
def match(self, other: Any) -> Incomplete: ...
@property
def precedence(self) -> Incomplete: ...
07070100000061000081A4000000000000000000000001687648C5000002BF000000000000000000000000000000000000004B00000000djangorestframework-stubs-3.16.1/rest_framework-stubs/utils/model_meta.pyifrom typing import NamedTuple
from django.db.models import Model
from django.db.models.fields import Field
from django.db.models.fields.related import RelatedField
class RelationInfo(NamedTuple):
model_field: RelatedField | None
related_model: type[Model]
to_many: bool
to_field: str
has_through_model: bool
reverse: bool
class FieldInfo(NamedTuple):
pk: Field
fields: dict[str, Field]
forward_relations: dict[str, RelationInfo]
reverse_relations: dict[str, RelationInfo]
fields_and_pk: dict[str, Field]
relations: dict[str, RelationInfo]
def get_field_info(model: type[Model]) -> FieldInfo: ...
def is_abstract_model(model: type[Model]) -> bool: ...
07070100000062000081A4000000000000000000000001687648C50000013B000000000000000000000000000000000000004F00000000djangorestframework-stubs-3.16.1/rest_framework-stubs/utils/representation.pyifrom typing import Any
def manager_repr(value: Any) -> str: ...
def smart_repr(value: Any) -> str: ...
def field_repr(field: Any, force_many: bool = ...) -> str: ...
def serializer_repr(serializer: Any, indent: Any, force_many: Any | None = ...) -> str: ...
def list_repr(serializer: Any, indent: Any) -> str: ...
07070100000063000081A4000000000000000000000001687648C500000DF0000000000000000000000000000000000000005300000000djangorestframework-stubs-3.16.1/rest_framework-stubs/utils/serializer_helpers.pyifrom _typeshed import SupportsKeysAndGetItem
from collections.abc import Iterable, Iterator, MutableMapping
from typing import Any, Generic, TypeVar, overload
from rest_framework.exceptions import ErrorDetail
from rest_framework.fields import Field
from rest_framework.serializers import BaseSerializer
_T = TypeVar("_T")
_VT = TypeVar("_VT")
_KT = TypeVar("_KT")
class ReturnDict(dict[_KT, _VT], Generic[_KT, _VT]):
serializer: BaseSerializer
# Copied from https://github.com/python/typeshed/blob/main/stdlib/builtins.pyi `class dict`
@overload
def __init__(self, *, serializer: BaseSerializer) -> None: ...
@overload
def __init__(self: ReturnDict[str, _VT], *, serializer: BaseSerializer, **kwargs: _VT) -> None: ...
@overload
def __init__(self, map: SupportsKeysAndGetItem[_KT, _VT], /, *, serializer: BaseSerializer) -> None: ...
@overload
def __init__(
self: ReturnDict[str, _VT],
map: SupportsKeysAndGetItem[str, _VT],
/,
*,
serializer: BaseSerializer,
**kwargs: _VT,
) -> None: ...
@overload
def __init__(self, iterable: Iterable[tuple[_KT, _VT]], /, *, serializer: BaseSerializer) -> None: ...
@overload
def __init__(
self: ReturnDict[str, _VT], iterable: Iterable[tuple[str, _VT]], /, *, serializer: BaseSerializer, **kwargs: _VT
) -> None: ...
# Next two overloads are for dict(string.split(sep) for string in iterable)
# Cannot be Iterable[Sequence[_T]] or otherwise dict(["foo", "bar", "baz"]) is not an error
@overload
def __init__(
self: ReturnDict[str, str], iterable: Iterable[list[str]], /, *, serializer: BaseSerializer
) -> None: ...
@overload
def __init__(
self: ReturnDict[bytes, bytes], iterable: Iterable[list[bytes]], /, *, serializer: BaseSerializer
) -> None: ...
def copy(self) -> ReturnDict[_KT, _VT]: ...
def __reduce__(self) -> tuple[type[dict[_KT, _VT]], tuple[dict[_KT, _VT]]]: ...
class ReturnList(list[_T], Generic[_T]):
serializer: BaseSerializer
# Copied from https://github.com/python/typeshed/blob/main/stdlib/builtins.pyi `class list`
@overload
def __init__(self, *, serializer: BaseSerializer) -> None: ...
@overload
def __init__(self, iterable: Iterable[_T], /, *, serializer: BaseSerializer) -> None: ...
def __reduce__(self) -> tuple[type[list[_T]], tuple[list[_T]]]: ...
class BoundField:
"""
A field object that also includes `.value` and `.error` properties.
Returned when iterating over a serializer instance,
providing an API similar to Django forms and form fields.
"""
value: Any
fields: dict[str, Field]
errors: list[ErrorDetail]
def __init__(self, field: Field, value: Any, errors: list[ErrorDetail], prefix: str = ...) -> None: ...
def __getattr__(self, attr_name: str) -> Any: ...
def as_form_field(self) -> BoundField: ...
class JSONBoundField(BoundField): ...
class NestedBoundField(BoundField):
def __iter__(self) -> Iterator[str]: ...
def __getitem__(self, key: str) -> BoundField | NestedBoundField: ...
class BindingDict(MutableMapping[str, Field]):
serializer: BaseSerializer
fields: dict[str, Field]
def __init__(self, serializer: BaseSerializer) -> None: ...
def __setitem__(self, key: str, field: Field) -> None: ...
def __getitem__(self, key: str) -> Field: ...
def __delitem__(self, key: str) -> None: ...
def __iter__(self) -> Iterator[Field]: ... # type: ignore[override]
def __len__(self) -> int: ...
07070100000064000081A4000000000000000000000001687648C500000091000000000000000000000000000000000000004500000000djangorestframework-stubs-3.16.1/rest_framework-stubs/utils/urls.pyifrom typing import Any
def replace_query_param(url: str, key: Any, val: Any) -> str: ...
def remove_query_param(url: str, key: Any) -> str: ...
07070100000065000081A4000000000000000000000001687648C500000CF3000000000000000000000000000000000000004500000000djangorestframework-stubs-3.16.1/rest_framework-stubs/validators.pyifrom collections.abc import Callable, Container, Iterable, MutableMapping
from typing import Any, Protocol, TypeAlias, TypeVar
from django.db.models import Model, Q, QuerySet
from django_stubs_ext import StrOrPromise
from rest_framework.fields import Field
from rest_framework.serializers import BaseSerializer
_T = TypeVar("_T", bound=Model)
_V = TypeVar("_V", contravariant=True)
class ContextValidator(Protocol[_V]):
requires_context: bool
def __call__(self, value: _V, context: Field, /) -> None: ...
Validator: TypeAlias = Callable[[_V], None] | ContextValidator[_V]
def qs_exists(queryset: QuerySet) -> bool: ...
def qs_filter(queryset: QuerySet[_T], **kwargs: Any) -> QuerySet[_T]: ...
class UniqueValidator:
message: StrOrPromise
requires_context: bool
queryset: QuerySet
lookup: str
def __init__(self, queryset: QuerySet, message: StrOrPromise | None = ..., lookup: str = ...) -> None: ...
def filter_queryset(self, value: Any, queryset: QuerySet[_T], field_name: str) -> QuerySet[_T]: ...
def exclude_current_instance(self, queryset: QuerySet[_T], instance: _T) -> QuerySet[_T]: ...
def __call__(self, value: Any, serializer_field: Field) -> None: ...
class UniqueTogetherValidator:
message: StrOrPromise
missing_message: StrOrPromise
requires_context: bool
queryset: QuerySet
fields: Iterable[str]
def __init__(
self,
queryset: QuerySet,
fields: Iterable[str],
message: StrOrPromise | None = ...,
condition_fields: Iterable[str] | None = None,
condition: Q | None = None,
) -> None: ...
def enforce_required_fields(self, attrs: Container[str], serializer: BaseSerializer) -> None: ...
def filter_queryset(
self, attrs: MutableMapping[str, Any], queryset: QuerySet[_T], serializer: BaseSerializer
) -> QuerySet[_T]: ...
def exclude_current_instance(
self, attrs: MutableMapping[str, Any], queryset: QuerySet[_T], instance: _T
) -> QuerySet[_T]: ...
def __call__(self, attrs: MutableMapping[str, Any], serializer: BaseSerializer) -> None: ...
def qs_exists_with_condition(queryset: QuerySet[Any], condition: Q | None, against: dict[str, Any]) -> bool: ...
class ProhibitSurrogateCharactersValidator:
message: StrOrPromise
code: str
def __call__(self, value: Any) -> None: ...
class BaseUniqueForValidator:
message: StrOrPromise
missing_message: StrOrPromise
requires_context: bool
queryset: QuerySet
field: str
date_field: str
def __init__(self, queryset: QuerySet, field: str, date_field: str, message: StrOrPromise | None = ...) -> None: ...
def enforce_required_fields(self, attrs: Container[str]) -> None: ...
def filter_queryset(
self, attrs: MutableMapping[str, Any], queryset: QuerySet[_T], field_name: str, date_field_name: str
) -> QuerySet[_T]: ...
def exclude_current_instance(
self, attrs: MutableMapping[str, Any], queryset: QuerySet[_T], instance: Model
) -> QuerySet[_T]: ...
def __call__(self, attrs: MutableMapping[str, Any], serializer: BaseSerializer) -> None: ...
class UniqueForDateValidator(BaseUniqueForValidator): ...
class UniqueForMonthValidator(BaseUniqueForValidator): ...
class UniqueForYearValidator(BaseUniqueForValidator): ...
07070100000066000081A4000000000000000000000001687648C500000492000000000000000000000000000000000000004500000000djangorestframework-stubs-3.16.1/rest_framework-stubs/versioning.pyifrom collections.abc import Mapping, Sequence
from re import Pattern
from typing import Any
from rest_framework.request import Request
class BaseVersioning:
default_version: str | None
allowed_versions: Sequence[str] | None
version_param: str
def determine_version(self, request: Request, *args: Any, **kwargs: Any) -> str: ...
def reverse(
self,
viewname: str,
args: Sequence[Any] | None = ...,
kwargs: Mapping[str, Any] | None = ...,
request: Request | None = ...,
format: str | None = ...,
**extra: Any,
) -> str: ...
def is_allowed_version(self, version: str | None) -> bool: ...
class AcceptHeaderVersioning(BaseVersioning):
invalid_version_message: str
class URLPathVersioning(BaseVersioning):
invalid_version_message: str
class NamespaceVersioning(BaseVersioning):
invalid_version_message: str
def get_versioned_viewname(self, viewname: str, request: Request) -> str: ...
class HostNameVersioning(BaseVersioning):
hostname_regex: Pattern
invalid_version_message: str
class QueryParameterVersioning(BaseVersioning):
invalid_version_message: str
07070100000067000081A4000000000000000000000001687648C50000126E000000000000000000000000000000000000004000000000djangorestframework-stubs-3.16.1/rest_framework-stubs/views.pyifrom collections.abc import Callable, Mapping, Sequence
from typing import Any, NoReturn, Protocol, TypeVar
from django.http import HttpRequest
from django.http.response import HttpResponseBase
from django.views.generic import View
from rest_framework.authentication import BaseAuthentication
from rest_framework.metadata import BaseMetadata
from rest_framework.negotiation import BaseContentNegotiation
from rest_framework.parsers import BaseParser
from rest_framework.permissions import _PermissionClass, _SupportsHasPermission
from rest_framework.renderers import BaseRenderer
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.schemas.inspectors import ViewInspector
from rest_framework.settings import APISettings
from rest_framework.throttling import BaseThrottle
from rest_framework.versioning import BaseVersioning
def get_view_name(view: APIView) -> str: ...
def get_view_description(view: APIView, html: bool = ...) -> str: ...
def set_rollback() -> None: ...
def exception_handler(exc: Exception, context: dict[str, Any]) -> Response | None: ...
_View = TypeVar("_View", bound=Callable[..., HttpResponseBase])
class AsView(Protocol[_View]):
cls: type[APIView]
view_class: type[APIView]
view_initkwargs: Mapping[str, Any]
csrf_exempt: bool
__call__: _View
# Call signature for view function that's returned by as_view()
class GenericView(Protocol):
def __call__(self, request: HttpRequest, *args: Any, **kwargs: Any) -> Response: ...
class APIView(View):
args: Any
authentication_classes: Sequence[type[BaseAuthentication]]
content_negotiation_class: type[BaseContentNegotiation]
format_kwarg: Any
headers: dict[str, str]
kwargs: Any
metadata_class: str | BaseMetadata | None
parser_classes: Sequence[type[BaseParser]]
permission_classes: Sequence[_PermissionClass]
renderer_classes: Sequence[type[BaseRenderer]]
request: Request
response: Response
schema: ViewInspector | None
settings: APISettings
throttle_classes: Sequence[type[BaseThrottle]]
versioning_class: type[BaseVersioning] | None
@property
def allowed_methods(self) -> list[str]: ...
@property
def default_response_headers(self) -> dict[str, str]: ...
@classmethod
def as_view(cls, **initkwargs: Any) -> AsView[GenericView]: ...
def http_method_not_allowed(self, request: Request, *args: Any, **kwargs: Any) -> Response: ... # type: ignore[override]
def permission_denied(self, request: Request, message: str | None = ..., code: str | None = ...) -> NoReturn: ...
def throttled(self, request: Request, wait: float) -> NoReturn: ...
def get_authenticate_header(self, request: Request) -> str: ...
def get_parser_context(self, http_request: HttpRequest) -> dict[str, Any]: ...
def get_renderer_context(self) -> dict[str, Any]: ...
def get_exception_handler_context(self) -> dict[str, Any]: ...
def get_view_name(self) -> str: ...
def get_view_description(self, html: bool = ...) -> str: ...
def get_format_suffix(self, **kwargs: Any) -> str | None: ...
def get_renderers(self) -> list[BaseRenderer]: ...
def get_parsers(self) -> list[BaseParser]: ...
def get_authenticators(self) -> list[BaseAuthentication]: ...
def get_permissions(self) -> Sequence[_SupportsHasPermission]: ...
def get_throttles(self) -> list[BaseThrottle]: ...
def get_content_negotiator(self) -> BaseContentNegotiation: ...
def get_exception_handler(self) -> Callable: ...
def perform_content_negotiation(self, request: Request, force: bool = ...) -> tuple[BaseRenderer, str]: ...
def perform_authentication(self, request: Request) -> None: ...
def check_permissions(self, request: Request) -> None: ...
def check_object_permissions(self, request: Request, obj: Any) -> None: ...
def check_throttles(self, request: Request) -> None: ...
def determine_version(
self, request: Request, *args: Any, **kwargs: Any
) -> tuple[str | None, BaseVersioning | None]: ...
def initialize_request(self, request: HttpRequest, *args: Any, **kwargs: Any) -> Request: ...
def initial(self, request: Request, *args: Any, **kwargs: Any) -> None: ...
def finalize_response(self, request: Request, response: Response, *args: Any, **kwargs: Any) -> Response: ...
def handle_exception(self, exc: Exception) -> Response: ...
def raise_uncaught_exception(self, exc: Exception) -> NoReturn: ...
def dispatch(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponseBase: ...
def options(self, request: Request, *args: Any, **kwargs: Any) -> Response: ... # type: ignore[override]
07070100000068000081A4000000000000000000000001687648C5000006E3000000000000000000000000000000000000004300000000djangorestframework-stubs-3.16.1/rest_framework-stubs/viewsets.pyifrom collections.abc import Callable
from typing import Any, TypeAlias
from django.http.request import HttpRequest
from django.http.response import HttpResponseBase
from rest_framework import generics, mixins, views
from rest_framework.decorators import ViewSetAction
from rest_framework.generics import _MT_co
from rest_framework.request import Request
from rest_framework.views import AsView, GenericView
def _is_extra_action(attr: Any) -> bool: ...
_ViewFunc: TypeAlias = Callable[..., HttpResponseBase]
class ViewSetMixin:
# Classvars assigned in as_view()
name: str | None
description: str | None
suffix: str | None
detail: bool
basename: str
# Instance attributes assigned in view wrapper
action_map: dict[str, str]
args: tuple[Any, ...]
kwargs: dict[str, Any]
# Assigned in initialize_request()
action: str
@classmethod
def as_view(
cls, actions: dict[str, str | ViewSetAction] | None = ..., **initkwargs: Any
) -> AsView[GenericView]: ...
def initialize_request(self, request: HttpRequest, *args: Any, **kwargs: Any) -> Request: ...
def reverse_action(self, url_name: str, *args: Any, **kwargs: Any) -> str: ...
@classmethod
def get_extra_actions(cls) -> list[_ViewFunc]: ...
def get_extra_action_url_map(self) -> dict[str, str]: ...
class ViewSet(ViewSetMixin, views.APIView): ...
class GenericViewSet(ViewSetMixin, generics.GenericAPIView[_MT_co]): ...
class ReadOnlyModelViewSet(mixins.RetrieveModelMixin, mixins.ListModelMixin, GenericViewSet[_MT_co]): ...
class ModelViewSet(
mixins.CreateModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
mixins.ListModelMixin,
GenericViewSet[_MT_co],
): ...
07070100000069000041ED000000000000000000000002687648C500000000000000000000000000000000000000000000002900000000djangorestframework-stubs-3.16.1/scripts0707010000006A000081A4000000000000000000000001687648C500000000000000000000000000000000000000000000003500000000djangorestframework-stubs-3.16.1/scripts/__init__.py0707010000006B000081A4000000000000000000000001687648C500000156000000000000000000000000000000000000003F00000000djangorestframework-stubs-3.16.1/scripts/drf_tests_settings.pySECRET_KEY = "1"
SITE_ID = 1
INSTALLED_APPS = (
"django.contrib.contenttypes",
"django.contrib.sites",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.admin.apps.SimpleAdminConfig",
"django.contrib.staticfiles",
"django.contrib.auth",
"rest_framework",
"rest_framework.authtoken",
)
0707010000006C000041ED000000000000000000000002687648C500000000000000000000000000000000000000000000003200000000djangorestframework-stubs-3.16.1/scripts/stubtest0707010000006D000081ED000000000000000000000001687648C500000189000000000000000000000000000000000000003500000000djangorestframework-stubs-3.16.1/scripts/stubtest.sh#!/usr/bin/env bash
# Run this script as `bash ./scripts/stubtest.sh`
set -e
export MYPYPATH='.'
# Cleaning existing cache:
rm -rf .mypy_cache
# TODO: remove `--ignore-positional-only` when ready
stubtest rest_framework \
--mypy-config-file mypy.ini \
--ignore-positional-only \
--allowlist scripts/stubtest/allowlist.txt \
--allowlist scripts/stubtest/allowlist_todo.txt
0707010000006E000081A4000000000000000000000001687648C5000005A9000000000000000000000000000000000000004000000000djangorestframework-stubs-3.16.1/scripts/stubtest/allowlist.txt# This is a true allow list with things that we really don't care about.
# `allowlist_todo.txt` is autogenerated by `stubtest --generate-allowlist`
# and might contain actual problems and things that we *do want* to fix.
#
# Please, move things here when you are sure that they really should be ignored.
# Comments about why things are ignored are mandatory.
# Constructor arguments *appear* optional but actually throw exception
rest_framework.relations.ManyRelatedField.__init__
rest_framework.relations.SlugRelatedField.__init__
rest_framework.serializers.ManyRelatedField.__init__
rest_framework.serializers.SlugRelatedField.__init__
# Migrations are omitted
rest_framework.authtoken.migrations
rest_framework.authtoken.migrations.0001_initial
rest_framework.authtoken.migrations.0002_auto_20160226_1747
rest_framework.authtoken.migrations.0003_tokenproxy
rest_framework.authtoken.migrations.0004_alter_tokenproxy_options
# Mypy doesn't like default value `empty`
rest_framework.fields.DateField.__init__
rest_framework.fields.DateTimeField.__init__
rest_framework.fields.TimeField.__init__
rest_framework.serializers.DateField.__init__
rest_framework.serializers.DateTimeField.__init__
rest_framework.serializers.TimeField.__init__
# Generated objects:
rest_framework.authtoken.models.Token@AnnotatedWith
rest_framework.authtoken.models.TokenProxy@AnnotatedWith
# .save() will be different soon:
rest_framework.authtoken.models.Token.save
0707010000006F000081A4000000000000000000000001687648C500001447000000000000000000000000000000000000004500000000djangorestframework-stubs-3.16.1/scripts/stubtest/allowlist_todo.txt# Autogenerated by `stubtest`
# Unsorted: there are real problems and things we can really ignore.
rest_framework.authtoken.admin.User
rest_framework.authtoken.default_app_config
rest_framework.authtoken.management.commands.drf_create_token.UserModel
rest_framework.authtoken.models.Token.created
rest_framework.authtoken.models.Token.get_next_by_created
rest_framework.authtoken.models.Token.get_previous_by_created
rest_framework.authtoken.models.Token.key
rest_framework.authtoken.models.Token.user
rest_framework.authtoken.models.Token.user_id
rest_framework.authtoken.models.TokenProxy.get_next_by_created
rest_framework.authtoken.models.TokenProxy.get_previous_by_created
rest_framework.authtoken.models.TokenProxy.pk
rest_framework.authtoken.models.TokenProxy.user_id
rest_framework.authtoken.views.ObtainAuthToken.serializer_class
rest_framework.authtoken.views.obtain_auth_token
rest_framework.compat.CodeBlockPreprocessor
rest_framework.compat.Preprocessor
rest_framework.compat.QuerySet
rest_framework.compat.__all__
rest_framework.compat.apply_markdown
rest_framework.decorators.ViewSetAction
rest_framework.decorators.action
rest_framework.default_app_config
rest_framework.documentation.get_docs_view
rest_framework.documentation.get_schemajs_view
rest_framework.documentation.include_docs_urls
rest_framework.fields.BooleanField.initial
rest_framework.fields.CharField.initial
rest_framework.fields.DateField.to_internal_value
rest_framework.fields.DateTimeField.to_internal_value
rest_framework.fields.DictField.initial
rest_framework.fields.DurationField.to_internal_value
rest_framework.fields.ListField.initial
rest_framework.fields.ListField.to_representation
rest_framework.fields.ModelField.get_attribute
rest_framework.fields.ModelField.to_representation
rest_framework.fields.NullBooleanField
rest_framework.fields.Option
rest_framework.fields.REGEX_TYPE
rest_framework.fields.SupportsToPython
rest_framework.fields.TimeField.to_internal_value
rest_framework.fields.empty
rest_framework.generics.BaseFilterProtocol
rest_framework.generics.UsesQuerySet
rest_framework.negotiation.DefaultContentNegotiation.settings
rest_framework.pagination.HtmlContext
rest_framework.pagination.HtmlContextWithPageLinks
rest_framework.parsers.BaseParser.media_type
rest_framework.parsers.FileUploadParser.get_encoded_filename
rest_framework.relations.ManyRelatedField.initial
rest_framework.relations.ManyRelatedField.to_representation
rest_framework.renderers.BaseRenderer.format
rest_framework.renderers.BaseRenderer.media_type
rest_framework.renderers.BrowsableAPIRenderer.get_extra_actions
rest_framework.renderers.CoreJSONRenderer.render
rest_framework.renderers._BaseOpenAPIRenderer.__init__
rest_framework.renderers._BaseOpenAPIRenderer.render
rest_framework.routers.BaseRouter.register
rest_framework.schemas.SchemaGenerator.__init__
rest_framework.schemas.coreapi.SchemaGenerator.__init__
rest_framework.schemas.generators.common_path
rest_framework.schemas.get_schema_view
rest_framework.schemas.openapi.AutoSchema.__init__
rest_framework.schemas.openapi.DRFOpenAPIInfo
rest_framework.schemas.openapi.DRFOpenAPISchema
rest_framework.schemas.openapi.ExternalDocumentationObject
rest_framework.schemas.openapi.SchemaGenerator.get_schema
rest_framework.schemas.views.SchemaView.__init__
rest_framework.schemas.views.SchemaView.renderer_classes
rest_framework.serializers.APIException
rest_framework.serializers.AuthenticationFailed
rest_framework.serializers.BooleanField.initial
rest_framework.serializers.CharField.initial
rest_framework.serializers.DateField.to_internal_value
rest_framework.serializers.DateTimeField.to_internal_value
rest_framework.serializers.DictField.initial
rest_framework.serializers.DurationField.to_internal_value
rest_framework.serializers.ListField.initial
rest_framework.serializers.ListField.to_representation
rest_framework.serializers.ManyRelatedField.initial
rest_framework.serializers.ManyRelatedField.to_representation
rest_framework.serializers.MethodNotAllowed
rest_framework.serializers.ModelField.get_attribute
rest_framework.serializers.ModelField.to_representation
rest_framework.serializers.ModelSerializer.Meta
rest_framework.serializers.NotAcceptable
rest_framework.serializers.NotAuthenticated
rest_framework.serializers.NotFound
rest_framework.serializers.NullBooleanField
rest_framework.serializers.ParseError
rest_framework.serializers.PermissionDenied
rest_framework.serializers.Throttled
rest_framework.serializers.TimeField.to_internal_value
rest_framework.serializers.UnsupportedMediaType
rest_framework.serializers.empty
rest_framework.settings.DefaultsSettings
rest_framework.settings.api_settings
rest_framework.templatetags.rest_framework.urlize_quoted_links
rest_framework.test.CoreAPIClient
rest_framework.test.APIClient.options
rest_framework.test.RequestsClient.__init__
rest_framework.throttling.SimpleRateThrottle.cache
rest_framework.utils.encoders.JSONEncoder.default
rest_framework.validators.BaseUniqueForValidator.message
rest_framework.validators.ContextValidator
rest_framework.validators.Validator
rest_framework.views.APIView.metadata_class
rest_framework.views.AsView
rest_framework.views.GenericView
07070100000070000081A4000000000000000000000001687648C500000567000000000000000000000000000000000000004100000000djangorestframework-stubs-3.16.1/scripts/tests_extension_hook.pyfrom pytest_mypy_plugins.collect import File
from pytest_mypy_plugins.item import YamlTestItem
def django_plugin_hook(test_item: YamlTestItem) -> None:
custom_settings = test_item.parsed_test_data.get("custom_settings", "")
installed_apps = test_item.parsed_test_data.get("installed_apps", None)
if installed_apps and custom_settings:
raise ValueError('"installed_apps" and "custom_settings" are not compatible, please use one or the other')
if installed_apps is not None:
# custom_settings is empty, add INSTALLED_APPS
installed_apps += ["django.contrib.contenttypes"]
installed_apps_as_str = "(" + ",".join([repr(app) for app in installed_apps]) + ",)"
custom_settings += "INSTALLED_APPS = " + installed_apps_as_str
if "SECRET_KEY" not in custom_settings:
custom_settings = 'SECRET_KEY = "1"\n' + custom_settings
django_settings_section = "\n[mypy.plugins.django-stubs]\ndjango_settings_module = mysettings"
if not test_item.additional_mypy_config:
test_item.additional_mypy_config = django_settings_section
else:
if "[mypy.plugins.django-stubs]" not in test_item.additional_mypy_config:
test_item.additional_mypy_config += django_settings_section
mysettings_file = File(path="mysettings.py", content=custom_settings)
test_item.files.append(mysettings_file)
07070100000071000081A4000000000000000000000001687648C50000019B000000000000000000000000000000000000002B00000000djangorestframework-stubs-3.16.1/setup.cfg[flake8]
exclude =
.venv
.idea
.mypy_cache
.venv
max_line_length = 120
per-file-ignores =
*.pyi: B, E301, E302, E305, E501, E701, E741, E743, NQA102, F401, F403, F405, F822, Y021, Y024, Y041, Y043
rest_framework-stubs/compat.pyi: B, E301, E302, E305, E501, E701, E741, E743, NQA102, F401, F403, F405, F822, Y021, Y024, Y041, Y043, Y026, Y002, F811
[metadata]
license_file = LICENSE.txt
07070100000072000081A4000000000000000000000001687648C500000878000000000000000000000000000000000000002A00000000djangorestframework-stubs-3.16.1/setup.pyimport os
from setuptools import find_packages, setup
def find_stub_files(name: str) -> list[str]:
result = []
for root, _dirs, files in os.walk(name):
for file in files:
if file.endswith(".pyi"):
if os.path.sep in root:
sub_root = root.split(os.path.sep, 1)[-1]
file = os.path.join(sub_root, file)
result.append(file)
return result
with open("README.md") as f:
readme = f.read()
dependencies = [
"django-stubs>=5.2.1",
"typing-extensions>=4.0",
"requests>=2.0",
"types-requests",
"types-PyYAML",
]
# Keep compatible-mypy major.minor version pinned to what latest django-stubs release uses.
extras_require = {
"compatible-mypy": ["mypy>=1.13,<1.17", "django-stubs[compatible-mypy]"],
"coreapi": ["coreapi>=2.0.0"],
"markdown": ["types-Markdown>=0.1.5"],
}
setup(
name="djangorestframework-stubs",
version="3.16.1",
description="PEP-484 stubs for django-rest-framework",
long_description=readme,
long_description_content_type="text/markdown",
url="https://github.com/typeddjango/djangorestframework-stubs",
author="Maksim Kurnikov",
author_email="maxim.kurnikov@gmail.com",
maintainer="Marti Raudsepp",
maintainer_email="marti@juffo.org",
license="MIT",
install_requires=dependencies,
extras_require=extras_require,
packages=["rest_framework-stubs", *find_packages(exclude=["scripts"])],
package_data={"rest_framework-stubs": find_stub_files("rest_framework-stubs")},
python_requires=">=3.10",
classifiers=[
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.13",
"Typing :: Typed",
"Framework :: Django",
],
project_urls={
"Release notes": "https://github.com/typeddjango/djangorestframework-stubs/releases",
"Funding": "https://github.com/sponsors/typeddjango",
},
)
07070100000073000041ED000000000000000000000002687648C500000000000000000000000000000000000000000000002700000000djangorestframework-stubs-3.16.1/tests07070100000074000041ED000000000000000000000002687648C500000000000000000000000000000000000000000000003100000000djangorestframework-stubs-3.16.1/tests/typecheck07070100000075000081A4000000000000000000000001687648C500000B65000000000000000000000000000000000000004600000000djangorestframework-stubs-3.16.1/tests/typecheck/test_all_imports.yml- case: all_imports_typecheck
main: |
import rest_framework
import rest_framework.apps
import rest_framework.authentication
import rest_framework.authtoken
import rest_framework.authtoken.admin
import rest_framework.authtoken.apps
import rest_framework.authtoken.management
import rest_framework.authtoken.management.commands
import rest_framework.authtoken.management.commands.drf_create_token
import rest_framework.authtoken.models
import rest_framework.authtoken.serializers
import rest_framework.authtoken.views
import rest_framework.checks
import rest_framework.compat
import rest_framework.decorators
import rest_framework.documentation
import rest_framework.exceptions
import rest_framework.fields
import rest_framework.filters
import rest_framework.generics
import rest_framework.management.commands.generateschema
import rest_framework.metadata
import rest_framework.mixins
import rest_framework.negotiation
import rest_framework.pagination
import rest_framework.parsers
import rest_framework.permissions
import rest_framework.relations
import rest_framework.renderers
import rest_framework.request
import rest_framework.response
import rest_framework.reverse
import rest_framework.routers
import rest_framework.schemas
import rest_framework.schemas.coreapi
import rest_framework.schemas.generators
import rest_framework.schemas.inspectors
import rest_framework.schemas.openapi
import rest_framework.schemas.utils
import rest_framework.schemas.views
import rest_framework.serializers
import rest_framework.settings
import rest_framework.status
import rest_framework.templatetags
import rest_framework.templatetags.rest_framework
import rest_framework.test
import rest_framework.throttling
import rest_framework.urlpatterns
import rest_framework.urls
import rest_framework.utils
import rest_framework.utils.breadcrumbs
import rest_framework.utils.encoders
import rest_framework.utils.field_mapping
import rest_framework.utils.formatting
import rest_framework.utils.html
import rest_framework.utils.humanize_datetime
import rest_framework.utils.json
import rest_framework.utils.mediatypes
import rest_framework.utils.model_meta
import rest_framework.utils.representation
import rest_framework.utils.serializer_helpers
import rest_framework.utils.urls
import rest_framework.validators
import rest_framework.versioning
import rest_framework.views
import rest_framework.viewsets
07070100000076000081A4000000000000000000000001687648C50000025F000000000000000000000000000000000000004500000000djangorestframework-stubs-3.16.1/tests/typecheck/test_api_client.yml- case: api_client_returns_proper_responses
main: |
from rest_framework import test
class MyTestCase(test.APITestCase):
client: test.APIClient
def test_my_code(self) -> None:
client = test.APIClient()
reveal_type(client.post('http://google.com')) # N: Revealed type is "rest_framework.response._MonkeyPatchedResponse"
def test_json_attribute_on_response(self) -> None:
client = test.APIClient()
resp = client.get('http://someapi.com/1')
self.assertTrue(resp.json())
07070100000077000081A4000000000000000000000001687648C500000131000000000000000000000000000000000000004100000000djangorestframework-stubs-3.16.1/tests/typecheck/test_compat.yml- case: test_compat_postgres_fields
main: |
from rest_framework.compat import postgres_fields
reveal_type(postgres_fields) # N: Revealed type is "types.ModuleType"
reveal_type(postgres_fields.hstore.HStoreField()) # N: Revealed type is "django.contrib.postgres.fields.hstore.HStoreField"
07070100000078000081A4000000000000000000000001687648C500000E9B000000000000000000000000000000000000004500000000djangorestframework-stubs-3.16.1/tests/typecheck/test_decorators.yml- case: api_view
main: |
from typing import Any
from rest_framework.decorators import api_view
from rest_framework.request import Request
from rest_framework.response import Response
@api_view()
def view_func1(request: Any) -> Any: ...
reveal_type(view_func1) # N: Revealed type is "rest_framework.views.AsView[def (django.http.request.HttpRequest) -> Any]"
- case: api_view_fancy
main: |
from rest_framework.decorators import api_view
from rest_framework.request import Request
from rest_framework.response import Response
@api_view(['GET', 'POST'])
def view_func2(request: Request, arg: str) -> Response: ...
reveal_type(view_func2) # N: Revealed type is "rest_framework.views.AsView[def (django.http.request.HttpRequest, arg: builtins.str) -> rest_framework.response.Response]"
view_func2(None, 10) # E: Argument 1 has incompatible type "None"; expected "HttpRequest" # E: Argument 2 has incompatible type "int"; expected "str"
- case: api_view_bare_is_error
main: |
from typing import Any
from rest_framework.decorators import api_view
@api_view # E: Argument 1 to "api_view" has incompatible type "Callable[[Any], Any]"; expected "Optional[Sequence[str]]"
def view_func2(request: Any) -> Any: ...
- case: api_view_incorrect_return
main: |
from rest_framework.decorators import api_view
from rest_framework.request import Request
@api_view() # E: Value of type variable "_RESP" of function cannot be "List[Any]"
def view_func2(request: Request) -> list: ...
- case: permission_classes
main: |
from rest_framework.decorators import permission_classes
reveal_type(permission_classes) # N: Revealed type is "def (permission_classes: typing.Sequence[Union[Type[rest_framework.permissions.BasePermission], rest_framework.permissions.OperandHolder, rest_framework.permissions.SingleOperandHolder]]) -> def [_View <: def (*Any, **Any) -> django.http.response.HttpResponseBase] (_View`-1) -> _View`-1"
- case: permission_classes_with_operators
main: |
from rest_framework.permissions import BasePermission, IsAuthenticated
from rest_framework.decorators import permission_classes
class Permission(BasePermission):
pass
permission_classes([IsAuthenticated & Permission])
permission_classes([IsAuthenticated | Permission])
permission_classes([~Permission])
- case: method_decorator
main: |
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.request import Request
from rest_framework.response import Response
class MyView(viewsets.ViewSet):
@action(methods=("get",), detail=False)
def view_func_1(self, request: Request) -> Response: ...
@action(methods=["post"], detail=False)
def view_func_2(self, request: Request) -> Response: ...
@action(methods=("GET",), detail=False)
def view_func_3(self, request: Request) -> Response: ...
- case: method_decorator_http_libary
skip: sys.version_info < (3, 11)
main: |
from http import HTTPMethod
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.request import Request
from rest_framework.response import Response
MY_VAR: HTTPMethod = HTTPMethod.POST
class MyView(viewsets.ViewSet):
@action(methods=[HTTPMethod.GET], detail=False)
def view_func_1(self, request: Request) -> Response: ...
@action(methods=[MY_VAR], detail=False)
def view_func_2(self, request: Request) -> Response: ...
07070100000079000081A4000000000000000000000001687648C500000791000000000000000000000000000000000000004500000000djangorestframework-stubs-3.16.1/tests/typecheck/test_exceptions.yml- case: test_exception_declaration
main: |
from rest_framework import exceptions
class MyException(exceptions.APIException):
status_code = 200
default_detail = "Everything is a okay"
default_code = "ok"
- case: test_exception_declaration_dict_detail
main: |
from rest_framework import exceptions
class MyException(exceptions.APIException):
status_code = 200
default_detail = {"ok": "everything"}
default_code = "ok"
- case: test_exception_declaration_lazystr
main: |
from django.utils.translation import gettext_lazy as _
from rest_framework import exceptions
class MyException(exceptions.APIException):
status_code = 200
default_detail = _("Está tudo bem")
default_code = "ok"
- case: test_exception_input
main: |
from django.utils.translation import gettext_lazy as _
from rest_framework.exceptions import APIException, ErrorDetail
test_exception = APIException({
'a': [
'value',
_('translated'),
ErrorDetail('with code', code='brown'),
{'b': 'test', 'c': _('translated')},
('also', 'tuple', ErrorDetail('value')),
]
})
APIException(detail=test_exception.detail, code='123')
APIException(detail=[test_exception.detail], code='123')
APIException('I am just a message', code='msg')
APIException()
APIException(None, None)
APIException(1) # E: Argument 1 to "APIException" has incompatible type "int"; expected "_APIExceptionInput"
APIException({'a': 1}) # E: Dict entry 0 has incompatible type "str": "int"; expected "str": "Union[_StrPromise, Sequence[_APIExceptionInput], Mapping[str, _APIExceptionInput], None]"
APIException({'a': ['test', 1]}) # E: List item 1 has incompatible type "int"; expected "Union[_StrPromise, Sequence[_APIExceptionInput], Mapping[str, _APIExceptionInput], None]"
0707010000007A000081A4000000000000000000000001687648C500001F3E000000000000000000000000000000000000004100000000djangorestframework-stubs-3.16.1/tests/typecheck/test_fields.yml- case: no_positional_args_fields
main: |
from rest_framework.fields import IntegerField, FloatField, UUIDField, CharField, DurationField
CharField(True) # E: Too many positional arguments for "CharField"
IntegerField(1) # E: Too many positional arguments for "IntegerField"
FloatField(1) # E: Too many positional arguments for "FloatField"
UUIDField('hex_verbose') # E: Too many positional arguments for "UUIDField"
DurationField(1) # E: Too many positional arguments for "DurationField"
- case: some_positional_args_fields
main: |
from datetime import datetime, time
from django.db import models
from rest_framework.fields import DecimalField, IPAddressField, SlugField, RegexField, ModelField, SerializerMethodField, ChoiceField, DateTimeField, DateField, TimeField
DecimalField(1, 1, False, 1, 1, False, None, False)
DecimalField(1, 1, False, 1, 1, False, None, False, True) # E: Too many positional arguments for "DecimalField"
IPAddressField('both')
IPAddressField('both', True) # E: Too many positional arguments for "IPAddressField"
SlugField(False)
SlugField(False, True) # E: Too many positional arguments for "SlugField"
RegexField('^$')
RegexField('^$', True) # E: Too many positional arguments for "RegexField"
SerializerMethodField('bla')
SerializerMethodField('bla', True) # E: Too many positional arguments for "SerializerMethodField"
mf: models.CharField = models.CharField()
ModelField(mf)
ModelField(mf, True) # E: Too many positional arguments for "ModelField"
ChoiceField([])
ChoiceField([], False) # E: Too many positional arguments for "ChoiceField"
d: datetime = datetime.now()
DateTimeField('', [], None, read_only=True, write_only=True, allow_null=True)
DateTimeField('', [], None, True) # E: Too many positional arguments for "DateTimeField"
DateField('', [], read_only=True, write_only=True, allow_null=True)
DateField('', [], True) # E: Too many positional arguments for "DateField"
TimeField('', [], read_only=True, write_only=True, allow_null=True)
TimeField('', [], True) # E: Too many positional arguments for "TimeField"
- case: default_and_inital_args_fields
main: |
from rest_framework.fields import DictField, CharField, empty
from typing import Optional, Dict, Any
CharField(initial='', default=lambda: '')
CharField(initial=None, default=4) # E: Argument "default" to "CharField" has incompatible type "int"; expected "Union[Union[str, _StrPromise], Callable[[], Union[str, _StrPromise]], _Empty, None]"
CharField(initial={}, default=empty) # E: Argument "initial" to "CharField" has incompatible type "Dict[Never, Never]"; expected "Union[str, Callable[[], str], _Empty, None]"
x: Optional[str] = CharField().get_initial()
y: Optional[int] = CharField().get_initial() # E: Incompatible types in assignment (expression has type "Optional[str]", variable has type "Optional[int]")
- case: float_field_args_fields
main: |
from rest_framework.fields import FloatField
FloatField(min_value=1, max_value=1.0)
FloatField(min_value=1.2, max_value=1)
- case: ChoiceField_default
main: |
from typing import Union
from rest_framework.fields import ChoiceField
def int_callback() -> int: ...
def mixed_callback() -> Union[int, str]: ...
ChoiceField([1], default=1)
ChoiceField(['test'], allow_null=True, default=None)
ChoiceField([1], default=int_callback)
ChoiceField([1, 'lulz'], default=mixed_callback)
ChoiceField([1], default=lambda: None) # E: Argument "default" to "ChoiceField" has incompatible type "Callable[[], None]"; expected "Union[Union[str, _StrPromise], int, Callable[[], Union[Union[str, _StrPromise], int]], _Empty, None]" # E: Incompatible return value type (got "None", expected "Union[Union[str, _StrPromise], int]")
- case: MultipleChoiceField_default
main: |
from typing import Set, Union
from rest_framework.fields import MultipleChoiceField
def int_set_callback() -> Set[int]: ...
def mixed_set_callback() -> Set[Union[int, str]]: ...
MultipleChoiceField(choices=[1], default={1})
MultipleChoiceField(choices=['test'], allow_null=True, default=None)
MultipleChoiceField(choices=[1], default=int_set_callback)
MultipleChoiceField(choices=[1, 'lulz'], default=mixed_set_callback)
MultipleChoiceField(choices=[1], default=lambda: [1]) # E: Argument "default" to "MultipleChoiceField" has incompatible type "Callable[[], List[int]]"; expected "Union[Set[Union[str, int]], Set[str], Set[int], Callable[[], Union[Set[Union[str, int]], Set[str], Set[int]]], _Empty, None]" # E: Incompatible return value type (got "List[int]", expected "Union[Set[Union[str, int]], Set[str], Set[int]]")
MultipleChoiceField(choices=[(1, "1"), (2, "2")], default={1})
MultipleChoiceField(choices=[(1, "1"), (2, "2")], default=[1]) # E: Argument "default" to "MultipleChoiceField" has incompatible type "List[int]"; expected "Union[Set[Union[str, int]], Set[str], Set[int], Callable[[], Union[Set[Union[str, int]], Set[str], Set[int]]], _Empty, None]"
MultipleChoiceField(choices=[(1, "1"), (2, "2")], initial={1})
MultipleChoiceField(choices=[(1, "1"), (2, "2")], initial=[1]) # E: Argument "initial" to "MultipleChoiceField" has incompatible type "List[int]"; expected "Union[Set[Union[Union[str, _StrPromise], int]], Set[Union[str, _StrPromise]], Set[int], Callable[[], Union[Set[Union[Union[str, _StrPromise], int]], Set[Union[str, _StrPromise]], Set[int]]], _Empty, None]"
- case: FileField_default
main: |
from rest_framework.fields import FileField, ImageField
from django.core.files.base import File
def file_callback() -> File: ...
FileField(allow_null=True, default=None)
FileField(allow_null=True, default=file_callback)
FileField(allow_null=True, default=file_callback())
FileField(allow_null=True, default=123) # E: Argument "default" to "FileField" has incompatible type "int"; expected "Union[File[Any], Callable[[], File[Any]], _Empty, None]"
ImageField(allow_null=True, default=None)
ImageField(default=file_callback)
ImageField(default=file_callback())
ImageField(default='a') # E: Argument "default" to "ImageField" has incompatible type "str"; expected "Union[File[Any], Callable[[], File[Any]], _Empty, None]"
- case: DictField_default
main: |
from rest_framework.fields import DictField, JSONField
DictField(allow_null=True, default=None)
DictField(default={})
DictField(default={'a': 1, 'b': 2})
DictField(default=lambda: {'a': [], 'b': 'str'})
DictField(default=[]) # E: Argument "default" to "DictField" has incompatible type "List[Never]"; expected "Union[Dict[Any, Any], Callable[[], Dict[Any, Any]], _Empty, None]"
JSONField(allow_null=True, default=None)
JSONField(default={})
JSONField(default={'a': 1, 'b': 2})
JSONField(default=lambda: {'a': [], 'b': 'str'})
JSONField(default=[]) # E: Argument "default" to "JSONField" has incompatible type "List[Never]"; expected "Union[Mapping[Any, Any], Callable[[], Mapping[Any, Any]], _Empty, None]"
- case: ListField_default
main: |
from rest_framework.fields import ListField
ListField(allow_null=True, default=None)
ListField(default=[])
ListField(default=[0, 'one'])
ListField(default=lambda: [])
ListField(default='wät') # E: Argument "default" to "ListField" has incompatible type "str"; expected "Union[List[Any], Callable[[], List[Any]], _Empty, None]"
0707010000007B000081A4000000000000000000000001687648C500000583000000000000000000000000000000000000004200000000djangorestframework-stubs-3.16.1/tests/typecheck/test_filters.yml- case: basic_filters
main: |
from rest_framework.mixins import CreateModelMixin
from rest_framework.generics import GenericAPIView
from rest_framework.serializers import BaseSerializer, ModelSerializer
from rest_framework.filters import OrderingFilter
from django.db.models import Model
class MyModel(Model):
pass
class MyView(GenericAPIView):
filter_backends = [OrderingFilter]
- case: django_filters
main: |
from typing import Any, List
from rest_framework.mixins import CreateModelMixin
from rest_framework.generics import GenericAPIView, BaseFilterProtocol
from rest_framework.request import Request
from rest_framework.views import APIView
from rest_framework.serializers import BaseSerializer, ModelSerializer
from django.db.models import Model, QuerySet
class MyModel(Model):
pass
class MyFilterBackend:
def filter_queryset(self, request: Request, queryset: QuerySet[MyModel], view: APIView) -> QuerySet[MyModel]:
pass
def get_schema_fields(self, view: APIView) -> List[Any]:
pass
def get_schema_operation_parameters(self, view: APIView) -> Any:
pass
class MyView(GenericAPIView):
filter_backends = [MyFilterBackend]
0707010000007C000081A4000000000000000000000001687648C5000004EC000000000000000000000000000000000000004100000000djangorestframework-stubs-3.16.1/tests/typecheck/test_mixins.yml- case: test_create
main: |
from rest_framework.mixins import CreateModelMixin
from rest_framework.generics import GenericAPIView
from rest_framework.serializers import BaseSerializer, ModelSerializer
from django.db.models import Model
class MyModel(Model):
pass
class MyView(GenericAPIView, CreateModelMixin):
def perform_create(self, serializer: BaseSerializer[MyModel]) -> None: ...
- case: test_perform_update
main: |
from rest_framework.mixins import UpdateModelMixin
from rest_framework.generics import GenericAPIView
from rest_framework.serializers import BaseSerializer
from django.db.models import Model
class MyModel(Model):
pass
class MyView(GenericAPIView, UpdateModelMixin):
def perform_update(self, serializer: BaseSerializer[MyModel]) -> None: ...
- case: test_perform_destroy
main: |
from rest_framework.mixins import DestroyModelMixin
from rest_framework.generics import GenericAPIView
from rest_framework.serializers import BaseSerializer
from django.db.models import Model
class MyModel(Model):
pass
class MyView(GenericAPIView, DestroyModelMixin):
def perform_destroy(self, instance: MyModel) -> None: ...
0707010000007D000081A4000000000000000000000001687648C500000207000000000000000000000000000000000000004500000000djangorestframework-stubs-3.16.1/tests/typecheck/test_pagination.yml- case: test_page_number_pagination_paginate_queryset
main: |
from rest_framework.pagination import PageNumberPagination
from rest_framework.request import Request
from django.contrib.auth.models import User
from django.db.models import QuerySet
paginator = PageNumberPagination()
request: Request
queryset: QuerySet[User]
page = paginator.paginate_queryset(queryset, request)
reveal_type(page) # N: Revealed type is "Union[builtins.list[django.contrib.auth.models.User], None]"
0707010000007E000081A4000000000000000000000001687648C500000147000000000000000000000000000000000000004200000000djangorestframework-stubs-3.16.1/tests/typecheck/test_request.yml- case: request_querydict
main: |
from rest_framework.request import Request
def some_view(request: Request) -> None:
reveal_type(request.query_params['field']) # N: Revealed type is "builtins.str"
reveal_type(request.POST['field']) # N: Revealed type is "builtins.str"
0707010000007F000081A4000000000000000000000001687648C50000031F000000000000000000000000000000000000004200000000djangorestframework-stubs-3.16.1/tests/typecheck/test_routers.yml- case: test_router_urls
main: |
from typing import List, Union
from django.urls import path, include
from rest_framework.routers import SimpleRouter, DefaultRouter
from rest_framework.urlpatterns import _AnyURL
simple = SimpleRouter()
reveal_type(simple.urls) # N: Revealed type is "builtins.list[Union[django.urls.resolvers.URLPattern, django.urls.resolvers.URLResolver]]"
default = DefaultRouter()
reveal_type(default.urls) # N: Revealed type is "builtins.list[Union[django.urls.resolvers.URLPattern, django.urls.resolvers.URLResolver]]"
urlpatterns: List[_AnyURL] = [
path('api/', include(simple.urls)),
path('api/', include((simple.urls, 'app_name'), namespace='instance_name')),
path('default/', include(default.urls)),
]
07070100000080000081A4000000000000000000000001687648C500002B7C000000000000000000000000000000000000004600000000djangorestframework-stubs-3.16.1/tests/typecheck/test_serializers.yml- case: multiple_inheritance_from_two_serializers_with_meta_nested_class_defined
main: |
from rest_framework import serializers
class SerializerA(serializers.Serializer):
class Meta:
pass
class SerializerB(serializers.Serializer):
class Meta:
pass
class SerializerC(SerializerA, SerializerB):
pass
- case: model_serializer_meta_attributes
main: |
from rest_framework import serializers
reveal_type(serializers.ModelSerializer.Meta.model) # N: Revealed type is "Type[_MT?]"
reveal_type(serializers.ModelSerializer.Meta.fields) # N: Revealed type is "typing.Sequence[builtins.str]"
reveal_type(serializers.ModelSerializer.Meta.read_only_fields) # N: Revealed type is "Union[typing.Sequence[builtins.str], None]"
reveal_type(serializers.ModelSerializer.Meta.exclude) # N: Revealed type is "Union[typing.Sequence[builtins.str], None]"
reveal_type(serializers.ModelSerializer.Meta.depth) # N: Revealed type is "Union[builtins.int, None]"
reveal_type(serializers.ModelSerializer.Meta.extra_kwargs) # N: Revealed type is "builtins.dict[builtins.str, builtins.dict[builtins.str, Any]]"
- case: test_model_serializer_passes_check
main: |
from rest_framework import serializers
from django.contrib.auth.models import User
from typing import Type
class TestSerializer(serializers.ModelSerializer):
class Meta:
model = User
def is_meta_model(serializer: Type[serializers.ModelSerializer]) -> bool:
return bool(serializer.Meta.model)
reveal_type(is_meta_model(TestSerializer)) # N: Revealed type is "builtins.bool"
- case: test_model_serializer_with_customized_serializer_field_mapping
main: |
from rest_framework import serializers
from django.contrib.auth.models import User
class TestSerializer(serializers.ModelSerializer):
serializer_related_field = serializers.PrimaryKeyRelatedField
serializer_related_to_field = serializers.SlugRelatedField
serializer_url_field = serializers.HyperlinkedIdentityField
serializer_choice_field = serializers.ChoiceField
class Meta:
model = User
- case: test_hyperlinked_model_serializer_with_customized_serializer_field_mapping
main: |
from rest_framework import serializers
from django.contrib.auth.models import User
class TestSerializer(serializers.HyperlinkedModelSerializer):
serializer_related_field = serializers.HyperlinkedRelatedField
class Meta:
model = User
- case: test_model_serializer_with_overriden_fields_property
main: |
from rest_framework import serializers
from rest_framework.utils.serializer_helpers import BindingDict
from django.contrib.auth.models import User
from django.utils.functional import cached_property
class TestSerializer(serializers.ModelSerializer):
class Meta:
model = User
@cached_property
def fields(self) -> BindingDict:
return super().fields
- case: test_return_list
main: |
from rest_framework import serializers
from rest_framework.utils.serializer_helpers import ReturnList
class TestSerializer(serializers.Serializer):
def test(self) -> None:
ReturnList([], serializer=self)
ReturnList((), serializer=self)
ReturnList([{}], serializer=self)
ReturnList(serializer=self)
ret = ReturnList(["1"], serializer=self)
reveal_type(ret) # N: Revealed type is "rest_framework.utils.serializer_helpers.ReturnList[builtins.str]"
- case: test_return_list_reduce
main: |
from rest_framework import serializers
from rest_framework.utils.serializer_helpers import ReturnList
class TestSerializer(serializers.Serializer):
def test(self) -> None:
ret = ReturnList(["1"], serializer=self)
callable, args = ret.__reduce__()
reveal_type(callable(*args)) # N: Revealed type is "builtins.list[builtins.str]"
- case: test_return_list_serializer_argument_is_kw_only
parametrized:
- arg: ""
err: No overload variant of "ReturnList" matches argument type "TestSerializer"
- arg: "[],"
err: No overload variant of "ReturnList" matches argument types "List[Never]", "TestSerializer"
main: |
from rest_framework import serializers
from rest_framework.utils.serializer_helpers import ReturnList
class TestSerializer(serializers.Serializer):
def test(self) -> None:
ReturnList({{ arg }} self)
out: |
main:6: error: {{ err }}
main:6: note: Possible overload variants:
main:6: note: def [_T] ReturnList(self, *, serializer: BaseSerializer[Any]) -> ReturnList[_T]
main:6: note: def [_T] ReturnList(self, Iterable[_T], /, *, serializer: BaseSerializer[Any]) -> ReturnList[_T]
- case: test_return_list_serializer_is_required
parametrized:
- arg: ""
err: All overload variants of "ReturnList" require at least one argument
- arg: "[]"
err: No overload variant of "ReturnList" matches argument type "List[Never]"
main: |
from rest_framework import serializers
from rest_framework.utils.serializer_helpers import ReturnList
class TestSerializer(serializers.Serializer):
def test(self) -> None:
ReturnList({{ arg }})
out: |
main:6: error: {{ err }}
main:6: note: Possible overload variants:
main:6: note: def [_T] ReturnList(self, *, serializer: BaseSerializer[Any]) -> ReturnList[_T]
main:6: note: def [_T] ReturnList(self, Iterable[_T], /, *, serializer: BaseSerializer[Any]) -> ReturnList[_T]
- case: test_return_dict
main: |
from rest_framework import serializers
from rest_framework.utils.serializer_helpers import ReturnDict
from typing import Mapping
class TestSerializer(serializers.Serializer):
def test(self) -> None:
input: Mapping[str, str] = {}
ReturnDict({}, serializer=self)
ReturnDict([("a", "a")], serializer=self)
ReturnDict(input, serializer=self)
iterable = ""
sep = " "
ReturnDict((string.split(sep) for string in iterable), serializer=self)
ReturnDict(serializer=self)
ret = ReturnDict({"a": "a"}, serializer=self)
reveal_type(ret) # N: Revealed type is "rest_framework.utils.serializer_helpers.ReturnDict[builtins.str, builtins.str]"
copy = ret.copy()
reveal_type(copy) # N: Revealed type is "rest_framework.utils.serializer_helpers.ReturnDict[builtins.str, builtins.str]"
- case: test_return_dict_reduce
main: |
from rest_framework import serializers
from rest_framework.utils.serializer_helpers import ReturnDict
class TestSerializer(serializers.Serializer):
def test(self) -> None:
ret = ReturnDict({"a": "1"}, serializer=self)
callable, args = ret.__reduce__()
reveal_type(callable(*args)) # N: Revealed type is "builtins.dict[builtins.str, builtins.str]"
- case: test_return_dict_serializer_argument_is_kw_only
parametrized:
- arg: ""
err: No overload variant of "ReturnDict" matches argument type "TestSerializer"
- arg: "{},"
err: No overload variant of "ReturnDict" matches argument types "Dict[Never, Never]", "TestSerializer"
- arg: "[],"
err: No overload variant of "ReturnDict" matches argument types "List[Never]", "TestSerializer"
- arg: "[('a', 'a')],"
err: No overload variant of "ReturnDict" matches argument types "List[Tuple[str, str]]", "TestSerializer"
main: |
from rest_framework import serializers
from rest_framework.utils.serializer_helpers import ReturnDict
class TestSerializer(serializers.Serializer):
def test(self) -> None:
ReturnDict({{ arg }} self)
out: |
main:6: error: {{ err }}
main:6: note: Possible overload variants:
main:6: note: def [_KT, _VT] ReturnDict(self, *, serializer: BaseSerializer[Any]) -> ReturnDict[_KT, _VT]
main:6: note: def [_KT, _VT] ReturnDict(self, *, serializer: BaseSerializer[Any], **kwargs: _VT) -> ReturnDict[str, _VT]
main:6: note: def [_KT, _VT] ReturnDict(self, SupportsKeysAndGetItem[_KT, _VT], /, *, serializer: BaseSerializer[Any]) -> ReturnDict[_KT, _VT]
main:6: note: def [_KT, _VT] ReturnDict(self, SupportsKeysAndGetItem[str, _VT], /, *, serializer: BaseSerializer[Any], **kwargs: _VT) -> ReturnDict[str, _VT]
main:6: note: def [_KT, _VT] ReturnDict(self, Iterable[Tuple[_KT, _VT]], /, *, serializer: BaseSerializer[Any]) -> ReturnDict[_KT, _VT]
main:6: note: def [_KT, _VT] ReturnDict(self, Iterable[Tuple[str, _VT]], /, *, serializer: BaseSerializer[Any], **kwargs: _VT) -> ReturnDict[str, _VT]
main:6: note: def [_KT, _VT] ReturnDict(self, Iterable[List[str]], /, *, serializer: BaseSerializer[Any]) -> ReturnDict[str, str]
main:6: note: def [_KT, _VT] ReturnDict(self, Iterable[List[bytes]], /, *, serializer: BaseSerializer[Any]) -> ReturnDict[bytes, bytes]
- case: test_return_dict_serializer_is_required
parametrized:
- arg: ""
err: All overload variants of "ReturnDict" require at least one argument
- arg: "{}"
err: No overload variant of "ReturnDict" matches argument type "Dict[Never, Never]"
- arg: "[]"
err: No overload variant of "ReturnDict" matches argument type "List[Never]"
- arg: "[('a', 'a')]"
err: No overload variant of "ReturnDict" matches argument type "List[Tuple[str, str]]"
main: |
from rest_framework import serializers
from rest_framework.utils.serializer_helpers import ReturnDict
class TestSerializer(serializers.Serializer):
def test(self) -> None:
ReturnDict({{ arg }})
out: |
main:6: error: {{ err }}
main:6: note: Possible overload variants:
main:6: note: def [_KT, _VT] ReturnDict(self, *, serializer: BaseSerializer[Any]) -> ReturnDict[_KT, _VT]
main:6: note: def [_KT, _VT] ReturnDict(self, *, serializer: BaseSerializer[Any], **kwargs: _VT) -> ReturnDict[str, _VT]
main:6: note: def [_KT, _VT] ReturnDict(self, SupportsKeysAndGetItem[_KT, _VT], /, *, serializer: BaseSerializer[Any]) -> ReturnDict[_KT, _VT]
main:6: note: def [_KT, _VT] ReturnDict(self, SupportsKeysAndGetItem[str, _VT], /, *, serializer: BaseSerializer[Any], **kwargs: _VT) -> ReturnDict[str, _VT]
main:6: note: def [_KT, _VT] ReturnDict(self, Iterable[Tuple[_KT, _VT]], /, *, serializer: BaseSerializer[Any]) -> ReturnDict[_KT, _VT]
main:6: note: def [_KT, _VT] ReturnDict(self, Iterable[Tuple[str, _VT]], /, *, serializer: BaseSerializer[Any], **kwargs: _VT) -> ReturnDict[str, _VT]
main:6: note: def [_KT, _VT] ReturnDict(self, Iterable[List[str]], /, *, serializer: BaseSerializer[Any]) -> ReturnDict[str, str]
main:6: note: def [_KT, _VT] ReturnDict(self, Iterable[List[bytes]], /, *, serializer: BaseSerializer[Any]) -> ReturnDict[bytes, bytes]
07070100000081000081A4000000000000000000000001687648C5000004A1000000000000000000000000000000000000003F00000000djangorestframework-stubs-3.16.1/tests/typecheck/test_test.yml- case: test_testcases_client_api
parametrized:
- test_class: APITransactionTestCase
- test_class: APITestCase
- test_class: APISimpleTestCase
- test_class: APILiveServerTestCase
main: |
from rest_framework import test, status
class MyTest(test.{{ test_class }}):
def test_example(self) -> None:
reveal_type(self.client) # N: Revealed type is "rest_framework.test.APIClient"
response = self.client.get('/', format="json")
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
self.assertEqual(response.data, {"detail": {"not_found"}})
- case: test_testcases_client_api_urlpatterns
main: |
from typing import Union, List
from django.urls import URLPattern, URLResolver
from rest_framework import test, status
class MyTest(test.URLPatternsTestCase):
urlpatterns : List[Union[URLPattern, URLResolver]] = []
def test_example(self) -> None:
reveal_type(self.client) # N: Revealed type is "django.test.client.Client"
response = self.client.get('/', format="json")
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
07070100000082000081A4000000000000000000000001687648C50000089B000000000000000000000000000000000000004000000000djangorestframework-stubs-3.16.1/tests/typecheck/test_views.yml- case: test_view_request_type
main: |
from typing import Any
from django.db.models import QuerySet
from rest_framework import generics
class MyListView(generics.ListAPIView):
def filter_queryset(self, queryset: QuerySet[Any]) -> QuerySet[Any]:
reveal_type(self.request) # N: Revealed type is "rest_framework.request.Request"
return queryset
- case: test_destroy_api_view
main: |
from rest_framework import generics
from myapp.models import MyModel
class MyView(generics.DestroyAPIView):
queryset = MyModel.objects.all()
def perform_destroy(self, instance: MyModel) -> None: ...
installed_apps:
- myapp
files:
- path: myapp/__init__.py
- path: myapp/models.py
content: |
from django.db import models
class MyModel(models.Model):
pass
- case: test_build_api_request
main: |
from django.http.request import HttpRequest
from rest_framework.views import APIView
request: HttpRequest
view: APIView
api_request = view.initialize_request(request)
reveal_type(api_request) # N: Revealed type is "rest_framework.request.Request"
- case: test_generics_of_extended_generic_view
main: |
from rest_framework import generics
from django.db.models import Model
class MyModel(Model):
pass
class MyRetrieveView(generics.RetrieveAPIView[MyModel]):
pass
reveal_type(MyRetrieveView().get_object()) # N: Revealed type is "main.MyModel"
- case: test_generics_of_extended_generic_view_set
main: |
from rest_framework import viewsets
from django.db.models import Model
class MyModel(Model):
pass
class MyRetrieveViewSet(viewsets.GenericViewSet[MyModel]):
pass
reveal_type(MyRetrieveViewSet().get_object()) # N: Revealed type is "main.MyModel"
- case: test_override_get_permissions
main: |
from typing import List
from rest_framework.viewsets import GenericViewSet
from rest_framework.permissions import BasePermission
class MyView(GenericViewSet):
def get_permissions(self) -> List[BasePermission]:
...
07070100000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000B00000000TRAILER!!!456 blocks