Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand Python Django request and response objects

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article focuses on "how to understand Python Django request and response objects". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to understand Python Django request and response objects.

Django request and response object

Django uses request and response objects to pass status through the system.

When a page is requested, Django creates a HttpRequest object that contains the requested metadata. Django then loads the corresponding view, taking HttpRequest as the first argument to the view function. Each view is responsible for returning a HttpResponse object.

HttpRequest object

The following describes the common properties and methods of HttpRequest objects.

HttpRequest Common Properties

1.HttpRequest.body

The original HTTP request body is used as a byte string. This is useful for processing data from unconventional HTML forms in different ways: binary images, XML payloads, and so on. For dealing with traditional form data, use HttpRequest.POST

2.HttpRequest.method

The string that represents the HTTP method used in the request must be an uppercase letter.

3.HttpRequest.GET

A dictionary-like object that contains all the given HTTP GET parameters.

4.HttpRequest.POST

A dictionary-like object that contains all the given HTTP POST parameters, provided that the request contains form data. If you need to access the raw or non-form data posted in the request, you can access it through the HttpRequest.body attribute.

The above four attributes are our most commonly used HttpRequest properties. In practice, the code we might write is as follows:

If request.method = = "POST": # POST request method try: data = json.loads (request.body) # get the non-form data (JSON data) carried by the POST request except json.JSONDecodeError: return JsonResponse ({"status": "1") "msg": "data format error") # form data # keys = request.POST.get ("keys") # if POST is carrying form data You can get it like this. Elif request.method = "GET": keys = request.GET.get ("keys") # get the parameter return JsonResponse ({"status": "0", "msg": "request successful"}) else: return JsonResponse ({"status": "0", "msg": "request method error"}) carried by the get request

5.HttpRequest.COOKIES

A dictionary containing all the cookies. Keys and values are strings.

6.HttpRequest.FILES

A dictionary-like object that contains all uploaded files. Each key in FILES is the name in. Each value in FILES is a UploadedFile.

FILES contains data only if the request method is POST and the request is issued with enctype= "multipart/form-data". Otherwise, FILES will be a blank object similar to a dictionary.

7.HttpRequest.META

A dictionary containing all available HTTP header files. The available header information depends on the client and server. Some possible examples are as follows:

1.CONTENT_LENGTH-the length of the request body (string).

2.CONTENT_TYPE-the MIME type of the request body.

3.HTTP_ACCEPT-acceptable response content type.

4.HTTP_ACCEPT_ENCODING-acceptable response coding.

5.HTTP_ACCEPT_LANGUAGE-an acceptable response language.

6.HTTP_HOST-the HTTP host header sent by the client.

7.HTTP_REFERER-referrer page, if any.

8.HTTP_USER_AGENT-the user agent string for the client.

9.QUERY_STRING-the query string, which is a single (unparsed) string.

10.REMOTE_ADDR-the IP address of the client.

11.REMOTE_HOST-the hostname of the client.

12.REMOTE_USER-users authenticated by the Web server, if any.

13.REQUEST_METHOD-strings such as "GET" or "POST".

14.SERVER_NAME-the hostname of the server.

15.SERVER_PORT-the port (string) of the server.

