Cookie, session, middleware

text

A cookie mechanism

Web applications are using the HTTP protocol for transferring data. HTTP protocol is stateless protocol. Once the data exchange is completed, the client and server-side connection will be closed again to exchange data need to establish a new connection. This means that the server can not connect from a session on the track. That person A buys one item in the shopping cart, purchase goods again when the server has been unable to determine whether the purchase is part of a session or a user session B of the user A's. Cookie can make up for lack of stateless HTTP protocol. Before Session appears, essentially all of the sites use to track Cookie session. cookie has the following characteristics:

  • A cookie is saved in the user's browser encrypted key-value pair
  • Initiative can be cleared (the browser interface, front-end, back-end)
  • It can be "forged"
  • The purpose in privacy protection, prohibit cross-domain shared: that www.googole.com and www.baidu.com each cookie can not be shared, because the domain name corresponding Google Inc. and Baidu's server is different.

1. Check the cookie

 2. Get cookie

request.COOKIES.get ( 'Key') 
request.get_signed_cookie (Key, default = RAISE_ERROR, = Salt '', the max_age = None) 
default: Default 
salt: Salt encryption 
max_age: background control expiration

3. Set the cookie

rep = HttpResponse(...)
rep = render(request, ...)
#rep是Httpresponse对象

rep.set_cookie(key,value,...)
rep.set_signed_cookie(key,value,salt='加密盐', max_age=None, ...)
Attribute name Description
String name The name of Cookie. Cookie Once created, the name will not be changed
Object value The value of Cookie. If the value is Unicode character, character encoding is required. If the value is binary data, it is necessary to use BASE64 encoding
int maxAge Cookie failure of the time in seconds. If positive, the Cookie fail after maxAge seconds. If negative, the temporary Cookie Cookie, close the browser that is invalid, the browser will not save the Cookie in any form. If 0, it means to delete the Cookie. The default is -1
boolean secure Cookie is used only if the security protocol. Security Protocol. Protocol security HTTPS, SSL, etc., prior to transmission data is first encrypted data over the network. The default is false. When using https type must be set to secure Y = True.
String path Using the path to the Cookie. If set to "/ sessionWeb /", only contextPath as "/ sessionWeb" program can access the Cookie. If set to "/", then under the domain contextPath can access the Cookie. Note that the last character must be "/"
String domain You can access the Cookie domain name. If set to ".google.com", all with the domain name "google.com" ending can access the Cookie. Note that the first character must be. ""
boolean httponly Limited to the browser console to get the key, but not to limit the capture tool.

 

4. Remove cookie

Zimbabwe Logout DEF (Request): 
    REP = redirect ( "/ the Login /") 
    rep.delete_cookie ( "the User") # delete usercookie values previously set on the user's browser to 
    return rep

cookie validation examples

# Cookie validation 
DEF login_required (Fn): 
    DEF Inner (Request): 
        IF request.COOKIES.get ( 'the set_cookie') == '111': 
            RET = Fn (Request) 
            # successful verification 
            return RET 
        the else: 
            # verification fails, obtaining current click interface, for later log jump 
            info = request.path_info 
            return the redirect ( '/ MainApp / Login / = {} Next?' the format (info).) 
    return Inner 

DEF Login (Request): 
    IF == request.method 'the POST': 
        name = request.POST.get ( 'name') 
        pwd = request.POST.get ( 'pwd') 
        Next request.GET.get = ( 'Next') 
        IF name == 'Matt' and pwd = = '123':
            if next:
                ret = redirect('%s'%next)
            else:
                ret = redirect('/mainapp/author/')
            ret.set_cookie('set_cookie', '111')
            return ret
        else:
            return render(request, 'login.html')
    return render(request, 'login.html')

二  session

session stored in the database

Cookie solves the "hold" requirements to some extent, but due to the 4096 byte maximum support itself Cookie, Cookie and stored in the client itself, may be intercepted or stolen.

session is at the request arrives, through SessionMiddleWare middleware, before carrying out the view function is executed, did some operations. In the Cookie it generates a random string as a session id (Cookie to each client is assigned a unique ID), and randomized key-value process, stored in the server (django present django_session default list).

Summary: Cookie HTTP stateless make up for the shortage, let the server know to the people "who"; however Cookie in the form of text stored locally, poor security itself, and the text under capacity; Session can encrypt data, You can save more than 4096 bytes of text. Cookie and Session are common, and the language is not limited to the frame.

1. session method

# Get, set, delete data in the Session 
makes request.session [ 'K1'] 
request.session.get ( 'K1', None) 
makes request.session [ 'K1'] = 123 
request.session.setdefault ( 'K1', 123 ) # is not set exists 
del makes request.session [ 'K1'] 

# all the keys, the key-value pair 
request.session.keys () 
request.session.values () 
request.session.items () 
request.session.iterkeys () 
request.session.itervalues () 
request.session.iteritems () 

# session session of Key 
request.session.session_key 

# All session expiration date less than the current date data deletion 
request.session.clear_expired () 

# check session session of key exists in the database 
request.session.exists ( "session_key") 

