Skip to content

Commit

Permalink
Merge branch 'encode:master' into jsonencoder_ipaddress
Browse files Browse the repository at this point in the history
  • Loading branch information
corenting committed Oct 29, 2023
2 parents d403188 + f56b85b commit 277e04a
Show file tree
Hide file tree
Showing 30 changed files with 137 additions and 91 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ jobs:
- '3.11'

steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4

- uses: actions/setup-python@v4
with:
Expand Down
7 changes: 7 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,10 @@ repos:
- id: flake8
additional_dependencies:
- flake8-tidy-imports
- repo: https://github.com/adamchainz/blacken-docs
rev: 1.13.0
hooks:
- id: blacken-docs
exclude: ^(?!docs).*$
additional_dependencies:
- black==23.1.0
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Contributing to REST framework

At this point in it's lifespan we consider Django REST framework to be essentially feature-complete. We may accept pull requests that track the continued development of Django versions, but would prefer not to accept new features or code formatting changes.
At this point in its lifespan we consider Django REST framework to be essentially feature-complete. We may accept pull requests that track the continued development of Django versions, but would prefer not to accept new features or code formatting changes.

Apart from minor documentation changes, the [GitHub discussions page](https://github.com/encode/django-rest-framework/discussions) should generally be your starting point. Please only raise an issue or pull request if you've been recommended to do so after discussion.

Expand Down
2 changes: 1 addition & 1 deletion docs/api-guide/authentication.md
Original file line number Diff line number Diff line change
Expand Up @@ -454,7 +454,7 @@ More information can be found in the [Documentation](https://django-rest-durin.r
[basicauth]: https://tools.ietf.org/html/rfc2617
[permission]: permissions.md
[throttling]: throttling.md
[csrf-ajax]: https://docs.djangoproject.com/en/stable/ref/csrf/#ajax
[csrf-ajax]: https://docs.djangoproject.com/en/stable/howto/csrf/#using-csrf-protection-with-ajax
[mod_wsgi_official]: https://modwsgi.readthedocs.io/en/develop/configuration-directives/WSGIPassAuthorization.html
[django-oauth-toolkit-getting-started]: https://django-oauth-toolkit.readthedocs.io/en/latest/rest-framework/getting_started.html
[django-rest-framework-oauth]: https://jpadilla.github.io/django-rest-framework-oauth/
Expand Down
16 changes: 8 additions & 8 deletions docs/api-guide/caching.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,33 +28,33 @@ from rest_framework import viewsets

class UserViewSet(viewsets.ViewSet):
# With cookie: cache requested url for each user for 2 hours
@method_decorator(cache_page(60*60*2))
@method_decorator(cache_page(60 * 60 * 2))
@method_decorator(vary_on_cookie)
def list(self, request, format=None):
content = {
'user_feed': request.user.get_user_feed()
"user_feed": request.user.get_user_feed(),
}
return Response(content)


class ProfileView(APIView):
# With auth: cache requested url for each user for 2 hours
@method_decorator(cache_page(60*60*2))
@method_decorator(vary_on_headers("Authorization",))
@method_decorator(cache_page(60 * 60 * 2))
@method_decorator(vary_on_headers("Authorization"))
def get(self, request, format=None):
content = {
'user_feed': request.user.get_user_feed()
"user_feed": request.user.get_user_feed(),
}
return Response(content)


class PostView(APIView):
# Cache page for the requested url
@method_decorator(cache_page(60*60*2))
@method_decorator(cache_page(60 * 60 * 2))
def get(self, request, format=None):
content = {
'title': 'Post title',
'body': 'Post content'
"title": "Post title",
"body": "Post content",
}
return Response(content)
```
Expand Down
26 changes: 16 additions & 10 deletions docs/api-guide/schemas.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,11 +94,13 @@ urlpatterns = [
# Use the `get_schema_view()` helper to add a `SchemaView` to project URLs.
# * `title` and `description` parameters are passed to `SchemaGenerator`.
# * Provide view name for use with `reverse()`.
path('openapi', get_schema_view(
title="Your Project",
description="API for all things …",
version="1.0.0"
), name='openapi-schema'),
path(
"openapi",
get_schema_view(
title="Your Project", description="API for all things …", version="1.0.0"
),
name="openapi-schema",
),
# ...
]
```
Expand Down Expand Up @@ -259,11 +261,13 @@ class CustomSchema(AutoSchema):
"""
AutoSchema subclass using schema_extra_info on the view.
"""

...


class CustomView(APIView):
schema = CustomSchema()
schema_extra_info = ... some extra info ...
schema_extra_info = ... # some extra info
```

Here, the `AutoSchema` subclass goes looking for `schema_extra_info` on the
Expand All @@ -278,10 +282,13 @@ class BaseSchema(AutoSchema):
"""
AutoSchema subclass that knows how to use extra_info.
"""

...


class CustomSchema(BaseSchema):
extra_info = ... some extra info ...
extra_info = ... # some extra info


class CustomView(APIView):
schema = CustomSchema()
Expand All @@ -302,10 +309,9 @@ class CustomSchema(BaseSchema):
self.extra_info = kwargs.pop("extra_info")
super().__init__(**kwargs)


class CustomView(APIView):
schema = CustomSchema(
extra_info=... some extra info ...
)
schema = CustomSchema(extra_info=...) # some extra info
```

This saves you having to create a custom subclass per-view for a commonly used option.
Expand Down
6 changes: 6 additions & 0 deletions docs/api-guide/settings.md
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,12 @@ The string that should used for any versioning parameters, such as in the media

Default: `'version'`

#### DEFAULT_VERSIONING_CLASS

The default versioning scheme to use.

Default: `None`

---

## Authentication settings
Expand Down
25 changes: 13 additions & 12 deletions docs/api-guide/viewsets.md
Original file line number Diff line number Diff line change
Expand Up @@ -201,15 +201,16 @@ To view all extra actions, call the `.get_extra_actions()` method.
Extra actions can map additional HTTP methods to separate `ViewSet` methods. For example, the above password set/unset methods could be consolidated into a single route. Note that additional mappings do not accept arguments.

```python
@action(detail=True, methods=['put'], name='Change Password')
def password(self, request, pk=None):
"""Update the user's password."""
...

@password.mapping.delete
def delete_password(self, request, pk=None):
"""Delete the user's password."""
...
@action(detail=True, methods=["put"], name="Change Password")
def password(self, request, pk=None):
"""Update the user's password."""
...


@password.mapping.delete
def delete_password(self, request, pk=None):
"""Delete the user's password."""
...
```

## Reversing action URLs
Expand All @@ -220,14 +221,14 @@ Note that the `basename` is provided by the router during `ViewSet` registration

Using the example from the previous section:

```python
>>> view.reverse_action('set-password', args=['1'])
```pycon
>>> view.reverse_action("set-password", args=["1"])
'http://localhost:8000/api/users/1/set_password'
```

Alternatively, you can use the `url_name` attribute set by the `@action` decorator.

```python
```pycon
>>> view.reverse_action(view.set_password.url_name, args=['1'])
'http://localhost:8000/api/users/1/set_password'
```
Expand Down
13 changes: 7 additions & 6 deletions docs/community/3.10-announcement.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ update your REST framework settings to include `DEFAULT_SCHEMA_CLASS` explicitly

```python
REST_FRAMEWORK = {
...
'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema'
...: ...,
"DEFAULT_SCHEMA_CLASS": "rest_framework.schemas.coreapi.AutoSchema",
}
```

Expand Down Expand Up @@ -74,10 +74,11 @@ urlpatterns = [
# Use the `get_schema_view()` helper to add a `SchemaView` to project URLs.
# * `title` and `description` parameters are passed to `SchemaGenerator`.
# * Provide view name for use with `reverse()`.
path('openapi', get_schema_view(
title="Your Project",
description="API for all things …"
), name='openapi-schema'),
path(
"openapi",
get_schema_view(title="Your Project", description="API for all things …"),
name="openapi-schema",
),
# ...
]
```
Expand Down
9 changes: 5 additions & 4 deletions docs/community/3.11-announcement.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,11 @@ be extracted from the class docstring:

```python
class DocStringExampleListView(APIView):
"""
get: A description of my GET operation.
post: A description of my POST operation.
"""
"""
get: A description of my GET operation.
post: A description of my POST operation.
"""

permission_classes = [permissions.IsAuthenticatedOrReadOnly]

def get(self, request, *args, **kwargs):
Expand Down
12 changes: 7 additions & 5 deletions docs/community/3.12-announcement.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ The tags used for a particular view may also be overridden...

```python
class MyOrders(APIView):
schema = AutoSchema(tags=['users', 'orders'])
schema = AutoSchema(tags=["users", "orders"])
...
```

Expand All @@ -68,7 +68,7 @@ may be overridden if needed](https://www.django-rest-framework.org/api-guide/sch

```python
class MyOrders(APIView):
schema = AutoSchema(component_name="OrderDetails")
schema = AutoSchema(component_name="OrderDetails")
```

## More Public API
Expand Down Expand Up @@ -118,10 +118,11 @@ class SitesSearchView(generics.ListAPIView):
by a search against the site name or location. (Location searches are
matched against the region and country names.)
"""

queryset = Sites.objects.all()
serializer_class = SitesSerializer
filter_backends = [filters.SearchFilter]
search_fields = ['site_name', 'location__region', 'location__country']
search_fields = ["site_name", "location__region", "location__country"]
```

### Searches against annotate fields
Expand All @@ -135,10 +136,11 @@ class PublisherSearchView(generics.ListAPIView):
Search for publishers, optionally filtering the search against the average
rating of all their books.
"""
queryset = Publisher.objects.annotate(avg_rating=Avg('book__rating'))

queryset = Publisher.objects.annotate(avg_rating=Avg("book__rating"))
serializer_class = PublisherSerializer
filter_backends = [filters.SearchFilter]
search_fields = ['avg_rating']
search_fields = ["avg_rating"]
```

---
Expand Down
11 changes: 4 additions & 7 deletions docs/community/3.9-announcement.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,15 +65,12 @@ from rest_framework.renderers import JSONOpenAPIRenderer
from django.urls import path

schema_view = get_schema_view(
title='Server Monitoring API',
url='https://www.example.org/api/',
renderer_classes=[JSONOpenAPIRenderer]
title="Server Monitoring API",
url="https://www.example.org/api/",
renderer_classes=[JSONOpenAPIRenderer],
)

urlpatterns = [
path('schema.json', schema_view),
...
]
urlpatterns = [path("schema.json", schema_view), ...]
```

And here's how you can use the `generateschema` management command:
Expand Down
6 changes: 5 additions & 1 deletion docs/community/release-notes.md
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,11 @@ Be sure to upgrade to Python 3 before upgrading to Django REST Framework 3.10.
class NullableCharField(serializers.CharField):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.validators = [v for v in self.validators if not isinstance(v, ProhibitNullCharactersValidator)]
self.validators = [
v
for v in self.validators
if not isinstance(v, ProhibitNullCharactersValidator)
]
```
* Add `OpenAPIRenderer` and `generate_schema` management command. [#6229][gh6229]
* Add OpenAPIRenderer by default, and add schema docs. [#6233][gh6233]
Expand Down
5 changes: 5 additions & 0 deletions docs/community/tutorials-and-resources.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ There are a wide range of resources available for learning and using Django REST
</a>
</div>

## Courses

* [Developing RESTful APIs with Django REST Framework][developing-restful-apis-with-django-rest-framework]

## Tutorials

* [Beginner's Guide to the Django REST Framework][beginners-guide-to-the-django-rest-framework]
Expand Down Expand Up @@ -130,3 +134,4 @@ Want your Django REST Framework talk/tutorial/article to be added to our website
[pycon-us-2017]: https://www.youtube.com/watch?v=Rk6MHZdust4
[django-rest-react-valentinog]: https://www.valentinog.com/blog/tutorial-api-django-rest-react/
[doordash-implementing-rest-apis]: https://doordash.engineering/2013/10/07/implementing-rest-apis-with-embedded-privacy/
[developing-restful-apis-with-django-rest-framework]: https://testdriven.io/courses/django-rest-framework/
2 changes: 1 addition & 1 deletion docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ continued development by **[signing up for a paid plan][funding]**.
REST framework requires the following:

* Python (3.6, 3.7, 3.8, 3.9, 3.10, 3.11)
* Django (3.0, 3.1, 3.2, 4.0, 4.1)
* Django (3.0, 3.1, 3.2, 4.0, 4.1, 4.2)

We **highly recommend** and only officially support the latest patch release of
each Python and Django series.
Expand Down
2 changes: 1 addition & 1 deletion docs/topics/ajax-csrf-cors.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ The best way to deal with CORS in REST framework is to add the required response

[cite]: https://blog.codinghorror.com/preventing-csrf-and-xsrf-attacks/
[csrf]: https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)
[csrf-ajax]: https://docs.djangoproject.com/en/stable/ref/csrf/#ajax
[csrf-ajax]: https://docs.djangoproject.com/en/stable/howto/csrf/#using-csrf-protection-with-ajax
[cors]: https://www.w3.org/TR/cors/
[adamchainz]: https://github.com/adamchainz
[django-cors-headers]: https://github.com/adamchainz/django-cors-headers
23 changes: 15 additions & 8 deletions docs/topics/documenting-your-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,10 +96,14 @@ urlpatterns = [
# ...
# Route TemplateView to serve Swagger UI template.
# * Provide `extra_context` with view name of `SchemaView`.
path('swagger-ui/', TemplateView.as_view(
template_name='swagger-ui.html',
extra_context={'schema_url':'openapi-schema'}
), name='swagger-ui'),
path(
"swagger-ui/",
TemplateView.as_view(
template_name="swagger-ui.html",
extra_context={"schema_url": "openapi-schema"},
),
name="swagger-ui",
),
]
```

Expand Down Expand Up @@ -145,10 +149,13 @@ urlpatterns = [
# ...
# Route TemplateView to serve the ReDoc template.
# * Provide `extra_context` with view name of `SchemaView`.
path('redoc/', TemplateView.as_view(
template_name='redoc.html',
extra_context={'schema_url':'openapi-schema'}
), name='redoc'),
path(
"redoc/",
TemplateView.as_view(
template_name="redoc.html", extra_context={"schema_url": "openapi-schema"}
),
name="redoc",
),
]
```

Expand Down
2 changes: 1 addition & 1 deletion requirements/requirements-documentation.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# MkDocs to build our documentation.
mkdocs>=1.1.2,<1.2
mkdocs==1.2.4
jinja2>=2.10,<3.1.0 # contextfilter has been renamed

# pylinkvalidator to check for broken links in documentation.
Expand Down
Loading

0 comments on commit 277e04a

Please sign in to comment.