Calling dict.keys() is unnecessary. The two are functionally equivalent
on modern Pythons.
Inspired by Lennart Regebro's talk "Prehistoric Patterns in Python" from
PyCon 2017.
https://www.youtube.com/watch?v=V5-JH23Vk0I
* Add failing test for #5672
* Add get_original_route to complement get_regex_pattern
* [WIP] Fix path handling
* needs more tests
* maybe needs some refactoring
* Add django 2 variant for all tests and fix trailing slash bug
* Add more combinations to mixed path test
* Extract method for `manual_fields` processing
Allows reuse of logic to replace Field instances in a field list by `Field.name`.
Adds a utility function for the logic plus a wrapper method on `AutoSchema`.
Closes#5632
* Manual fields suggestions (#2)
* Use OrderedDict in inspectors
* Move empty check to 'update_fields()'
* Make 'update_fields()' an AutoSchema staticmethod
* Add 'AutoSchema.get_manual_fields()'
* Conform '.get_manual_fields()' to other methods
* Add test for update_fields
* Make sure `manual_fields` is a list.
(As documented to be)
* Add docs for new AutoSchema methods.
* `get_manual_fields`
* `update_fields`
* Add release notes for PR.
* Update assertion style in user logout test
* Apply middlewares to django request object
* Fix test for request auth hiding AttributeErrors
* Re-raise/wrap auth attribute errors
* Fix test for py2k
* Add docs for WrappedAttributeError
* SchemaJSRenderer renders invalid Javascript
Under Py3 the base64.b64encode() method returns a binary object, which gets rendered as `b'...'` in schema.js. This results in the output becoming:
var coreJSON = window.atob('b'eyJf...'');
which is invalid Javascript. Because base64 only uses ASCII characters it is safe to decode('ascii') it. Under Py2 this will result in a unicode object, which is fine. Under Py3 it results in a string, which is also fine. This solves the problem and results in a working schema.js output.
* Add regression test for #5608
* Add regression test for #5608
* Apparently the linter on Travis wants the imports in a different order than on my box...
* Remove trailing whitespace from lines
* Remove trailing nad leading whitespace from files
Allows for cleaner diffs in future changes. For editors that
automatically clean up whitespace on save, will avoid unrelated line
changes in diffs.
Set literals are available on all supported Python versions. They are
idiomatic and always faster:
$ python3 -m timeit '{}'
10000000 loops, best of 3: 0.0357 usec per loop
$ python3 -m timeit 'dict()'
10000000 loops, best of 3: 0.104 usec per loop
$ python3 -m timeit '{1, 2, 3}'
10000000 loops, best of 3: 0.0754 usec per loop
$ python3 -m timeit 'set([1, 2, 3])'
1000000 loops, best of 3: 0.228 usec per loop
Running the tests with bytes warning enabled shows some bytes/str
mixups. Fix them all.
Some examples of mixing usage:
str(b'foo') -- calling str() on bytes
b'foo' == 'foo' -- compare str with bytes
'foo' + b'bar' -- concatenating str and bytes
* Adding rounding parameter to DecimalField.
* Using standard `assert` instead of `self.fail()`.
* add testcase and PEP8 multilines fix
* flake8 fixes
* Use decimal module constants in tests.
* Add docs note for `rounding` parameter.
When running tests with warnings enabled, appear as:
DeprecationWarning: invalid escape sequence \d
Starting with Python 3.6, invalid escape sequences are deprecated. In a
future Python versions they will be a syntax error. For more details, see:
https://docs.python.org/3/whatsnew/3.6.html#deprecated-python-behavior
> A backslash-character pair that is not a valid escape sequence now
> generates a DeprecationWarning. Although this will eventually become a
> SyntaxError, that will not be for several Python releases.
Closes#5528.
Viewset custom actions (@detail_route etc) OPTIONS (and HEAD) methods were not being excluded from Schema Generations.
This PR adds a test reproducing the reported error and adjusts `EndpointEnumerator.get_allowed_methods()` to filter ViewSet actions in the same way as other `APIView`s
* substitute '@@' code block delimiter with triple back-tick, more consistent with other markdown extensions
* remove development print and allow spaces between triple backtick and syntax name in codeblock
* update comparison content for markdown test
* Fixed issues with schema name collisions
* Fixed mutating issues in python 3
* Optimized solution
* Fixed isort
* Removed not needed cast
* Fix for key collision
* Added preferred key to preserve if available
* Add accidently removed test
* Update remaing `include` calls
Missed as part of #5481 cleanup.
* Provide app_name in include_docs_urls
* Update remaining get_regex_pattern usages
* Allow functools.partial in is_simple_callable check
* Identify code that needs to be pulled out of/removed from compat.py
* Extract modern code from get_names_and_managers in compat.py and remove compat code
* Extract modern code from is_authenticated() in compat.py and remove.
* Extract modern code from is_anonymous() in compat.py and remove
* Extract modern code from get_related_model() from compat.py and remove
* Extract modern code from value_from_object() in compat.py and remove
* Update postgres compat
JSONField now always available.
* Remove DecimalValidator compat
* Remove get_remote_field compat
* Remove template_render compat
Plus isort.
* Remove set_many compat
* Remove include compat
* add 'docstrings-with-pygments' feature without packages checks and tests
* move syntax_highlight doc filter in compatibility module and define it conditionally
* typo fixed
* add test for optional code highlight ('pygments' and 'markdown' packages must be installed)
Closes#5237
Generics/ModelViewset performs filtering on: list, retrieve, put, patch and destroy (plus method equivalents).
i.e. on list plus anything that calls `get_object`.
This PR makes schema generation follow that.
It adds `AutoSchema._allows_filters()` which can be overridden in subclasses.
I’ve made this initially “private” so we can make quick changes if needs be in a 3.7.1 etc.
## Description
The `choices` field for the `ChoiceField` class should be able to be edited after `ChoiceField.__init__` is called.
```
field = ChoiceField(choices=[1,2])
field.choices = [1] # Should no longer allow `2` as a choice
```
Currently, you must update `choices`, `grouped_choices`, and `choice_strings_to_values` to achieve this. This P/R keeps `grouped_choices` and `choice_strings_to_values` in sync whenever the `choices` are edited.
* Add tests for schema exclusions
* Move exclusion check to should_include_endpoint
* Update docs
* Switch to using `schema = None`
* Test PendingDeprecationWarnings
* Add note to release notes.
* s/deprecated/pending deprecation/
* Add PR link to release notes
* Correct typo in test class name
* Test 'exclude_from_schema' deprecation warning message (#1)
* Correct deprecation warning message
* Initial Refactor Step
* Add descriptor class
* call from generator
* proxy back to generator for implementation.
* Move `get_link` to descriptor
* Move `get_description` to descriptor
* Remove need for generator in get_description
* Move get_path_fields to descriptor
* Move `get_serializer_fields` to descriptor
* Move `get_pagination_fields` to descriptor
* Move `get_filter_fields` to descriptor
* Move `get_encoding` to descriptor.
* Pass just `url` from SchemaGenerator to descriptor
* Make `view` a property
Encapsulates check for a view instance.
* Adjust API Reference docs
* Add `ManualSchema` class
* Refactor to `ViewInspector` plus `AutoSchema`
The interface then is **just** `get_link()`
* Add `manual_fields` kwarg to AutoSchema
* Add schema decorator for FBVs
* Adjust comments
* Docs: Provide full params in example
Ref feedback b52e372f8f (r137254795)
* Add docstring for ViewInstpector.__get__ descriptor method.
Ref https://github.com/encode/django-rest-framework/pull/5354#discussion_r137265022
* Make `schemas` a package.
* Split generators, inspectors, views.
* Adjust imports
* Rename to EndpointEnumerator
* Adjust ManualSchema to take `fields`
… and `description`.
Allows `url` and `action` to remain dynamic
* Add package/module docstrings
* Add regression test for #2505. Thanks @pySilver!
* Add regression test for #5087
* Revert "Cached the field's root and context property."
This reverts commit 792005806b.
* Add test for disabling declared fields on child
* Check that declared base field is not in attrs
* Update meta inheritance docs to include serializer
* Test that meta fields cannot be declared as None
* Add docs example for declarative field disabling
* add failing testcase for breadcrumb suffixes missing when using ModelViewSets
* fix get_breadcrumbs to honor overridden get_view_name and keep viewset suffixes
* ensure suffixes are appended in breadcrumb util
To do `GROUP_BY` queries in django requires one to use `.values()`
eg this groups posts by user getting a count of posts per user.
```
Posts.objects.order_by('user').values('user').annotate(post_count=Count('post'))
```
This would produce a value queryset which serializes its result
objects as dictionaries while `CursorPagination` requires a queryset
with result objects that are model instances.
This commit enables cursor pagination for value querysets.
- had to mangle the tests a bit to test it out. They might need
some refactoring.
- tried the same for `.values_list()` but it turned out to be
trickier than I expected since you have to use tuple indexes.
Since `str` objects are immutable, appending to existing `str` creates
in fact a new `str` instance.
Thus `ErrorDetail.detail.code` attribute is lost after `str` concatenation operation.
* Start test case
* Added 'requests' test client
* Address typos
* Graceful fallback if requests is not installed.
* Add cookie support
* Tests for auth and CSRF
* Py3 compat
* py3 compat
* py3 compat
* Add get_requests_client
* Added SchemaGenerator.should_include_link
* add settings for html cutoff on related fields
* Router doesn't work if prefix is blank, though project urls.py handles prefix
* Fix Django 1.10 to-many deprecation
* Add django.core.urlresolvers compatibility
* Update django-filter & django-guardian
* Check for empty router prefix; adjust URL accordingly
It's easiest to fix this issue after we have made the regex. To try
to fix it before would require doing something different for List vs
Detail, which means we'd have to know which type of url we're
constructing before acting accordingly.
* Fix misc django deprecations
* Use TOC extension instead of header
* Fix deprecations for py3k
* Add py3k compatibility to is_simple_callable
* Add is_simple_callable tests
* Drop python 3.2 support (EOL, Dropped by Django)
* schema_renderers= should *set* the renderers, not append to them.
* API client (#4424)
* Fix release notes
* Add note about 'User account is disabled.' vs 'Unable to log in'
* Clean up schema generation (#4527)
* Handle multiple methods on custom action (#4529)
* RequestsClient, CoreAPIClient
* exclude_from_schema
* Added 'get_schema_view()' shortcut
* Added schema descriptions
* Better descriptions for schemas
* Add type annotation to schema generation
* Coerce schema 'pk' in path to actual field name
* Deprecations move into assertion errors
* Use get_schema_view in tests
* Updte CoreJSON media type
* Handle schema structure correctly when path prefixs exist. Closes#4401
* Add PendingDeprecation to Router schema generation.
* Added SCHEMA_COERCE_PATH_PK and SCHEMA_COERCE_METHOD_NAMES
* Renamed and documented 'get_schema_fields' interface.
The meta information stored in opts needs to be restored for
each search field. Otherwise it references the wrong model
when an attribute of a related model comes before an attribute
of the original model in search fields. This doesn't apply to
m2m relations since must_call_distinct returns True in that
case.
* lookup_type is deprecated in favor of lookup_expr
* assertEquals is deprecated in favor of assertEqual
* app_name is a required keyword as of Django 1.10
It is possible that a key in a MultiValueDict has multiple values, lists
are represented this way. When accessing a key in a MultiValueDict
it only returns the last element of that key. This becomes a problem
when parsing an html dict with a list inside of it.
To fix this problem we have to get and set the value using .getlist()
and .setlist().
* Exclude read_only=True fields from unique_together validation
* Test to ensure that unique_together validators can be removed
* Do not add uniquness_extra_kwargs when validators are explicitly declared.
* Add docs on validation in complex cases
* Add Meta.fields = '__all__' to serializer classes where required.
* Add explicit on_delete=models.CASCADE to ForeignKey fields.
* Use '.remote_field' and '.model' in preference to '.rel' and '.to' when inspecting model fields.
* Use new value_from_object in preference to internal _get_val_from_obj
* Added TEMPLATES setting to tests
* Remove deprecated view-string in URL conf
* Replace 'urls = ...' in test classes with override_settings('ROOT_URLCONF=...')
* Refactor UsingURLPatterns to use override_settings(ROOT_URLCONF=...) style
* Get model managers and names in a version-compatible manner.
* Apply override_settings to a TestCase, not a mixin class
* Use '.callback' property instead of private attributes when inspecting urlpatterns
* Pass 'user' to template explicitly
* Correct sorting of import statements.
* Remove unused TEMPLATE_LOADERS setting, in favor of TEMPLATES.
* Remove code style issue
* BaseFilter test requires a concrete model
* Resolve tox.ini issues
* Resolve isort differences between local and tox environments
When serializers has fields with something like `source=user.email`, the
uniqueness validator should check `email` field instead of `user`, cause
`user` is a model object.
This allows subclassing TokenAuthentication and setting custom keyword,
thus allowing the Authorization header to be for example:
Bearer 956e252a-513c-48c5-92dd-bfddc364e812
It doesn't change the behavior of TokenAuthentication itself,
it simply allows to reuse the logic of TokenAuthentication without
the need of copy pasting the class and changing one hardcoded string.
Related: #4080
Previously an extra list wrapped nested validation errors raised from serializer's validate() methods.
That was inconsistent with the format of validation errors raised by validate_<fieldname> methods.
i.e. these two resulted in *different* behaviour:
def validate_foo(self):
raise ValidationError(['bar'])
def validate(self):
raise ValidationError({'foo': ['bar']})
These two tests were previously added in
7d79cf35b7
but we have now discovered that there are not actually two separate
cases, there was just a bug in the code that made it look that way.
This also removes a redundant check to see if `DecimalValidator` was
defined.
This test was incorrectly checking that there were no validators set in
older versions of Django, even though it should have been checking for
the two validators that were set up on the model field level.
The originally regression test that this fixes was added in
7d79cf35b7
when fixing an issue with the `DecimalValidator`.
This adds tests for a regression where the `min_value` and `max_value`
arguments are not being set for a DRF `DecimalField` even though the
corresponding `MinValueValidator` and `MaxValueValidator` is being set
on the model fields.
Note that this only appears to be a regression for Django < 1.9, as
these regression tests pass on newer versions of Django.