# delete all data in the current session session 
request.session.delete ()
  
# Delete the current session data and delete the Cookie session. 
request.session.flush () 
    This is used to ensure that the previous session data can not be accessed again the user's browser, 
    for example, django.contrib.auth.logout () function is called it. 

# Set the Session and Cookie timeout 
request.session.set_expiry (value) 
    * If the value is an integer, session will expire after some number of seconds. 
    * If the value is datatime or timedelta, session will expire after this time. 
    * If the value is 0, the user closes the browser session will fail. 
    * If the value is None, session will depend on the global session expiration policy.

2. session configuration

Global View

from django.conf import global_settings

session global configuration

1. Database the Session 
SESSION_ENGINE = 'django.contrib.sessions.backends.db' # engine (default) 

2. Cache the Session 
SESSION_ENGINE = 'django.contrib.sessions.backends.cache' # engine 
used by the cache SESSION_CACHE_ALIAS = 'default' # alias (default cache memory, may be memcache), provided by the alias cache dependency 

3. file the Session 
SESSION_ENGINE = 'django.contrib.sessions.backends.file' engine # 
SESSION_FILE_PATH = None # cache file path, if None, using tempfile module obtains a temporary address tempfile.gettempdir () 

4. + database cache 
SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db' # engine 

5. the Session encrypted cookies 
SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies 'engine #
 
other public settings:
Key when SESSION_COOKIE_NAME = "sessionid" # Session's cookie on the browser, namely: sessionid = random string (the default) 
SESSION_COOKIE_PATH = "/" # saved Session cookie path (default) 
SESSION_COOKIE_DOMAIN = None # Session of the cookie save the domain name (the default) 
SESSION_COOKIE_SECURE = False # whether Https transfer cookie (default) 
SESSION_COOKIE_HTTPONLY = True # whether the Session cookie only supports http transmission (default) 
SESSION_COOKIE_AGE = 1209600 # Session of cookie expiration date (two weeks) (default) 
SESSION_EXPIRE_AT_BROWSER_CLOSE is = False # whether to close the browser makes Session expired (default) 
SESSION_SAVE_EVERY_REQUEST = False # whether to save the Session each request, only after saving changes to the default (default)

Examples of verification session

 

# Session authentication 
DEF login_required (Fn): 
    DEF Inner (Request): 
        # request.COOKIES.get IF ( 'the set_cookie') == '111': 
        IF request.session.get ( 'set_session') == '111': 
            the Fn = RET (Request) 
            # verify successful 
            return RET 
        the else: 
            # validation fails, get the current click interface for future Login Jump 
            info = request.path_info 
            return redirect ( '/ MainApp / the Login / = {} the Next?' format. (info)) 
    return Inner 

DEF Login (Request): 
    IF request.method == 'the POST': 
        name = request.POST.get ( 'name') 
        pwd = request.POST.get ( 'pwd') 
        Next = Request. GET.get ( 'next') 
        IF name == 'matt'and pwd == '123':
            request.session['set_session'] = '111'
            if next:
                ret = redirect('%s' % next)
            else:
                ret = redirect('/mainapp/author/')
            # ret.set_cookie('set_cookie', '111')
            return ret
        else:
            return render(request, 'login.html')
    return render(request, 'login.html')

@login_required
def author(request):
    obj = models.Author.objects.all()
    return render(request, 'author.html', {'obj': obj})

3. Supplement

  • csrf_protect, forced to current function CSRF prevention function, even if there is no intermediate settings in global settings.
  • csrf_exempt, it cancels the current function CSRF prevention function, even if the global settings set in the middleware.
    from django.views.decorators.csrf import csrf_exempt, csrf_protect
    from django.utils.decorators import method_decorator

Three middleware

Middleware is a frame-level requests and responses Django hooks are used. It is a lightweight, low-level plug-in system, for changing the input and output of Django globally. Middleware is a view before performing the function can do and after some additional operations performed, it is essentially a custom class, class defines several methods, Django framework to carry out these methods at a particular time of the request.

1. Role

  • IP restrictions, frequent login restrictions
  • Detection session
  • Cache, the client request, the middleware to see if there is cache data, if returned directly to the client, the logic did not go layer performs a function of view

2. Custom Middleware

Middleware can define five methods, namely :( main thing is process_request and process_response)

  • process_request(self,request)
  • process_view(self, request, view_func, view_args, view_kwargs)
  • process_template_response(self,request,response)
  • process_exception(self, request, exception)
  • process_response(self, request, response)

Sign in middleware setting.py

= MIDDLEWARE [ 
    ... 'django.middleware.clickjacking.XFrameOptionsMiddleware', 
    'app01.views.CustomizeMiddleware' # create custom middleware classes (class name + path) 
]

