Python - day64 (cookie with the session, middleware)

1. Templates (always the effect of rendering the page)

1.1 Basic Data Types

Variables, lists, dictionaries, dictionaries list set

1.2 Master

layout.html page layout

{%block mycss%}

{%endblock%}

Child inherits:

{% extends “layout.html”%}

{%block mycss%}
  link
  script src
{%endblock%}

1.3 Import

I wrote a very beautiful html code (html page)

{% the include "html page"%}

1.4 Built-in functions

{Name {|}} Upper     # The name of the capital 

{{name | Lower}}      #   the name lowercase 

{{name | First | Upper}}   # Take the first letter capitalized and 
 
{{name | title}}       # the first name full capitalization 
 
{{name | truncatewords: ' 2 ' }}   # the this XXX yyy ==== >>> the this IS IS ... 

{{the ctime | DATE: " Ymd H: I: S " }}   # time format

1.5 custom function

simple_filter

simple_tag

 1.5.1 Configuration

a, create templatetags module in the app

b. Create xx.py

1.5.2 Use

1. simple_filter

from django import template

register = template.Library()

@register.filter()
def my_func(val, arg1):
    return val + arg1




Note:
1. Only one parameter passed
2. no spaces between the function name and parameters
Usage:
{XX% Load%}
{{name | my_func: 'kkkk'}}

2. simple_tag

from django import template

register = template.Library()

@register.simple_tag()
def my_func(val, arg1):
    return val + arg1

用法:
    {% load xx %}
    {% my_tag 'zekai' 'is' 'jjj' %}

2. cookie与session

2.1 What is a cookie 

Cookie is a key-value structure, similar to a dictionary in python. Sent to the client browser with the server's response. Then the client browser will save up Cookie, next time again to access the server and then the Cookie sent to the server. Cookie is created by the server, and then sent to a client by responding to the key pair. The client will save Cookie, and will mark the source of Cookie (Cookie which server). When the client makes a request to the server will send all the servers Cookie contained in the request to the server so that the server can identify a client!

2.2 cookie principles

Works cookie is: generated content from the server, the browser receives the request saved locally; when the browser visits, the browser will automatically bring the Cookie, so the server can be judged by the content of this Cookie "who "a.

2.3 Django cookie in operation

2.3.1 acquisition cookie

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

2.3.1 set a cookie

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

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

2.3.3 Parameter Description

key, the key 
value = '' , the value of 
the max_age = None, cookie timeout continuation time required (in seconds) If the parameter is \ None``, the cookie to the browser will continue closes the 
Expires = None, timeout ( the requires the Expires IE, the SET IT SO IF hasn ' t been already). 
path = ' / ' , which entered into force Cookie path, / represents the root path, special: cookie root path can only be accessed any url of the page, the browser the cookie back to the page with the path to avoid other applications cookie will be passed to the site. 
domain domain = None, Cookie take effect You can use this parameter to construct a cross-site cookie. Such as, Domain = " .example.com " constructed cookie on these sites is readable following: www.example.com, www2.example.com and an.other.sub.domain.example.com. If this parameter is set to None, cookie can only be read by setting its sites 
Secure =False, the browser will be passed back and forth over HTTPS cookie 
HttpOnly = False only http protocol transmission, JavaScript can not be acquired (not absolute, can get to the bottom of capture may be covered)

2.3.4 delete cookie

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

 

2.4 session

2.4.1 Basic use

# 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 ) # presence is not set 
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 () 

#Random string of user session 
request.session.session_key 

# all Session expiration date than the current date data deletion 
request.session.clear_expired () 

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

# delete all data in the current session of session (only delete database) 
request.session.delete () 
  
# delete the current session data and deletes the session cookie (cookie and database are deleted). 
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 Session 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.4.2 session configuration

1 . Database the Session 
SESSION_ENGINE = ' django.contrib.sessions.backends.db '    # engine (default)
 
2 . Caching the Session 
SESSION_ENGINE = ' django.contrib.sessions.backends.cache '   # engine 
SESSION_CACHE_ALIAS = ' default '                             # cache used 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. + cache database 
SESSION_ENGINE = ' django.contrib.sessions.backends.cached_db '         # engine
 
5 . Encrypt the Session cookies 
SESSION_ENGINE = ' Django .contrib.sessions.backends.signed_cookies '    # engine 

other public settings: 
SESSION_COOKIE_NAME = " sessionid "                        # the Session's cookie when a key on the browser, namely: sessionid = random string (the default) 
SESSION_COOKIE_PATH = " / "                                # save the cookie path Session of the (default) 
SESSION_COOKIE_DOMAIN = None                             # Session saved cookie domain (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                   # if you close the browser makes Session expired (default) 
SESSION_SAVE_EVERY_REQUEST = False                        # whether each request save Session, was saved after modifying default (default)

3. Middleware (life cycle Django request)

3.1 What are the middleware

Middleware name implies, is interposed between a processing request and response process, relatively lightweight, and changes the input and output on the global django

- class class 

    process_request: the request must go through a method 
    process_response: This method must go through a response 

    process_view

3.2 Middleware position

settings:    
            MIDDLEWARE = [
                'django.middleware.security.SecurityMiddleware',
                'django.contrib.sessions.middleware.SessionMiddleware',
                'django.middleware.common.CommonMiddleware',
                'django.middleware.csrf.CsrfViewMiddleware',
                'django.contrib.auth.middleware.AuthenticationMiddleware',
                'django.contrib.messages.middleware.MessageMiddleware',
                'django.middleware.clickjacking.XFrameOptionsMiddleware',
                'm1.M1',
                'm2.M2'
            ]

3.3 Application

Preprocessing time, the code is written in the middleware
determines whether the value of the IP blacklist

 

 

 

 

 4. MTV MTV and

MVC: 
    
    Design Patterns project directory structure of 
    
    
    customers        ------ ordering --------> ------ waiter needs treatment menu --------> cook
                <--- --------------- <-------------------------         
    
    (browser)   ----- --------------> functions or handling ------------------>   database 
                                       business logic 
    views: Controllers Models: 
                                        loginController.py LoginModel .py 
                                        UserController.py UserModel.py 
        a lot of html page                          
        
    
MVC 
    
    Django: 
        M: Models
        T: Templates (various html page) corresponding to views
        V: Views (view handler) corresponds controllers

 

Guess you like

Origin www.cnblogs.com/wangyong123/p/11207123.html