Any HTTP headers in the request are converted to the META key by converting all characters to uppercase letters, replacing any hyphens with underscores, and prefixing the name with HTTP_ `. For example, the X-CSRFToken in the request header becomes HTTP_X_CSRFTOKEN in META.

Properties of middleware settings

Some of the middleware included in Django's contrib application sets properties in the request.

1.HttpRequest.session

From SessionMiddleware. A readable, writable, dictionary-like object that represents the current session.

2.HttpRequest.user

From AuthenticationMiddleware. An instance of AUTH_USER_MODEL that represents the currently logged in user. If the user is not currently logged in, user will be set to an instance of AnonymousUser. You can use is_authenticated to distinguish between them, for example:

If request.user.is_authenticated:... # Do something for logged-in users.else:... # Do something for anonymous users.

If the Django project is deployed using Nginx+uWsgi, then the REMOTE_ADDR,REMOTE_HOST in META is incorrect, because it is forwarded to the port that uWsgi listens to through the Nginx agent, and the client information obtained by the application is 127.0.0.1 native information, not the real client information. Therefore, you need to add the following parameters to Nginx:

Uwsgi_param Host $host;uwsgi_param X-Real-IP $remote_addr;uwsgi_param X-Forwarded-For $proxy_add_x_forwarded_for;uwsgi_param X-Forwarded-Proto $http_x_forwarded_proto

Whether you need X-Real-IP or X-Forwarded-For depends on your business logic.

QueryDict object

In a HttpRequest object, the GET and POST properties are instances of django.http.QueryDict, a dictionary-like class that handles multiple values of the same key. This is necessary because some HTML form elements, in particular, pass multiple values of the same key.

The QueryDict in request.POST and request.GET is immutable when it will be accessed during the normal request / response cycle. To get a mutable version, you need to use QueryDict.copy ().

QueryDict method

QueryDict is a subclass of dictionaries, so QueryDict has all the standard methods of dictionaries.

1.QueryDict.get (key, default=None)

If the key does not exist, a default value is returned with a hook. If the key has more than one value, the last value is obtained.

2.QueryDict.getlist (key, default=None)

Returns a list of data with the request key. If the key does not exist and default is None, an empty list is returned. Returns a list unless the default value provided is not a list.

Here is a piece of code that shows the use of get and getlist.

> qd = QueryDict ('axiaroom2roomaroom3roombread4') # construct QueryDict object qd > qd.get (' a2') # get the last value of key a ['3' > qd.getlist ('a') # get all values of key a ['1values,' 2values,'3'] > > qd > qd.getlist ('c') [] > > qd.getlist ('cantin, [1J 2]) [1jue 2] > > qd.get (' c') '5')' 5'HttpResponse object

Django automatically creates HttpRequest (wsgi or asgi creation) objects, while HttpResponse is the back-end developer responsible for instantiating, populating, and returning. Each view function must return a HttpResponse object.

The HttpResponse class is located in the django.http module.

HttpResponse object usage

A typical use is to pass the contents of the page to the HttpResponse constructor as a string, byte string, or memoryview. For example:

> from django.http import HttpResponse > > response = HttpResponse ("Hello World!")

In this way, the return response front end can get the response data at the end of the function.

But if you want to add content incrementally, you can use response as a file-like object:

> response = HttpResponse () > response.write ("

Here's the text of the Web page.

") > response.write ("

Here's another paragraph.

")

Under the general trend of front-end separation, we rarely use the back-end to render the page. The backend usually returns JSON data.

Incoming iterator

You can pass HttpResponse an iterator instead of a string. HttpResponse immediately consumes the iterator, stores its contents as a string, and then discards it. Objects with the close () method, such as files and generators, are immediately closed. If you need to stream the response from the iterator to the client, you must use the StreamingHttpResponse class instead.

This is fine in a normal scenario, but if the files or pictures are large and large, we usually use a separate static file server to solve the problem, rather than Django to deal with these things.

* * tell the browser to treat the response as a file attachment * *

Response = HttpResponse (my_data, headers= {... 'Content-Type': 'application/vnd.ms-excel',... 'Content-Disposition':' attachment; filename= "foo.xls",...})

The Content-Disposition header doesn't have anything specific to Django, but it's easy to forget the syntax, so we include it here.

HttpResponse object Properties

1.HttpResponse.charset

A string that represents the character set that the response will be encoded. If it is not given when the HttpResponse is instantiated, it will be extracted from the content_type, and if it is not successful, the DEFAULT_CHARSET setting will be used (if not set, the default is utf-8).

2.HttpResponse.status_code

The HTTP status code of the HttpResponse object.

Unless reason_phrase is explicitly set, changing the value of status_code outside the constructor also modifies the value of reason_phrase.

HttpResponse object method

1.HttpResponse.set_cookie (key, value='', max_age=None, expires=None, path='/', domain=None, secure=False, httponly=False, samesite=None)

Set up a cookie. The parameters are the same as the Morsel cookie objects 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 be a string of the format "Wdy, DD-Mon-YY HH:MM:SS GMT", or a datetime.datetime object of UTC. If expires is a datetime object, max_age is evaluated.

Max_age will replace expires in the near future.

If you want to set up a cross-domain cookie, use domain. For example, domain= "example.com" will set a cookie that can be read by domains such as www.example.com, blog.example.com, and so on. Otherwise, a cookie can only be read by the domain in which it is set.

If you want cookie to send to the server only when making a request using the https scheme, use secure=True.

If you want to prevent the client's JavaScript from accessing cookie, use httponly=True.

HttpOnly is a flag contained in the Set-Cookie HTTP response header. It is part of the Cookie in the RFC 6265 standard and can be used as a useful way to reduce the risk of client script accessing protected Cookie data.

Use samesite='Strict' or samesite='Lax' to tell the browser not to send this cookie when performing a cross-source request. SameSite is not supported by all browsers, so it is not a substitute for Django's CSRF protection, but a defense in depth.

Use samesite=''None' (string) to make it clear that the cookie will be sent with all peer and cross-site requests.

Changed in Django 3.1:

Samesite='None (string) is allowed.

2.HttpResponse.delete_cookie (key, path='/', domain=None, samesite=None)

Deletes the cookie of the given key. If the key does not exist, silence fails.

Because of the way cookie works, path and domain should be the same values you used in set_cookie (), otherwise cookie may not be deleted.

HttpResponse subclass

The HttpResponse subclass can refer directly to the Django documentation, and for now, nothing is more common than the JsonResponse subclass. Here, the JsonResponse subclass will be introduced specifically.

JsonResponse object

Class JsonResponse (data, encoder=DjangoJSONEncoder, safe=True, json_dumps_params=None, * * kwargs)

A HttpResponse subclass that helps create a JSON-encoded response. It inherits most of the behavior of its superclass, but with some differences:

Its default Content-Type header is set to application/json.

The first parameter, data, should be a dict instance. If the safe parameter is set to False (see below), it can be any JSON serializable object.

Encoder, which defaults to django.core.serializers.json.DjangoJSONEncoder, will be used to serialize data.

The safe Boolean parameter defaults to True. If it is set to False, any object can be passed to the serialization (otherwise only dict instances are allowed). If safe is True and the first parameter is a non-dict object, a TypeError is thrown.

The json_dumps_params parameter is a dictionary of keyword arguments that are passed to the json.dumps () call to generate a response. Can be used to specify the encoding.

At this point, I believe you have a deeper understanding of "how to understand Python Django request and response objects". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report