2.1 request_process(self,request)

  • In the URL parsing, executed before the view function.
  • Positive sequence execution
  • The request is transmitted between different middleware same object
  • If the return value Httpresponse, direct execution of the current method process_response middleware.
    Import the HttpResponse django.shortcuts from 
    MiddlewareMixin from django.utils.deprecation Import 
    class CustomizeMiddleware (MiddlewareMixin): 
        DEF process_request (Self, Request): 
            allowed_ip = [ '192.168.1.1',] 
            # allow / deny access ip address list, the request is determined ip, release / blocking 
            IF request.META.get ( 'REMOTE_ADDR') not in allowed_ip: 
                return HttpResponse ( 'your IP address does not have access') 
            the else: 
                return None

2.2 process_view(self, request, view_func, view_args, view_kwargs)

request is the HttpRequest object. 
view_func is Django view function that will be used. (Which is actually a function of the object, rather than as a function of the name string.) 
View_args position parameter list is passed to the view. 
View_kwargs keyword dictionary is passed to the view parameters. view_args and view_kwargs not contain the first view parameter (request).
  • After the URL parsing, executed before the view function.
  • Positive sequence execution
  • If the return value Httpresponse, direct execution method process_response bottom middleware.

2.3 process_exception(self, request, exception)

request: HttpRequest objects 
exception: Exception function abnormality generated Object View.

Abnormal view, is executed, the default is not performed

django.shortcuts Import HttpResponse from 
class CustomizeMiddleware (MiddlewareMixin): 

    DEF process_exception (Self, Request, Exception): 
        return HttpResponse ( 'when dealing with middleware, an exception is thrown, it will go here oh ~')
  • In the URL parsing, executed after the view function.
  • Reverse execution
  • If the return value Httpresponse, direct execution method process_response bottom middleware.

2.4 process_template_response (self, request, response) (rarely used)

request: HttpRequest Object 
response: TemplateResponse object (generated by the view function or middleware)

After performing the view function, executed immediately middleware process_template_response method, a reverse order, performing first CustomizeMiddleware3, and then CustomizeMiddleware2 performed, followed by performing a render method returns HttpResponse object view function returns a new HttpResponse object, the method is then performed process_response middleware.

2.5 process_response(self, request, response)

CustomizeMiddleware class (MiddlewareMixin): 

    DEF process_response (Self, Request, Response): 
        Print ( 'some logic processing conditions ......') 
        return Response
  • In the URL parsing, executed after the view function.
  • Reverse execution

Example:

class MD1(MiddlewareMixin):

    def process_request(self, request):
        print("MD1里面的 process_request")

    def process_response(self, request, response):
        print("MD1里面的 process_response")
        return response

    def process_view(self, request, view_func, view_args, view_kwargs):
        print("-" * 80)
        print("MD1 中的process_view")
        print(view_func, view_func.__name__)

    def process_exception(self, request, exception):
        print(exception)
        print("MD1 中的process_exception")
        return HttpResponse(str(exception))

    def process_template_response(self, request, response):
        print("MD1 中的process_template_response")
        return response

class MD2(MiddlewareMixin):
    def process_request(self, request):
        print("MD2里面的 process_request")
        pass

    def process_response(self, request, response):
        print("MD2里面的 process_response")
        return response

    def process_view(self, request, view_func, view_args, view_kwargs):
        print("-" * 80)
        print("MD2 中的process_view")
        print(view_func, view_func.__name__)

    def process_exception(self, request, exception):
        print(exception)
        print("MD2 中的process_exception")

    def process_template_response(self, request, response):
        print("MD2 中的process_template_response")
        return response

views.py in:

def index(request):
    print("app01 中的 index视图")

    def render():
        print("in index/render")
        return HttpResponse("O98K")
    rep = HttpResponse("OK")
    rep.render = render
    return rep

 

Access the index view, the result output terminal:

MD2 inside process_request 
MD1 inside process_request 
------------------------------------------ -------------------------------------- 
MD2 in process_view 
<function index AT 0x000001C111B97488> index 
- -------------------------------------------------- ----------------------------- 
MDl in process_view 
<AT 0x000001C111B97488 function index> index 
app01 the index view 
process_template_response MD1 in 
MD2 the process_template_response 
in index / the render 
MD1 inside process_response 
MD2 inside process_response

Example:

from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import redirect, HttpResponse, render
import time
# session验证
class MD1(MiddlewareMixin):
    black_list = ['/press/']
    white_list = ['/mainapp/login/']

    def process_request(self, request):
        info = request.path_info
        if request.session.get('set_session') == '111' or info in self.white_list:
            return None
        else:
            return redirect('/mainapp/login/?next={}'.format(info))
# 10s内请求不能超过三次
class Ipcount(MiddlewareMixin):
    ip_list = {}
    def process_request(self, request):
        ip_name = request.META.get('REMOTA_ADDR')
        if ip_name in self.ip_list:
            time_list = self.ip_list[ip_name]
            time_list.append(time.time())
            if len(time_list) > 3:
                if time_list[-1] - time_list[0] < 10:
                    time_list.pop()
                    return HttpResponse('太频繁')
                else:
                    time_list.pop(0)
        else:
            self.ip_list[ip_name] = [time.time()]

3. Implementation Process

 4. Process Django with middleware

 

Guess you like

Origin www.cnblogs.com/FangYi0328/p/11746353.html