Python framework Django How to handle cookies tutorial

Source: Internet
Author: User
Tags http request sessions

Let's take a look at how cookies work. When you open the browser and visit the google.com, your browser sends an HTTP request to Google, starting with the first part like this:

get/http/1.1
Host:google.com
...


When Google responds, the HTTP response is this:

http/1.1 OK
Content-type:text/html
set-cookie:pref=id=5b14f22bdaf1e81c:tm=1167000671:lm=1167000671;
Expires=sun, 17-jan-2038 19:14:07 GMT;
path=/; Domain=.google.com
server:gws/2.1
...


Pay attention to Set-cookie's head. Your browser will store the cookie value (pref=id=5b14f22bdaf1e81c:tm=1167000671:lm=1167000671), and the cookie value will be echoed every time you visit the Google site. So the next time you visit Google, your browser will send a request like this:


get/http/1.1
Host:google.com
cookie:pref=id=5b14f22bdaf1e81c:tm=1167000671:lm=1167000671
...


The value of Cookies will tell Google that you are the person who visited the Google site earlier. This value may be the key for storing user information in the database, and it can be used to display your username on the page. Google will (and is currently) use it to display the user name of your account on the Web page.

Access Cookies

When dealing with persistence in Django, most of the time you would prefer to use higher-level sessions and/or the user framework to be discussed later. But until then, we need to stop to see how to read and write cookies at the bottom. This will help you understand how the tools that are discussed later in this chapter work, and it will help if you need to manipulate cookies yourself.

It is extremely easy to read cookies that have been set up. Each ' HttpRequest ' object has a ' cookie ' object that behaves like a dictionary, and you can use it to read COOKIES from any browser sent to view.


def show_color (Request):
If "Favorite_Color" in Request. COOKIES:
Return HttpResponse (' Your favorite color is%s '% request. cookies["Favorite_Color"])
Else
Return HttpResponse ("You don ' t have a favorite color.")


It's a little more complicated to write cookies. You need to use the Set_cookie () method of the HttpResponse object. Here's a set of favorite_color based on get parameters.

Examples of cookies:


--edit http://www.aichengxu.com/view/61768--
def set_color (Request):
If "Favorite_Color" in Request. Get:

# Create an HttpResponse object ...
Response = HttpResponse ("Your favorite color is now%s"% request. get["Favorite_Color"])

#.. and set a cookie on the response
Response.set_cookie ("Favorite_Color",
Request. get["Favorite_Color"])

return response

Else
Return HttpResponse ("You didn ' t give a favorite color.")


You can pass some optional parameters to Response.set_cookie () to control the behavior of cookies, refer to: http://www.aichengxu.com/view/61768

mixed cookies.

Perhaps you have noticed that the way cookies work can cause problems. Let's take a look at some of the more important questions:

Cookies are stored voluntarily, and a client does not necessarily have to accept or store cookies. In fact, all browsers allow the user to control whether or not to accept cookies. If you want to know how important cookies are to web apps, you can try opening the browser's options:

Although cookies are widely used, they are still considered unreliable. This means that developers must check to see if a user can receive cookies before using cookies.

Cookies, especially those that are not transmitted over HTTPS, are very unsafe. Because HTTP data is sent in clear text, it is particularly susceptible to sniffer attacks. In other words, sniffer attackers can intercept and read cookies on the network, so you should absolutely avoid storing sensitive information in cookies. This means that you should not use cookies to store any sensitive information.

There is also a more insidious attack known as a "middleman", in which an attacker intercepts a cookie and uses it for another user. The 19th chapter will discuss in depth the nature of the attack and how to avoid it.

Even cookies returned from a desired recipient are unsafe. In most browsers, you can easily modify the information in cookies. Experienced users can even construct an HTTP request by using tools such as Mechanize (http://wwwsearch.sourceforge.net/mechanize/).

Therefore, it is not possible to store sensitive data that may be tampered with in cookies. Store isloggedin=1 in cookies to identify the user is logged in. The number of sites that make such errors is unbelievable; the security system that bypasses these sites is a breeze.


Django handles cookies and session

As for what cookies and sessions I believe everyone knows, so don't say birds. Directly record how cookies and sessions are manipulated under the Djano framework.

Access Cookies

It is easy to read cookies, because the cookies can be read using Httpresquest, each Httpresquest object has a cookie object, you can use it to read any browser sent to the view of cookies.

Because the first parameter of each view function is request, it is actually a Htppresquest object, so use the request directly. Cookies are good to read cookies.

Writing cookies uses the Set_cookie () method of the Httpresquest object, set_cookie Some optional parameters to specify some special actions.

Session Action

Open session (he was implemented through a middleware and a model).

1. Edit Middleware_classes to ensure that the django.contrib.sessions.middleware.SessionMiddleware is already included.

2. Confirm Installed_apps to ensure that there is already a ghost animal called Django.contrib.sessions.

In fact, these two, the general default is the premise that your project is to use Python manage.py startproject mysite to create.

use session in view

After Sessionmiddleware is activated, the first parameter request (that is, the Httpresquest object) for each view function has a session attribute, which, like a cookie, is a typical object that can be used like a normal dictionary.

Some taboo in the operation session:

1. Use a normal string to access the dictionary, not integers, objects, or anything else that is annoying.

The 2.key value is best not to be named with an underscore, because some are reserved, but are not generally used.

3. Do not replace request.session with a new object.

4. Do not deposit attributes into the request.session.

Test Cookies

Of course, some of the scumbags like to close cookies, so as a web developer with egg aches, it takes a test to store a cookie on someone's machine.

You can use Request.session.set_test_cookie () to test to make use of request.session.test_cookie_worked () in other views, and two Tests are not in the same view function. Why, it's about how cookies work.

Delete_test_cookie can be used to delete cookies that are set for testing.

Use the session outside of the view

We can use the Django database API to access the session, and we use get_decoded to read the actual session data.

Validity period

If Session_expire_at_browser_close is set to False, then the COOKIE is saved in the browser for session_cookie_age seconds. If set to True, the browser will fail when it is closed.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.