django cookie&session


What is a cookie

Because http protocol is stateless, that is, the server does not know the user's last action is what is done. This is a serious impediment to 交互式WEB应用程序implementation. A cookie is an additional means of http, to save part of the information to the user of the client, the cookie that is stored in the user's end, maintained by the user's browser, usually divided into two types: memory cookie, hard cookie. cookie is entrained in the http request, generally limited to about the size of 4KB

After adding servers in response settings over cookie, cookie support browsers will respond to in some way to save this cookie, when the next time the user making the request, the browser cookie to determine whether the current failure (expirse) , matching path (path), the matching domain (domain) and other operations, this cookie will be added to the header of the request sent to the server. Server to process it

Use a cookie in django

  • Save implement user login status
# views.py
def login(request):
    if request.method == "GET":
        return render(request, 'login.html')
    elif request.method == "POST":
        u = request.POST.get("username", None)
        p = request.POST.get("password", None)
        dic = user_info.get(u)
        print(dic)
        if not dic:
            return render(request, 'login.html')
        elif dic.get('pwd') == p:
           # 密码正确后设定cookie
            response = redirect('/index/')
            response.set_cookie("username", u)
            return response
        else:
            return render(request, 'login.html')
    else:
        return render(request, 'login.html')

#index
def index(request):
    ck = request.COOKIES.get("username")  # 早cookie中获取当前登录的用户
    if not ck:
         return redirect('/login/')
    return render(request, 'index.html', {'current_user': ck})

When a user name and password authentication is successful, the return of redirectsettings cookie. In this simple example which can realize save the user's login status, the time when the next time the user accessed index is not required to log in

  • Some other cookie settings:

1. request.COOKIESuser data sent to bring COOKIE, as a dictionary, you can get use to get
2 response.set_cookie("字典的key",'字典的值')times back without parameters, can only be set when a browser is closed on the failure of the cookie
3. response.set_cookie("username",'value',max_age=10)expire after how many seconds cookie
4. The expiration is set by datetime

current_date = datetime.datetime.utcnow()
current_date = current_date+ datetime.timedelta(seconds=10)   # 当前时间加上10s后
response.set_cookie("username", u, expires=current_date)  # 设定到哪个时间点后失效,如果时间设置与当前时间相同,那么就是清除这个cookie

5. Set cookie path effects

response.set_cookie("username", u,path='/index/')  # 设置这个cookie只在当前url生效,例如设定一个cookie为当前页面显示多少条数据,别的页面就不会被干扰

6. The domain=''current settings cookie name
7. secure = Falsedisposed cookie to https transmission
8 httponly = Trueis provided only as a cookie http transmission, js not be acquired. Js use in the document.cookieacquisition of all can a cookie, a cookie can also be operated using JQuery

9. cookie with a salt of

# 设定加盐
COOKIE_SALT = "随机字符串"
response.set_signed_cookie('username', u, salt=COOKIE_SALT)

# 加盐获取
ck = request.get_singed_cookie("username",salt=COOKIE_SALT)

session

What is the session

Reference: Jin brother of their own money

session is generally translated into a session, the session came to see from a different perspective, a different meaning:

  1. From the user's point of view, he opened a website, and a series of browser, login, shopping and other operations, which can be referred to a conversation
  2. To carefully analyze it from the ground due to http stateless, users log on to our need to save his login status, all current product in the shopping cart needs to be preserved, so we need a special data structure to hold the data. This thing is called a session

So http session protocol is based on a data storage structure for enhancing the http or programs, stored in the server session. General step into the server session creation: generating a globally unique identification sessionid, open space in the corresponding data, and then transmits the globally unique identifier to the session clients. Server for each session maintains a data session information, and the client and server to rely on a globally unique identifier to access session information data.

So how the client and the server sends this identifier it? Generally, there are two ways to achieve:

  • cookie, cookie server by setting the way, will be sent to the client sessionid
  • url rewriting, before returning to the page requested by the user, all within the page URL back all the way to get together session identifier, the user at the next operation, this will add an identifier, enabling the session to keep this when users disable cookie is made effective way

