request django что это
Documentation
Request and response objects¶
Quick overview¶
Django uses request and response objects to pass state through the system.
When a page is requested, Django creates an HttpRequest object that contains metadata about the request. Then Django loads the appropriate view, passing the HttpRequest as the first argument to the view function. Each view is responsible for returning an HttpResponse object.
This document explains the APIs for HttpRequest and HttpResponse objects, which are defined in the django.http module.
HttpRequest objects¶
Attributes¶
All attributes should be considered read-only, unless stated otherwise.
A string representing the scheme of the request ( http or https usually).
A string representing the full path to the requested page, not including the scheme, domain, or query string.
Under some web server configurations, the portion of the URL after the host name is split up into a script prefix portion and a path info portion. The path_info attribute always contains the path info portion of the path, no matter what web server is being used. Using this instead of path can make your code easier to move between test and deployment servers.
A string representing the HTTP method used in the request. This is guaranteed to be uppercase. For example:
A string representing the MIME type of the request, parsed from the CONTENT_TYPE header.
A dictionary of key/value parameters included in the CONTENT_TYPE header.
A dictionary-like object containing all given HTTP GET parameters. See the QueryDict documentation below.
A dictionary-like object containing all given HTTP POST parameters, providing that the request contains form data. See the QueryDict documentation below. If you need to access raw or non-form data posted in the request, access this through the HttpRequest.body attribute instead.
It’s possible that a request can come in via POST with an empty POST dictionary – if, say, a form is requested via the POST HTTP method but does not include form data. Therefore, you shouldn’t use if request.POST to check for use of the POST method; instead, use if request.method == «POST» (see HttpRequest.method ).
A dictionary containing all cookies. Keys and values are strings.
See Managing files for more information.
A dictionary containing all available HTTP headers. Available headers depend on the client and server, but here are some examples:
A case insensitive, dict-like object that provides access to all HTTP-prefixed headers (plus Content-Length and Content-Type ) from the request.
The name of each header is stylized with title-casing (e.g. User-Agent ) when it’s displayed. You can access headers case-insensitively:
For use in, for example, Django templates, headers can also be looked up using underscores in place of hyphens:
An instance of ResolverMatch representing the resolved URL. This attribute is only set after URL resolving took place, which means it’s available in all views but not in middleware which are executed before URL resolving takes place (you can use it in process_view() though).
Attributes set by application code¶
Django doesn’t set these attributes itself but makes use of them if set by your application.
This will be used as the root URLconf for the current request, overriding the ROOT_URLCONF setting. See How Django processes a request for details.
This will be used instead of DEFAULT_EXCEPTION_REPORTER_FILTER for the current request. See Custom error reports for details.
This will be used instead of DEFAULT_EXCEPTION_REPORTER for the current request. See Custom error reports for details.
Attributes set by middleware¶
From the SessionMiddleware : A readable and writable, dictionary-like object that represents the current session.
From the CurrentSiteMiddleware : An instance of Site or RequestSite as returned by get_current_site() representing the current site.
Methods¶
Returns the originating host of the request using information from the HTTP_X_FORWARDED_HOST (if USE_X_FORWARDED_HOST is enabled) and HTTP_HOST headers, in that order. If they don’t provide a value, the method uses a combination of SERVER_NAME and SERVER_PORT as detailed in PEP 3333.
Raises django.core.exceptions.DisallowedHost if the host is not in ALLOWED_HOSTS or the domain name is invalid according to RFC 1034/ 1035.
The get_host() method fails when the host is behind multiple proxies. One solution is to use middleware to rewrite the proxy headers, as in the following example:
Returns the originating port of the request using information from the HTTP_X_FORWARDED_PORT (if USE_X_FORWARDED_PORT is enabled) and SERVER_PORT META variables, in that order.
HttpRequest. build_absolute_uri (location=None)¶
If the location is already an absolute URI, it will not be altered. Otherwise the absolute URI is built using the server variables available in this request. For example:
Mixing HTTP and HTTPS on the same site is discouraged, therefore build_absolute_uri() will always generate an absolute URI with the same scheme the current request has. If you need to redirect users to HTTPS, it’s best to let your web server redirect all HTTP traffic to HTTPS.
Returns a cookie value for a signed cookie, or raises a django.core.signing.BadSignature exception if the signature is no longer valid. If you provide the default argument the exception will be suppressed and that default value will be returned instead.
The optional salt argument can be used to provide extra protection against brute force attacks on your secret key. If supplied, the max_age argument will be checked against the signed timestamp attached to the cookie value to ensure the cookie is not older than max_age seconds.
See cryptographic signing for more information.
Returns True if the request is secure; that is, if it was made with HTTPS.
HttpRequest. accepts (mime_type)¶
Returns True if the request Accept header matches the mime_type argument:
Most browsers send Accept: */* by default, so this would return True for all content types. Setting an explicit Accept header in API requests can be useful for returning a different content type for those consumers only. See Content negotiation example of using accepts() to return different content to API consumers.
HttpRequest. read (size=None)¶ HttpRequest. readline ()¶ HttpRequest. readlines ()¶ HttpRequest. __iter__ ()¶
Methods implementing a file-like interface for reading from an HttpRequest instance. This makes it possible to consume an incoming request in a streaming fashion. A common use-case would be to process a big XML payload with an iterative parser without constructing a whole XML tree in memory.
Given this standard interface, an HttpRequest instance can be passed directly to an XML parser such as ElementTree :
QueryDict objects¶
Methods¶
QueryDict implements all the standard dictionary methods because it’s a subclass of dictionary. Exceptions are outlined here:
QueryDict. __init__ (query_string=None, mutable=False, encoding=None)¶
If query_string is not passed in, the resulting QueryDict will be empty (it will have no keys or values).
classmethod QueryDict. fromkeys (iterable, value=», mutable=False, encoding=None)¶
QueryDict. __setitem__ (key, value)¶
Sets the given key to [value] (a list whose single element is value ). Note that this, as other dictionary functions that have side effects, can only be called on a mutable QueryDict (such as one that was created via QueryDict.copy() ).
QueryDict. __contains__ (key)¶
QueryDict. get (key, default=None)¶
QueryDict. setdefault (key, default=None)¶
QueryDict. update (other_dict)¶
In addition, QueryDict has the following methods:
QueryDict. getlist (key, default=None)¶
QueryDict. setlist (key, list_)¶
Sets the given key to list_ (unlike __setitem__() ).
QueryDict. appendlist (key, item)¶
Appends an item to the internal list associated with key.
QueryDict. setlistdefault (key, default_list=None)¶
Returns a list of values for the given key and removes them from the dictionary. Raises KeyError if the key does not exist. For example:
Removes an arbitrary member of the dictionary (since there’s no concept of ordering), and returns a two value tuple containing the key and a list of all values for the key. Raises KeyError when called on an empty dictionary. For example:
Returns a string of the data in query string format. For example:
Use the safe parameter to pass characters which don’t require encoding. For example:
HttpResponse objects¶
The HttpResponse class lives in the django.http module.
Usage¶
Passing strings¶
But if you want to add content incrementally, you can use response as a file-like object:
Passing iterators¶
Finally, you can pass HttpResponse an iterator rather than strings. HttpResponse will consume the iterator immediately, store its content as a string, and discard it. Objects with a close() method such as files and generators are immediately closed.
If you need the response to be streamed from the iterator to the client, you must use the StreamingHttpResponse class instead.
Setting header fields¶
To set or remove a header field in your response, use HttpResponse.headers :
You can also manipulate headers by treating your response like a dictionary:
When using this interface, unlike a dictionary, del doesn’t raise KeyError if the header field doesn’t exist.
You can also set headers on instantiation:
HTTP header fields cannot contain newlines. An attempt to set a header field containing a newline character (CR or LF) will raise BadHeaderError
The HttpResponse.headers interface was added.
The ability to set headers on instantiation was added.
Telling the browser to treat the response as a file attachment¶
To tell the browser to treat the response as a file attachment, set the Content-Type and Content-Disposition headers. For example, this is how you might return a Microsoft Excel spreadsheet:
There’s nothing Django-specific about the Content-Disposition header, but it’s easy to forget the syntax, so we’ve included it here.
Attributes¶
A bytestring representing the content, encoded from a string if necessary.
A string denoting the charset in which the response will be encoded. If not given at HttpResponse instantiation time, it will be extracted from content_type and if that is unsuccessful, the DEFAULT_CHARSET setting will be used.
The HTTP reason phrase for the response. It uses the HTTP standard’s default reason phrases.
This attribute exists so middleware can treat streaming responses differently from regular responses.
True if the response has been closed.
Methods¶
Instantiates an HttpResponse object with the given page content, content type, and headers.
reason is the HTTP response phrase. If not provided, a default phrase will be used.
headers is a dict of HTTP headers for the response.
The headers parameter was added.
Sets the given header name to the given value. Both header and value should be strings.
HttpResponse. __delitem__ (header)¶
Deletes the header with the given name. Fails silently if the header doesn’t exist. Case-insensitive.
HttpResponse. __getitem__ (header)¶
Returns the value for the given header name. Case-insensitive.
HttpResponse. get (header, alternate=None)¶
Returns the value for the given header, or an alternate if the header doesn’t exist.
HttpResponse. has_header (header)¶
Returns True or False based on a case-insensitive check for a header with the given name.
Acts like dict.items() for HTTP headers on the response.
HttpResponse. setdefault (header, value)¶
Sets a header unless it has already been set.
HttpResponse. set_cookie (key, value=», max_age=None, expires=None, path=’/’, domain=None, secure=False, httponly=False, samesite=None)¶
Sets a cookie. The parameters are the same as in the Morsel cookie object in the Python standard library.
max_age should be an integer number of seconds, or None (default) if the cookie should last only as long as the client’s browser session. If expires is not specified, it will be calculated.
expires should either be a string in the format «Wdy, DD-Mon-YY HH:MM:SS GMT» or a datetime.datetime object in UTC. If expires is a datetime object, the max_age will be calculated.
Use domain if you want to set a cross-domain cookie. For example, domain=»example.com» will set a cookie that is readable by the domains www.example.com, blog.example.com, etc. Otherwise, a cookie will only be readable by the domain that set it.
Use secure=True if you want the cookie to be only sent to the server when a request is made with the https scheme.
Use httponly=True if you want to prevent client-side JavaScript from having access to the cookie.
HttpOnly is a flag included in a Set-Cookie HTTP response header. It’s part of the RFC 6265 standard for cookies and can be a useful way to mitigate the risk of a client-side script accessing the protected cookie data.
Use samesite=’Strict’ or samesite=’Lax’ to tell the browser not to send this cookie when performing a cross-origin request. SameSite isn’t supported by all browsers, so it’s not a replacement for Django’s CSRF protection, but rather a defense in depth measure.
Use samesite=’None’ (string) to explicitly state that this cookie is sent with all same-site and cross-site requests.
RFC 6265 states that user agents should support cookies of at least 4096 bytes. For many browsers this is also the maximum size. Django will not raise an exception if there’s an attempt to store a cookie of more than 4096 bytes, but many browsers will not set the cookie correctly.
HttpResponse. delete_cookie (key, path=’/’, domain=None, samesite=None)¶
Deletes the cookie with the given key. Fails silently if the key doesn’t exist.
Due to the way cookies work, path and domain should be the same values you used in set_cookie() – otherwise the cookie may not be deleted.
This method is called at the end of the request directly by the WSGI server.
HttpResponse. write (content)¶
This method makes an HttpResponse instance a file-like object.
This method makes an HttpResponse instance a file-like object.
This method makes an HttpResponse instance a file-like object.
HttpResponse. writelines (lines)¶
Writes a list of lines to the response. Line separators are not added. This method makes an HttpResponse instance a stream-like object.
HttpResponse subclasses¶
The first argument to the constructor is required – the path to redirect to. This can be a fully qualified URL (e.g. ‘https://www.yahoo.com/search/’ ), an absolute path with no domain (e.g. ‘/search/’ ), or even a relative path (e.g. ‘search/’ ). In that last case, the client browser will reconstruct the full URL itself according to the current path. See HttpResponse for other optional constructor arguments. Note that this returns an HTTP status code 302.
This read-only attribute represents the URL the response will redirect to (equivalent to the Location response header).
The constructor doesn’t take any arguments and no content should be added to this response. Use this to designate that a page hasn’t been modified since the user’s last request (status code 304).
Acts just like HttpResponse but uses a 400 status code.
Acts just like HttpResponse but uses a 404 status code.
Acts just like HttpResponse but uses a 403 status code.
Acts just like HttpResponse but uses a 410 status code.
Acts just like HttpResponse but uses a 500 status code.
Custom response classes¶
JsonResponse objects¶
An HttpResponse subclass that helps to create a JSON-encoded response. It inherits most behavior from its superclass with a couple differences:
Its default Content-Type header is set to application/json.
The json_dumps_params parameter is a dictionary of keyword arguments to pass to the json.dumps() call used to generate the response.
Usage¶
Typical usage could look like:
Serializing non-dictionary objects¶
In order to serialize objects other than dict you must set the safe parameter to False :
Note that an API based on dict objects is more extensible, flexible, and makes it easier to maintain forwards compatibility. Therefore, you should avoid using non-dict objects in JSON-encoded response.
Before the 5th edition of ECMAScript it was possible to poison the JavaScript Array constructor. For this reason, Django does not allow passing non-dict objects to the JsonResponse constructor by default. However, most modern browsers implement ECMAScript 5 which removes this attack vector. Therefore it is possible to disable this security precaution.
Changing the default JSON encoder¶
If you need to use a different JSON encoder class you can pass the encoder parameter to the constructor method:
StreamingHttpResponse objects¶
Django is designed for short-lived requests. Streaming responses will tie a worker process for the entire duration of the response. This may result in poor performance.
Generally speaking, you should perform expensive tasks outside of the request-response cycle, rather than resorting to a streamed response.
StreamingHttpResponse should only be used in situations where it is absolutely required that the whole content isn’t iterated before transferring the data to the client. Because the content can’t be accessed, many middleware can’t function normally. For example the ETag and Content-Length headers can’t be generated for streaming responses.
Attributes¶
The HTTP reason phrase for the response. It uses the HTTP standard’s default reason phrases.
FileResponse objects¶
FileResponse is a subclass of StreamingHttpResponse optimized for binary files. It uses wsgi.file_wrapper if provided by the wsgi server, otherwise it streams the file out in small chunks.
FileResponse accepts any file-like object with binary content, for example a file open in binary mode like so:
The file will be closed automatically, so don’t open it with a context manager.
Methods¶
Учебник 2: Запросы и ответы¶
С этого момента мы действительно начнем освещать суть фреймворка REST. Давайте представим несколько основных строительных блоков.
Объекты запроса¶
Объекты реагирования¶
Коды состояния¶
Обертывание представлений API¶
Фреймворк REST предоставляет две обертки, которые можно использовать для написания представлений API.
Декоратор @api_view для работы с представлениями, основанными на функциях.
Класс APIView для работы с представлениями, основанными на классах.
Собираем все вместе¶
Итак, давайте начнем использовать эти новые компоненты, чтобы немного рефакторизовать наши представления.
Наше представление экземпляра является улучшением по сравнению с предыдущим примером. Оно немного лаконичнее, и код теперь очень похож на тот, который мы использовали при работе с Forms API. Мы также используем именованные коды состояния, что делает значения ответов более очевидными.
Добавление необязательных суффиксов формата к нашим URL-адресам¶
Начните с добавления аргумента в виде ключевого слова format к обоим представлениям, как показано ниже.
Нам не обязательно добавлять эти дополнительные шаблоны url, но это дает нам простой и чистый способ ссылаться на определенный формат.
Как он выглядит?¶
Мы можем получить список всех сниппетов, как и раньше.
Мы можем контролировать формат ответа, который мы получаем обратно, либо с помощью заголовка Accept :
Или путем добавления суффикса формата:
Удобство просмотра¶
Поскольку API выбирает тип содержимого ответа на основе запроса клиента, он по умолчанию возвращает представление ресурса в формате HTML, когда ресурс запрашивается веб-браузером. Это позволяет API возвращать полностью доступное для веб-браузера представление HTML.
Что дальше?¶
В :doc: ` tutorial part 3 `** мы начнем использовать представления, основанные на классах, и увидим, как общие представления уменьшают количество кода, который нам нужно написать.
Requests
Request parsing
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.
.query_params
.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.
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.
Content negotiation
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.
.accepted_renderer
The renderer instance that was selected by the content negotiation stage.
.accepted_media_type
A string representing the media type that was accepted by the content negotiation stage.
Authentication
REST framework provides flexible, per-request authentication, that gives you the ability to:
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.
.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.
Browser enhancements
.method
request.method returns the uppercased string representation of the request’s HTTP method.
.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.
.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.
Standard HttpRequest attributes
Note that due to implementation reasons the Request class does not inherit from HttpRequest class, but instead extends the class using composition.
Путь от request до response в Джанго
Веб-приложение или веб-сайт вращаются вокруг цикла запрос-ответ, и приложения Django не являются исключением. Но это не просто двухэтапный процесс. Наши приложения Django должны пройти различные стадии, чтобы вернуть конечному пользователю результат. Чтобы лучше понять структуру Django, мы должны понимать, как инициируются запросы и как конечный результат передается конечному пользователю. В следующих разделах я собираюсь объяснить различные этапы запросов и используемое там программное обеспечение или код.
При настройке нового проекта Django первое, что вы сделаете, это подключите ваши URLconfs и создадите какие-то представления. Но что на самом деле происходит «под капотом»? Как Django направляет трафик к представлению и какую роль играют промежуточное ПО (middleware) в этом цикле?
WSGI — это инструмент, созданный для решения основной проблемы: подключения веб-сервера к веб-среде. WSGI имеет две стороны: «серверная» и «прикладная». Для обработки ответа WSGI сервер выполняет приложение и предоставляет функцию обратного вызова на стороне приложения. Приложение обрабатывает запрос и возвращает ответ на сервер, используя предоставленный обратный вызов. По сути, обработчик WSGI действует как привратник между вашим веб-сервером (Apache, NGINX и т.д.) и вашим проектом на Django.
Между сервером и приложением лежат промежуточные программы (middleware). Вы можете думать о промежуточном программном обеспечении как о серии двунаправленных фильтров: они могут изменять (или замыкать) данные, передаваемые назад и вперед между сетью и вашим приложением Django.
Большая картина — поток данных
Когда пользователь делает запрос к вашему приложению, создается экземпляр обработчика WSGI, который:
Слои приложения Джанго
Всякий раз, когда поступает запрос, он обрабатывается промежуточным программным обеспечением. Мы можем иметь несколько промежуточных программ. Найти их можно в настройках проекта ( settings.py ). Промежуточное ПО запросов Django происходит по порядку при обработке запроса. Предположим, что если у нас есть запрос промежуточного программного обеспечения в порядке A, B, C, то запрос сначала обрабатывается промежуточным программным обеспечением A, а затем B, а затем C. Django предлагает связку промежуточного программного обеспечения по умолчанию. Мы также можем написать наши собственные или пользовательские промежуточные программы. После обработки запроса промежуточным программным обеспечением он будет отправлен на маршрутизатор URL (диспетчер URL).
URL-маршрутизатор примет запрос от промежуточного программного обеспечения запроса (request middleware) и получит путь URL-адреса из запроса. На основе пути URL-маршрутизатор попытается сопоставить путь запроса с доступными шаблонами URL-адреса. Эти шаблоны URL имеют форму регулярных выражений. После сопоставления пути URL с доступными шаблонами URL запрос будет отправлен в представление, связанное с URL.
Теперь мы находимся в слое бизнес-логики. Представления обрабатывают бизнес-логику, используя запрос и данные запроса (данные, отправленные в GET, POST и т.д.). После обработки в представлении запрос отправляется контекстным процессорам, с помощью обработчиков контекста запроса добавляет контекстные данные, которые помогут средству визуализации шаблонов визуализировать шаблон для генерации HTTP-ответа.
И снова запрос будет отправлен обратно в промежуточное программное обеспечение, но уже ответа ( response ) для его обработки. Промежуточное программное обеспечение ответа обработает запрос и добавит или изменит информацию заголовка /информацию тела перед отправкой обратно клиенту (браузеру). После этого браузер обработает и отобразит его для конечного пользователя.
Промежуточное программное обеспечение используется в ряде ключевых функций в проекте Django: например мы используем промежуточное ПО CSRF для предотвращения атак подделки межсайтовых запросов. Они используются для обработки данных сеанса. Аутентификация и авторизация осуществляется с использованием промежуточного программного обеспечения. Мы можем написать наши собственные классы промежуточного программного обеспечения для формирования (или замыкания) потока данных через ваше приложение.
process_request
Определение URL
Представление имеет три требования:
process_view
Теперь, когда обработчик WSGI знает, какую функцию представления вызывать, он снова просматривает свой список методов промежуточного программного обеспечения. Метод process_view для любого промежуточного программного обеспечения Django объявлен так:
process_exception
process_response
Все сделано!
Наконец, обработчик Django WSGI создает возвращаемое значение из объекта HttpResponse и выполняет функцию обратного вызова для отправки этих данных на веб-сервер и для пользователя.
Итак, два ключевых вывода: