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

Explanation of common properties and method functions of HttpResponse and HttpRequest objects in Django framework

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

Share

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

This article introduces the relevant knowledge of "explaining the common properties and methods of HttpResponse and HttpRequest objects in the Django framework". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Catalogue

HttpRequest object

1. We can print this request object

two。 We can print and see what methods it has.

Function explanation of common properties and methods:

HttpResponse object

Properties and methods of HttpResponse object

Attribute

Method

Subclasses of HttpResponse

Response function that returns data

HttpRequest object

You have written so many view functions with this blogger earlier, but each view function receives a parameter called request.

Are you curious: what kind of object is the request received by the view function?

1. We can print this request object

Take a look:

We know that WSGIRequest is a HTTP request object, which includes the submission method and URL path.

To sum up, we can see that:

After receiving the request from http protocol, the server will create a HttpRequest object based on the message.

It is a request object: user information (submission method, etc.); browser information (request header information, etc.).

The first argument to the view function is the HttpRequest object.

The API of the HttpRequest object is defined in the django.http module

two。 We can print to see what methods dir (request) it has.

Function explanation of common properties and methods:

Attributes:

Path: a string that represents the full path to the requested page, excluding the domain name.

Method: a string indicating the HTPP method used by the request. Common values include: 'GET','POST'.

Encoding: a string that represents how the submitted data is encoded. If None, it means that the default setting of the browser (usually utf-8) is used. This property is writable, and you can modify the encoding used to access the form data by modifying it, adding that any access to the property will use the new encoding value.

GET: a dictionary-like object that contains all the parameters of the get request method.

POST: a dictionary-like object that contains all the parameters of the post request method.

FILES: a dictionary-like object that contains all uploaded files.

COOKIES: a standard Python dictionary that contains all cookie. Keys and values are strings.

Session: a dictionary-like object that is both readable and writable that represents the current session and is available only when Django enables session support.

Methods:

Is_ajax (): returns True if the request is initiated through XMDHttpRequest.

HttpResponse object

Many times when we visit a web page, the developers of the web page mostly use JS effects to display effects such as pop-up windows (reminders to log in / register / the user name has been registered, etc.).

So, how do you achieve the JS effect with Django?

After receiving the request from the client, the Django server encapsulates the submitted data into a HttpRequest object and passes it to the view function. Then the view function also needs to return a response to the browser after dealing with the relevant logic. For this response, we must return an object of HttpResponseBase or its subclass. HttpResponse is the most frequently used subclass of HttpResponseBase. So let's take a look at HttpResponse and its subclasses.

Properties and method properties of the HttpResponse object

Content: indicates the returned content, string type

Charset: indicates the encoded character set and string type used by response

Status_code: HTTP response status code of the response

Content-type: the MIME type of the returned data. Default is text/html. The browser will display the data based on this property. If it is text/html, the string will be parsed, and if text/plain, a plain text will be displayed. The commonly used Content-Type is as follows:

Text/html (default, html file)

Text/plain (plain text)

Text/css (css file)

Text/javascript (js file)

Multipart/form-data (document submission)

Application/json (json Transport)

Application/xml (xml file)

Example:

Response = HttpResponse ('Wechat official account [lonely cold person], content_type='text/plain;charset=utf-8') # Note: generally, when using' text/plain', you will add 'charset=utf-8',' otherwise it will garbled. Return response method

Init: instantiate HttpResponse objects using page content

Write (content): write as a file

Flush (): output the cache as a file

Set_cookie (key, value='',max_age=None, expires=None): sets Cookie.

Parameter explanation:

  ① key,value are all string types

  ② max_age is an integer that expires after a specified number of seconds

  ③ expires is a datetime or timedelta object, and the session will expire on this specified date / time. Note that the datetime and timedelta values can only be serialized when using PickleSerializer

Choose between   ④ max_age and inventor. If you do not specify an expiration time, closing the browser will become invalid.

Delete_cookie (key): deletes the cookie of the specified key, and nothing happens if the Key does not exist.

The subclass of HttpResponse returns the response function of the data

HttpResponse () returns a simple string object

Render () rendering template

Redirect () redirect

JsonResponse () returns json data. Combined with the front-end AJax and other technologies, the back-end can transmit data to the front-end, and the front-end can realize the JS effect functions such as registration and login after receiving. This solves the problem mentioned above! )

From django.http import JsonResponsedef resp (request): return JsonResponse ({'ss':' login succeeded!' }) # help users create JSON-encoded responses; # parameter data is a dictionary object; the default Content-Type of # JsonResponse is application/json. This is the end of the introduction to "introduction to common properties and methods of HttpResponse and HttpRequest objects in the Django framework". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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