Comparison with the session cookie

  1. Scenarios
  • Cookie typical application scenario is to remember passwords, Remember Me operation, the user's account information in the form of a cookie stored in the client, when the user requests a URL that matches again, the account information will be sent to the server, forwarded to the appropriate the program is completed automatically logs and other functions. Of course, you can save some of the client information, such as page layout, and search history, and so on.
  • Session typical application scenarios after the user logs on a site, their login information into the session, check the appropriate login information after each request to ensure that the user is legitimate. Of course, still have a shopping cart, and so the classic scene;
  1. safety
  • cookie information stored in the client, if not encrypted, then it would expose some private information, poor security, under normal circumstances, after sensitive information is encrypted in a cookie, but it could easily be stolen memory.
  • The information session will be stored in the server, if stored in a file or database, there are likely to be stolen, but the possibility of much smaller than the cookie. Here is hardware related to security, but in general is higher than the security session cookie;
  1. performance
  • Cookie is stored on the client, the client's consumption is the I / O and memory, while the session is stored on the server, the server is consuming resources.
  • Pressure caused by the server session concentrated, well dispersed and cookie consumption of resources, on this point, the session cookie is superior;
  1. Timeliness
  • Cookie can be a long time exists in the client by setting the validity of it, and
  • session generally only a relatively short period (timeout triggered after a user actively destroy or close the browser session);
  1. Other
    processing Cookie is not easy session in development. And on the client side cookie is to limit the number and size, and the size of the session but only to hardware limitations, the data can be stored undoubtedly too big.

django used session

Note:

  1. django default django.contrib.sessions.models.Sessionmodule, the session storage in a database django_sessiontable, of course, these are configurable

  2. It is necessary to use database-backed sessionsa certain set before, and generating a table stored in the session database fields among
python manage.py makemigrations
python manage.py migrate
  • Simple implementation
# views.py
def login(request):
    if request.method == "GET":
        return render(request, "login.html")

    if request.method == "POST":
        user = request.POST.get('user')
        pwd = request.POST.get('pwd')
        rmb = request.POST.get('rmb',None)
        print(rmb)
        if user == 'root' and pwd == "123":
            # 直接设定值
            request.session['username'] = user
            request.session['is_login'] = True
            if rmb == "10":
                request.session.set_expiry(10)  # 设置多少秒后过期
            # 生成的session默认存储在django的默认数据库中
            return redirect('/index/')
        else:
            return render(request, "login.html")

def logout(request):
    # 注销
    if request.method == 'POST':
        print(request.session.get('username'))
        request.session.delete(request.session.session_key) # 从数据库中删除
        print(request.session.session_key)
        print(request.session.get('username'))
        return redirect('/login/')

def index(request):
    if request.session.get('is_login'):
        return render(request, 'index.html')
    else:
        return HttpResponse("Fuck off")
  • Access will generate the following data in the database in such applications

session-table

  • More Actions
1. 获取session中的值
request.session['k1']
request.session.get('k1',None)
2. 设定session中的值
request.session['k1'] = 123
request.session.setdefault('k1',123) # 存在则不设置
3. 删除session对应的值
del request.session['k1']
4. 由于session的真是数据结构其实是个字典对象,所以拥有字典的一些方法:
request.session.keys() # 所有的key
request.session.values() # 所有的value
request.session.items() # 键值对元组
# 其他方法
request.session.iterkeys() # key的可迭代对象
request.session.itervalues() # value的可迭代对象
request.session.iteritems()  # 键值对元组的可迭代对象
5. 用户的全局唯一sessionid
request.session.session_key
6. 将所有Session失效日期小于当前日期的数据删除
request.session.clear_expired()
7. 判断是否存在
request.session.exists("session_key")
8. 删除这个sessionid,并也会删除其对应的数据
request.session.delete("session_key")
9. 过期设定
request.session.set_expiry(value)
    * 如果value是个整数,session会在些秒数后失效。
    * 如果value是个datatime或timedelta,session就会在这个时间后失效
    * 如果value是0,用户关闭浏览器session就会失效。
    * 如果value是None,session会依赖全局session失效策略。(默认是两个周)
  • Configuration-related

1. Engine Related
addition to the supported django engine other than the following may be used as the session redis storage, reference may be provided a method redis Mengchuo

# 数据库存储
SESSION_ENGINE = 'django.contrib.sessions.backends.db'
# 缓存存储
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
# 文件存储
SESSION_ENGINE = 'django.contrib.sessions.backends.file'
SESSION_FILE_PATH = None # 缓存文件路径,如果为None,则使用tempfile模块获取一个临时地址tempfile.gettempdir()
# 缓存加数据库
SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db'
# 加密cookie Session
SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies'

2. Common Settings

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,默认修改之后才保存

Guess you like

Origin www.cnblogs.com/forsaken627/p/12521965.html