Django rest framework запросы
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
Урок 2: Запросы и ответы
С этого момента мы начнем изучать ядро DRF. Давайте рассмотрим пару основных блоков.
Также DRF предоставляет объект Response, являющийся расширением TemplateResponse, который берет сырые данные и использует их для определения и формирование правильного типа контента, возвращаемого клиенту.
DRF предоставляет два способа обозначения представлений API:
- декоратор @api_view для работы с представлениями-функциями;
- класс APIView для наследования при работе с представлениями-классами.
Эти способы обозначения добавляют некоторый функционал в представления. Например, они всегда преобразуют запрос в объект Request , или добавляют контекст в объект Response , чтобы можно было согласовать контент.
Так же они предоставляют такой функционал, как возврат 405 Method Not Allowed ответа, когда это необходимо, и обработку ошибок ParseError , когда данные в request.data неверно сформированы.
Собираем все вместе
Давайте начнем использовать эти компоненты, чтобы написать несколько представлений.
Мы больше не нуждаемся в классе JSONResponse в модуле views.py , так что можно его удалить. Когда это будет сделано, мы можем продолжить переписывать наши представления.
Это более корректное описание нашего представления. Теперь оно более понятно и код стал больше походить на то, как мы работаем с формами. Также мы используем коды статусов, что делает код более наглядным.
Здесь у нас представление отдельного сниппета.
Это не должно быть слишком сложным для понимания - оно практически не отличается от работы с обычными Django представлениями.
Обратите внимание, что мы больше не привязываем наши запросы и ответы к определенному типу контента. Request.data может обрабатывать входящие запросы как в формате json, так и в других форматах. Точно так же мы возвращаем объекты Response с данными, но позволяем DRF формировать данные в правильный тип.
Добавление определителей формата в URL
Начнем с того, что добавим именованный параметр к нашим представлениям
Теперь необходимо обновить urls.py , добавив format_suffix_patterns в дополнение к уже имеющимся представлениям.
Нам не нужно добавлять еще один параметр URL - у нас есть возможность просто и аккуратно сослаться на необходимый формат.
Как это выглядит
Проверьте работу API из командной строки, как это делалось в Уроке 1. Все работает одинаково, при этом мы получили улучшенную обработку ошибок в случае отправки неверных запросов.
Мы можем получить список всех сниппетов, как и раньше.
Мы можем управлять форматом ответа, используя заголовок Accept :
Или с помощью добавления в конец расширения файла для формата:
Так же мы можем управлять форматом запроса, который мы отправили, используя заголовок Content-Type .
Если вы используете ключ --debug , вы сможете увидеть тип запроса в заголовках запроса.
Поскольку API выбирает тип ответа, основываясь на запросе клиента, оно будет, по умолчанию, возвращать HTML версию запрашиваемого ресурса, когда запрос будет происходить из браузера. Это позволяет API формировать полностью браузерную версию данных.
Иметь браузерную версию API - огромное преимущество, поскольку значительно облегчает разработку. Также, это снижает порог входа в разработку как разрабатывающим API, так и разрабатывающим клиенты на основе этого API.
В уроке 3, мы будем использовать представления-классы(class-based views, CBV) и посмотрим, как встроенные представления уменьшат количество необходимого кода.
From this point we're going to really start covering the core of REST framework. Let's introduce a couple of essential building blocks.
.method
Browser-based PUT , PATCH and DELETE forms are transparently supported.
.status_code
Browsability
Because the API chooses the content type of the response based on the client request, it will, by default, return an HTML-formatted representation of the resource when that resource is requested by a web browser. This allows for the API to return a fully web-browsable HTML representation.
Having a web-browsable API is a huge usability win, and makes developing and using your API much easier. It also dramatically lowers the barrier-to-entry for other developers wanting to inspect and work with your API.
See the browsable api topic for more information about the browsable API feature and how to customize it.
.renderer_context
A dictionary of additional context information that will be passed to the renderer's .render() method.
Set automatically by the APIView or @api_view immediately before the response is returned from the view.
The Response class extends SimpleTemplateResponse , and all the usual attributes and methods are also available on the response. For example you can set headers on the response in the standard way:
Response()
The renderers used by the Response class cannot natively handle complex datatypes such as Django model instances, so you need to serialize the data into primitive datatypes before creating the Response object.
You can use REST framework's Serializer classes to perform this data serialization, or use your own custom serialization.
The unrendered, serialized data of the response.
.render()
As with any other TemplateResponse , this method is called to render the serialized data of the response into the final response content. When .render() is called, the response content will be set to the result of calling the .render(data, accepted_media_type, renderer_context) method on the accepted_renderer instance.
You won't typically need to call .render() yourself, as it's handled by Django's standard response cycle.
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
Руководство 2: Запросы и Ответы
В этой части руководства мы начнем с основ REST фреймворка. Позвольте представить основные строительные блоки фреймворка.
REST фрeймворк также использует объект Response , который похож на TemplateResponse принимающий необработанный контент и использующий согласование содержания чтобы определить правильный тип контента для того, чтобы вернуть клиенту.
Оборачиваем API views
REST фреймворк предоставляет два способа обернуть API views.
- Декоратор @api_view для работы с view на основе функций.
- Класс APIView для работы с view на основе классов.
Эти обертки предоставляют некоторую функциональность: возможность убедится, что вы получили экземпляр Request в вашем view, и добавление контекста в объект Response так, что согласование содержимого может быть произведено.
Обертывание также позволяет вернуть при случае ответы 405 Method Not Allowed и обработать любое ParseError исключение которое появляется при доступе к request.data с испорченными данными.
Объеденим все вместе
Хорошо, давайте пойдем дальше и начнем использовать эти новые компоненты чтобы написать несколько views.
У нас нет больше нужды в нашем классе JSONResponse во views.py , так что удалим его. После этого мы можем начать рефакторить наше view.
Это view для отдельного снипета, в модуле views.py .
Должно быть это все очень знакомо, потому что тут нет больших отличий от обычный Django views.
Заметьте, что мы теперь не явно связываем наши запросы или ответы с типом контента. request.data может обрабатывать входящие json запросы, но также он может обрабатывать и другие форматы. Аналогично мы возвращаем объекты ответа с данными, но позволяем REST фреймворку обработать ответ в нужный тип контента для нас.
Добавление опционального расширения для урла
Начнем с добавления аргумента format к обоим views
Теперь обновим немного файл urls.py добавив набор format_suffix_patterns к существующим урлам.
Не обязательно добавлять эти дополнительные паттерны, но это дает нам простой и ясный путь к назначению определенных форматов.
Как это выглядит?
Давайте протестируем наше API в командной строке, как мы делали в первой части руководства. Все работает очень похоже, но если мы отправил неверный запрос, то получим обработчик ошибок.
Мы можем получить список всех снипетов как и прежде.
Мы можем контролировать формат ответа используя хедер Accept :
Или добавлением расширения:
Подобно, мы можем контролировать формат запроса, используя хедер Content-Type .
Так как API выбрало тип контента ответа на основе клиентского запроса, то по умолчанию, вернет HTML отфарматированный ресурс когда он будет вызван веб браузером. Это позволяет API возвращать полностью веб ориентированное представление.
Обладание вебориентированным API это большая пользовательская победа, которая делает разработку и использование API на много проще. Это также низкий барьер вхождения для других разработчиков которые захотят посмотреть и использовать это API.
Смотри тему api в браузере для дополнительной информации о фичах вебориентированного API и как его адаптированить под свои нужды.
В части третьей мы начнем использовать views на основе классов и увидим как общие view сокращают количество кода.
.accepted_renderer
The renderer instance that will be used to render the response.
Set automatically by the APIView or @api_view immediately before the response is returned from the view.
.query_params
request.query_params is a more correctly named synonym for request.GET .
.parsers
The APIView class or @api_view decorator will ensure that this property is automatically set to a list of Parser instances, based on the parser_classes set on the view or based on the DEFAULT_PARSER_CLASSES setting.
You won't typically need to access this property.
Note: If a client sends malformed content, then accessing request.data may raise a ParseError . By default REST framework's APIView class or @api_view decorator will catch the error and return a 400 Bad Request response.
If a client sends a request with a content-type that cannot be parsed then a UnsupportedMediaType exception will be raised, which by default will be caught and return a 415 Unsupported Media Type response.
The request exposes some properties that allow you to determine the result of the content negotiation stage. This allows you to implement behaviour such as selecting a different serialization schemes for different media types.
.template_name
The template_name , if supplied. Only required if HTMLRenderer or some other custom template renderer is the accepted renderer for the response.
Response objects
REST framework also introduces a Response object, which is a type of TemplateResponse that takes unrendered content and uses content negotiation to determine the correct content type to return to the client.
.authenticators
The APIView class or @api_view decorator will ensure that this property is automatically set to a list of Authentication instances, based on the authentication_classes set on the view or based on the DEFAULT_AUTHENTICATORS setting.
You won't typically need to access this property.
REST framework supports a few browser enhancements such as browser-based PUT , PATCH and DELETE forms.
Status codes
.accepted_media_type
The media type that was selected by the content negotiation stage.
Set automatically by the APIView or @api_view immediately before the response is returned from the view.
.accepted_renderer
The renderer instance that was selected by the content negotiation stage.
How's it looking?
Go ahead and test the API from the command line, as we did in tutorial part 1. Everything is working pretty similarly, although we've got some nicer error handling if we send invalid requests.
We can get a list of all of the snippets, as before.
We can control the format of the response that we get back, either by using the Accept header:
Or by appending a format suffix:
Similarly, we can control the format of the request that we send, using the Content-Type header.
Pulling it all together
Okay, let's go ahead and start using these new components to refactor our views slightly.
Our instance view is an improvement over the previous example. It's a little more concise, and the code now feels very similar to if we were working with the Forms API. We're also using named status codes, which makes the response meanings more obvious.
Here is the view for an individual snippet, in the views.py module.
This should all feel very familiar - it is not a lot different from working with regular Django views.
Notice that we're no longer explicitly tying our requests or responses to a given content type. request.data can handle incoming json requests, but it can also handle other formats. Similarly we're returning response objects with data, but allowing REST framework to render the response into the correct content type for us.
.content
The rendered content of the response. The .render() method must have been called before .content can be accessed.
What's next?
In tutorial part 3, we'll start using class-based views, and see how generic views reduce the amount of code we need to write.
If you're doing REST-based web service stuff . you should ignore request.POST.
— Malcom Tredinnick, Django developers group
REST framework's Request objects provide flexible request parsing that allows you to treat requests with JSON data or other media types in the same way that you would normally deal with form data.
request.data returns the parsed content of the request body. This is similar to the standard request.POST and request.FILES attributes except that:
For more details see the parsers documentation.
Wrapping API views
REST framework provides two wrappers you can use to write API views.
- The @api_view decorator for working with function based views.
- The APIView class for working with class-based views.
These wrappers provide a few bits of functionality such as making sure you receive Request instances in your view, and adding context to Response objects so that content negotiation can be performed.
The wrappers also provide behaviour such as returning 405 Method Not Allowed responses when appropriate, and handling any ParseError exceptions that occur when accessing request.data with malformed input.
.content_type
You won't typically need to directly access the request's content type, as you'll normally rely on REST framework's default request parsing behavior.
Request objects
.stream
request.stream returns a stream representing the content of the request body.
You won't typically need to directly access the request's content, as you'll normally rely on REST framework's default request parsing behavior.
Unless you want to heavily customize REST framework for some reason, you should always use an APIView class or @api_view function for views that return Response objects. Doing so ensures that the view can perform content negotiation and select the appropriate renderer for the response, before it is returned from the view.
Adding optional format suffixes to our URLs
Start by adding a format keyword argument to both of the views, like so.
Now update the snippets/urls.py file slightly, to append a set of format_suffix_patterns in addition to the existing URLs.
We don't necessarily need to add these extra url patterns in, but it gives us a simple, clean way of referring to a specific format.
.accepted_media_type
A string representing the media type that was accepted by the content negotiation stage.
REST framework provides flexible, per-request authentication, that gives you the ability to:
- Use different authentication policies for different parts of your API.
- Support the use of multiple authentication policies.
- Provide both user and token information associated with the incoming request.
request.auth returns any additional authentication context. The exact behavior of request.auth depends on the authentication policy being used, but it may typically be an instance of the token that the request was authenticated against.
If the request is unauthenticated, or if no additional context is present, the default value of request.auth is None .
Читайте также: