django templates, built-in functions, custom functions son, cookie and session

In Django template into the motherboard and daughterboard daughterboard inherited style template.

Rendering basic types of data: variables, lists, dictionaries, dictionaries list sets.

Motherboard act as page layout, rendering the daughter board coming back data. Daughter board need to use a motherboard style. Use: {% extends "layout.html"%}

Css style motherboard using inheritance: {% block mycss%} {% endblock%}

Inheriting body motherboard: {% block cotent%} {% endblock%}

Inheritance style motherboard js: {% block myjs%} {% endblock%}

Template Import: When we wrote a very beautiful html code, if we want to use in the project can come in import

Use: {% include "html page"%}

Built-in functions:

In Django built-in function to the data for our rendering operations.

For example, the case of the control data, in python, we are using: str (name) .upper lowercase: str (name) .lower.

It is used in the module:

    {{ name|upper }}
    {{ name|lower }}
    {{ name|first|upper }}
    {{ name|title }}
    {{ name|truncatewords:'2' }}

We can also customize the built-in functions to meet our needs,

- Custom Function 
            configuration: 
                A, creating the templatetags module app 

                b Create xx.py.
            
            
             - simple_filter: 
                
                from Django Import Template 
                Register = template.Library () 
                @ register.filter () 
                DEF my_func (Val, arg1):
                     return Val + arg1 
                Note:
                     1 can only pass a parameter.
                     2 can not have spaces between the function name and the parameters. 
                usage: 
                    { % Load XX% } 
                    {{name | my_func: 'kkkk'}}
            - simple_tag:
                from django import template
                register = template.L
                ibrary()
                @register.simple_tag()
                def my_func(val, arg1):
                    return val + arg1
                用法:
                    {% load xx %}
                    {% my_tag 'zekai' 'is' 'jjj' %}

cookie和session

cookie and session principle is: cookie exists with the client browser k, v key-value pairs, session is a presence server stores a user key to sensitive information, k, is the value of the cookie, the user landed when a cookie is sent over the server for comparison, representing over after the user is a legitimate user, you do not need to enter the account password to log in, if there is no cookie let users return to log in again.

session:

Key containing user sensitive information exists in the server for 
                
                { 
                    "Cookie value": { "name": 'Zekai', ' Age': 18 is}, 
                    "Cookie value. 1": { "name": 'zekai2', ' Age ': 34 is}, 
                    "Cookie value 2": { "name":' zekai3 ', ' Age ': 45}, 
                    "Cookie value. 3": { "name":' zekai4 ', ' Age ': 56 is}, 
                }

When we generated session will automatically help us generate a cookie.

Generate session:

 request.session['name'] = username
            request.session['pwd'] = pwd
            request.session['age'] = 12

session stored in relational database tables in Django-session,

In a relational database session is stored on the hard disk, such as mysql sqllite oracle, db2 

In the non-relational database based session storage memory: redis, mongdb memcache

# Random string of user session 
            request.session.session_key 
     
            # The expiration date less than the current date data to remove all the Session 
            request.session.clear_expired () 
     
            # random string to check whether the user session in the database 
            request.session.exists ( " session_key " ) 
     
            # delete all current Session data users 
            request.session.delete ( " session_key " ) 
     
            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.
            

Available storage media, we can generate sesion set in the settings in which:

SESSION_ENGINE = 1. ' django.contrib.sessions.backends.db '    # engine (default) 
     
                SESSION_COOKIE_NAME = " SessionID "                        # Key stored at the Session cookie on the browser, namely: sessionid = random string (default) 
                SESSION_COOKIE_PATH = " / "                                # save the cookie path of Session (the default) 
                SESSION_COOKIE_DOMAIN = None                              # saved Session of 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                        # is
            
     
            2. SESSION_ENGINE = ' django.contrib.sessions.backends.cache '   # engine 
                    SESSION_CACHE_ALIAS = ' default '                             # cache alias used (the default cache memory, may be memcache), provided by the alias cache dependency 
                 
                 
                    SESSION_COOKIE_NAME = " SessionID"                         # When the Session's cookie on the browser key, namely: sessionid = random string 
                    SESSION_COOKIE_PATH = " / "                                 # saved Session cookie path 
                    SESSION_COOKIE_DOMAIN = None                               # saved Session of cookie domain 
                    SESSION_COOKIE_SECURE = False                              # whether Https transfer cookie 
                    SESSION_COOKIE_HTTPONLY = True                             # whether the Session cookie only supports http transmission 
                    SESSION_COOKIE_AGE = 1209600                               # Session of cookie expiration date (two weeks)
                    = False SESSION_EXPIRE_AT_BROWSER_CLOSE is                    # whether the browser is closed so that the Session Expired 
                    SESSION_SAVE_EVERY_REQUEST = False                         # 
             
            3. SESSION_ENGINE = ' django.contrib.sessions.backends.file '     # engine 
                SESSION_FILE_PATH = None                                     # cache file path, if None, the obtaining module using a tempfile temporary address tempfile.gettempdir () # eg: / var / Folders / D3 / j9tj0gz93dg06bmwxmhh6_xm0000gn / T 
             
             
                SESSION_COOKIE_NAME = " SessionID "                           # the Session's cookie when the key on the browser, i.e.: sessionid = random string
                SESSION_COOKIE_PATH = " / "                                   # saved Session cookie path 
                SESSION_COOKIE_DOMAIN = None                                 # saved Session of cookie domain 
                SESSION_COOKIE_SECURE = False                                # whether Https transfer cookie 
                SESSION_COOKIE_HTTPONLY = True                               # whether the Session cookie only supports http transmission 
                SESSION_COOKIE_AGE = 1209600                                 # Session of cookie failure date (two weeks) 
                SESSION_EXPIRE_AT_BROWSER_CLOSE is = False                      # if you close the browser makes Session expired
                SESSION_SAVE_EVERY_REQUEST = False       
            
            4. 配置 settings.py
 
                SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db'        # 
            

Middleware (django request lifecycle)

We can customize it to your own middleware, do data preprocessing to determine whether the value of the IP blacklist. We need to configure settings in custom middleware good middleware:

import m1 
import m2
- 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' ]

MTV and MVC
former refers to the programming ideas in Django, the latter is referred to as a variety of other programming ideas.

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

 


 

Guess you like

Origin www.cnblogs.com/1624413646hxy/p/11210423.html