django study notes day 5

Summary of knowledge points

- Session
- CSRF
- Model Operation
- Form Validation (ModelForm)
- Middleware
- Cache
- Signal


Details:

1. When Session
is used for user authentication based on cookies: sensitive information is not suitable to be placed in cookies

a. Session principle
Cookie is a key-value pair saved on the user's browser.
Session is a key-value pair saved on the server side.

b. Comparison between Cookie and Session

c. Session configuration (lack of cache)

d. Example: to achieve two-week automatic login
- request. session.set_expiry(60*10)
- SESSION_SAVE_EVERY_REQUEST = True

PS: If a timeout is not set in the cookie, it means that the browser is automatically cleared when the browser is closed


- session depends on cookies
- basic server session operations
# Get, set, delete data in Session
request.session['k1']
request.session.get(' k1',None)
request.session['k1'] = 123
request.session.setdefault('k1',123) # If it exists, do not set
del request.session['k1']

# All key, value, key-value pairs
request.session.keys()
request.session.values()
request.session.items()
request.session.iterkeys()
request.session.itervalues()
request.session.iteritems() # Random string request


of user session
.session.session_key

# Delete all data whose session expiration date is less than the current date
request.session.clear_expired()

# Check whether the random string of the user session is in the database
request.session.exists("session_key")

# Delete all session data of the current user and use
request.session.clear()
request.session.delete("session_key")

request.session.set_expiry(value)
* if value is an integer, the session will expire after some number of seconds.
* If value is a datatime or timedelta, the session will expire after this time.
* If the value is 0, the user closes the browser session will be invalid.
* If the value is None, the session will rely on the global session invalidation policy.

- The default operation is set in the configuration file (general configuration):
SESSION_COOKIE_NAME = "sessionid" # The key when the session's cookie is saved on the browser, namely: sessionid = random string (default)
SESSION_COOKIE_PATH = "/" # The session's cookie is saved The path (default)
SESSION_COOKIE_DOMAIN = None # The domain name of the session's cookie storage (default)
SESSION_COOKIE_SECURE = False # Whether Https transmits cookies (default)
SESSION_COOKIE_HTTPONLY = True # Whether the session's cookies only support http transmission (default)
SESSION_COOKIE_AGE = 1209600 # Session cookie expiration date (2 weeks) (default)
SESSION_EXPIRE_AT_BROWSER_CLOSE = False # Whether to close the browser to make the session expire (default)
# set_cookie('k',123)
SESSION_SAVE_EVERY_REQUEST = False # Whether to save the session for each request , save after modification by default (if this is True, each time the page is retrieved, the session will expire after a specified time delay)

- Engine configuration
Default
SESSION_ENGINE = 'django.contrib.sessions.backends.db' # Engine (default)
cache
SESSION_ENGINE = 'django.contrib.sessions.backends.cache' # Engine
SESSION_CACHE_ALIAS = 'default' #
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': [
'172.19.26.240:11211',
'172.19.26.242:11211',
]
}
'db1 ': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': [
'172.19.26.240:11211',
'172.19.26.242:11211',
]
}
}
The cache alias used (default memory cache, or memcache), where the alias depends on the cache settings
File session
SESSION_ENGINE = 'django.contrib.sessions.backends.file' # Engine
SESSION_FILE_PATH = None # Cache file path, if None, use tempfile module to get a temporary address tempfile.gettempdir()
cache plus database
SESSION_ENGINE = 'django.contrib. sessions.backends.cached_db' # engine
encrypted cookies Session
SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies' # engine

2. CSRF
a. CSRF principle
The browser returns a random string when the page is retrieved for the first time, and the string needs to be submitted when submitting data later, otherwise it will
return this string when an error is reported. In the cookie,
when using form to submit:
{% csrf_token %}
b. There are hidden dangers when there is no CSRF

c. Form submission (CSRF)

d. Ajax submission (CSRF)
CSRF request header X-CSRFToken
e. Solutions for individual pages that require csrf authentication
django implements the function of preventing cross-site request forgery for users, through the middleware django.middleware.csrf .CsrfViewMiddleware to complete. The anti-cross-site request forgery function in django is divided into global and local.
Global:
  Middleware django.middleware.csrf.CsrfViewMiddleware
Local:
@csrf_protect, forcibly set the anti-cross-site request forgery function for the current function, even if the global middleware is not set in the settings.
@csrf_exempt, cancel the anti-cross-site request forgery function of the current function, even if the global middleware is set in the settings.
Note: from django.views.decorators.csrf import csrf_exempt,csrf_protect
ajax add
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr .setRequestHeader("X-CSRFToken", csrftoken);
}
}
});

6. Middleware

7. Cache
5 configurations and
3 applications:
global
view function
template

8. Signal
- built-in signal
- custom
- define signal
- send signal
- register function in signal

3. Model operation

a. Field type + parameter

b. Connect table fields + parameters

c. Target

d. SQL operations:
- Basic addition, deletion, modification and query -
Advanced operations
- Positive and negative queries
- Other operations

e. Validation (weak)

4. Form operation
Complete:
- Validate user request
- Generate HTML
(retain the last submitted data)

Custom:
- Class
- Field (validation)
- Plugin (Generate HTML)

Initialization operation:



========= ==== Job: xxxoo management ==============
User authentication: session
new URL: Form authentication
middleware: IP filter
signal: record operation
CSRF:

a. Form authentication user request

b. Form generates HTML

c. Form field details (custom fields, Model...) + plugin

d. Custom validation (hooks and __all__)

e. Registration example:
username, password, email, mobile number (RegexValidator or RegexField), gender, hobby, city

f. Initialization value

5. ModelForm

a. Model+Form function collection

b. save

c. save + save_m2m

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325693111&siteId=291194637