Detailed explanation of Cookie and Session in python

不言
Release: 2018-09-20 15:48:16
Original
7235 people have browsed it

This article brings you a detailed explanation of Cookie and Session in python. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Cookie

1. The origin of Cookie

Everyone knows that the HTTP protocol is stateless.

Stateless means that each request is independent. Its execution and results are not directly related to the previous request or subsequent requests. It will not be directly affected by the previous request response. It will not directly affect subsequent request responses.

An interesting sentence to describe it is that life is just like seeing it for the first time. For the server, every request is brand new.

State can be understood as the data generated by the client and server in a session, and stateless means that these data will not be retained. The data generated in the session is what we need to save, which means we need to "maintain state". Therefore, Cookie was born in such a scenario.

2. What is Cookie

Cookie specifically refers to a small piece of information. It is a set of key-value pairs sent by the server and stored on the browser. You can browse the next time you visit the server. The server will automatically carry these key-value pairs so that the server can extract useful information.

3. Principle of Cookie

The working principle of cookie is: the content is generated by the server, and the browser saves it locally after receiving the request; when the browser visits again, the browser will automatically bring Cookie, so that the server can determine "who" this is through the content of the cookie.

Operation Cookie in Django

1. Get Cookie

request.COOKIES['key']
request.get_signed_cookie(key, default=RAISE_ERROR, salt='', max_age=None)
Copy after login

Parameters:

  • default: Default value

  • salt: Encrypted salt

  • max_age: Background control expiration time

2. Set Cookie

rep = HttpResponse(...)
rep = render(request, ...)

rep.set_cookie(key,value,...)
rep.set_signed_cookie(key,value,salt='加密盐',...)
Copy after login

Parameters:

  • key, key

  • value='', value

  • max_age =None, timeout period

  • expires=None, timeout period (IE requires expires, so set it if hasn't been already.)

  • path='/', the path where the cookie is valid, / represents the root path, special: the cookie of the root path can be accessed by any url page

  • domain=None, the cookie is valid Domain name

  • secure=False, https transmission

  • httponly=False can only be transmitted by http protocol and cannot be obtained by JavaScript (not absolute, bottom-level capture The package can be obtained or overwritten)

3. Delete Cookie

def logout(request):
    rep = redirect("/login/")
    rep.delete_cookie("user")  # 删除用户浏览器上之前设置的usercookie值
    return rep
Copy after login

Session

Session Origin

Although Cookie solves the need of "maintaining state" to a certain extent, because the Cookie itself supports a maximum of 4096 bytes, and the Cookie itself is saved on the client, it may be intercepted or stolen. There is a need for a new thing that can support more bytes, and it is stored on the server with higher security. This is Session.

The problem is, based on the stateless characteristics of the HTTP protocol, the server does not know "who" the visitor is at all. Then the above-mentioned Cookie plays a bridging role.

We can assign a unique id to each client's cookie, so that when the user visits, the server will know "who" the visitor is through the cookie. Then we store private information on the server for a period of time based on different cookie IDs, such as "account password" and so on.

In summary: Cookies make up for the shortcomings of HTTP's statelessness, allowing the server to know "who" the person coming is; however, Cookies are stored locally in the form of text, and their own security is poor; so we use Cookies identify different users and correspondingly store private information and text exceeding 4096 bytes in the Session.

In addition, the Cookie and Session mentioned above are actually common things and are not limited to languages ​​and frameworks.

Session related methods in Django

# 获取、设置、删除Session中数据
request.session['k1']
request.session.get('k1',None)
request.session['k1'] = 123
request.session.setdefault('k1',123) # 存在则不设置
del request.session['k1']


# 所有 键、值、键值对
request.session.keys()
request.session.values()
request.session.items()
request.session.iterkeys()
request.session.itervalues()
request.session.iteritems()

# 会话session的key
request.session.session_key

# 将所有Session失效日期小于当前日期的数据删除
request.session.clear_expired()

# 检查会话session的key在数据库中是否存在
request.session.exists("session_key")

# 删除当前会话的所有Session数据
request.session.delete()
  
# 删除当前的会话数据并删除会话的Cookie。
request.session.flush() 
    这用于确保前面的会话数据不可以再次被用户的浏览器访问
    例如,django.contrib.auth.logout() 函数中就会调用它。

# 设置会话Session和Cookie的超时时间
request.session.set_expiry(value)
    * 如果value是个整数,session会在些秒数后失效。
    * 如果value是个datatime或timedelta,session就会在这个时间后失效。
    * 如果value是0,用户关闭浏览器session就会失效。
    * 如果value是None,session会依赖全局session失效策略。
Copy after login

1. Session process analysis

2. Session configuration in Django

Django supports Session by default, and it provides 5 types of Session internally for developers to use.

1. 数据库Session
SESSION_ENGINE = 'django.contrib.sessions.backends.db'   # 引擎(默认)

2. 缓存Session
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'  # 引擎
SESSION_CACHE_ALIAS = 'default'                            # 使用的缓存别名(默认内存缓存,也可以是memcache),此处别名依赖缓存的设置

3. 文件Session
SESSION_ENGINE = 'django.contrib.sessions.backends.file'    # 引擎
SESSION_FILE_PATH = None                                    # 缓存文件路径,如果为None,则使用tempfile模块获取一个临时地址tempfile.gettempdir() 

4. 缓存+数据库
SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db'        # 引擎

5. 加密Cookie Session
SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies'   # 引擎

其他公用设置项:
SESSION_COOKIE_NAME = "sessionid"                       # Session的cookie保存在浏览器上时的key,即:sessionid=随机字符串(默认)
SESSION_COOKIE_PATH = "/"                               # Session的cookie保存的路径(默认)
SESSION_COOKIE_DOMAIN = None                             # Session的cookie保存的域名(默认)
SESSION_COOKIE_SECURE = False                            # 是否Https传输cookie(默认)
SESSION_COOKIE_HTTPONLY = True                           # 是否Session的cookie只支持http传输(默认)
SESSION_COOKIE_AGE = 1209600                             # Session的cookie失效日期(2周)(默认)
SESSION_EXPIRE_AT_BROWSER_CLOSE = False                  # 是否关闭浏览器使得Session过期(默认)
SESSION_SAVE_EVERY_REQUEST = False                       # 是否每次请求都保存Session,默认修改之后才保存(默认)

Django中Session相关设置

Django中Session相关设置
Copy after login

Session-related settings in Django

3. Decorator-related settings in CBV

Login view implemented by CBV

class LoginView(View):

    def get(self, request):
        """
        处理GET请求
        """
        return render(request, 'login.html')

    def post(self, request):
        """
        处理POST请求 
        """
        user = request.POST.get('user')
        pwd = request.POST.get('pwd')
        if user == 'alex' and pwd == "alex1234":
            next_url = request.GET.get("next")
            # 生成随机字符串
            # 写浏览器cookie -> session_id: 随机字符串
            # 写到服务端session:
            # {
            #     "随机字符串": {'user':'alex'}
            # }
            request.session['user'] = user
            if next_url:
                return redirect(next_url)
            else:
                return redirect('/index/')
        return render(request, 'login.html')
Copy after login

To use our above check_login decorator in the CBV view, there are three ways:

from django.utils.decorators import method_decorator

1. Add the get in the CBV view Or on the post method

from django.utils.decorators import method_decorator


class HomeView(View):

    def dispatch(self, request, *args, **kwargs):
        return super(HomeView, self).dispatch(request, *args, **kwargs)

    def get(self, request):
        return render(request, "home.html")
    
    @method_decorator(check_login)
    def post(self, request):
        print("Home View POST method...")
        return redirect("/index/")
Copy after login

2. Add it on the dispatch method

from django.utils.decorators import method_decorator


class HomeView(View):

    @method_decorator(check_login)
    def dispatch(self, request, *args, **kwargs):
        return super(HomeView, self).dispatch(request, *args, **kwargs)

    def get(self, request):
        return render(request, "home.html")

    def post(self, request):
        print("Home View POST method...")
        return redirect("/index/")
Copy after login

Because the first thing executed in CBV is the dispatch method, writing this is equivalent to Both the get and post methods add login verification.

3. Add it directly to the view class, but method_decorator must pass the name keyword parameter

If both the get method and the post method require login verification, write two a decorator.

from django.utils.decorators import method_decorator

@method_decorator(check_login, name="get")
@method_decorator(check_login, name="post")
class HomeView(View):

    def dispatch(self, request, *args, **kwargs):
        return super(HomeView, self).dispatch(request, *args, **kwargs)

    def get(self, request):
        return render(request, "home.html")

    def post(self, request):
        print("Home View POST method...")
        return redirect("/index/")
Copy after login

The above is the detailed content of Detailed explanation of Cookie and Session in python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template