Django implements cookie & session and authentication system, djangocookie
COOKIE & SESSION knowledge reserve
Because the http protocol is unable to maintain the status, but in the actual situation, we need to "maintain the status", so cookie is born in such a scenario.
Cookie: The content generated by the server is stored locally after the browser receives the request. When the browser accesses the content again, the browser automatically carries the cookie, in this way, the server can determine who the cookie is.
Although the cookie meets the "persistence" requirement to some extent, the cookie itself supports a maximum of 4096 bytes and the cookie itself is stored on the client, which may be intercepted or stolen, therefore, there is a need for something new. It supports more bytes and stores them on the server, providing high security. This is the session.
The problem arises. Based on the stateless features of http, the server does not know who the visitor is ". Therefore, the cookie mentioned above serves as a bridge.
We can assign a unique id to each client's cookie, so that the server will know who the user is when accessing the cookie ". Then, we store confidential information on the server based on different cookie IDs, such as "account and password.
Summary: cookies make up for the lack of http stateless, so that the server can know who it is. However, cookies are stored locally in the form of text, and their security is poor; therefore, we use cookies to identify different users and store private information in sessions and texts of over 4096 bytes.
Django implements COOKIE setting
Obj = HttpResponse (...) or obj = render (request,...) or obj = redirect () obj. set_cookie (key, value ,...)
Obj. set_signed_cookie (key, value, salt=
'Encrypted salan'
,...)
Get cookie
request.COOKIES.get('key')
request.get_signed_cookie(key, default=
RAISE_ERROR, salt
=
'', max_age
=
None
)
Delete cookie
response.delete_cookie("cookie_key",path="/",domain=name)
Parameters
Key, key value = '', value max_age = None, ultra-long expires = None, ultra-long path = '/', Cookie effective path, the browser will only send the cookie back to the page with this path, so as to avoid passing the cookie to other applications on the site. /Indicates the root path. Special: the cookie of the root path can be accessed by any url page. domain = None. You can use this parameter to construct a cross-site Cookie. For example, the cookie constructed by domain = ".example.com" is readable for the following websites: www.example.com, www2.example.com, and an.other.sub.domain.example.com. If this parameter is set to None, the cookie can only be read by the site where it is set. Secure = False. If it is set to True, the browser will pass the cookie back and forth through HTTPS. Httponly = False can only be transmitted over http and cannot be obtained by JavaScript (not absolute, it can be obtained or overwritten by capturing packets at the underlying layer.
$.cookie("key", value,{ path: '/' })
Jquery operation cookieDjango implements SESSION setting
Request. session ['key'] = 'value' ''' actual operations: 1. check whether the request has a sessionid and whether it exists with the database. If yes, update session_data. if not, a random string is created. set_cookie ('sessionid', 'random string') 4. in the session table, add the random session-key session-data string {"key": "value"} ----------- ''' after processing '''
Get Session
Session_name = request. session ['key'] ''': 1. random string request. COOKIE. get ('sessionid') 2. filter in the session table: obj = django-session.objects.filter (session-key = random_str ). first () obj. session-data.get ("user ")'''
Others
# Delete the Sessions value del request. session ["session_name"] # Check whether the session value if "session_name" is request. session:
Configuration
Django supports sessions by default, and stores Session data in the database by default, that is, the django_session table. A. configure settings. py SESSION_ENGINE = 'django. contrib. sessions. backends. db' # Engine (default) SESSION_COOKIE_NAME = "sessionid" # Session cookie key stored in the browser, that is, sessionid = random string (default) SESSION_COOKIE_PATH = "/" # path for saving Session cookies (default) SESSION_COOKIE_DOMAIN = None # domain name for storing Session cookies (default) SESSION_COOKIE_SECURE = False # Whether to transmit cookies over Https (default) SESSION_COOKIE_HTTPONLY = True # Whether Session 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 disable the browser to make the Session expire (default) SESSION_SAVE_EVERY_REQUEST = False # Whether to save the Session for each request. It is saved only after modification by default (default)
Database Configuration (configuration)
A. configure settings. py SESSION_ENGINE = 'django. contrib. sessions. backends. cache '# Engine SESSION_CACHE_ALIAS = 'default' # The cache alias used (default memory cache, or memcache ), here, the alias depends on the cache settings SESSION_COOKIE_NAME = "sessionid" # The Session cookie key stored in the browser, that is: sessionid = random string SESSION_COOKIE_PATH = "/" # Session's cookie storage path SESSION_COOKIE_DOMAIN = None # Session's cookie storage domain name SESSION_COOKIE_SECURE = False # Https transmission cookie SESSION_COOKIE_HTTPONLY = True # Session? the cookie only supports http transmission of SESSION_COOKIE_AGE = 1209600 # Session cookie expiration date (2 weeks) SESSION_EXPIRE_AT_BROWSER_CLOSE = False # whether to close the browser to make the Session expire SESSION_SAVE_EVERY_REQUEST = False # Whether to save the Session for each request. It is saved only after modification by default.
Cache Configuration
A. configure settings. py SESSION_ENGINE = 'django. contrib. sessions. backends. file' # Engine SESSION_FILE_PATH = None # cache file path. If it is None, use the tempfile module to obtain a temporary address tempfile. gettempdir () SESSION_COOKIE_NAME = "sessionid" # key of Session cookie stored in the browser, that is: sessionid = random string SESSION_COOKIE_PATH = "/" # Session's cookie storage path SESSION_COOKIE_DOMAIN = None # Session's cookie storage domain name SESSION_COOKIE_SECURE = False # Https transmission cookie SESSION_COOKIE_HTTPONLY = True # Session? the cookie only supports http transmission of SESSION_COOKIE_AGE = 1209600 # Session cookie expiration date (2 weeks) SESSION_EXPIRE_AT_BROWSER_CLOSE = False # whether to close the browser to make the Session expire SESSION_SAVE_EVERY_REQUEST = False # Whether to save the Session for each request. It is saved only after modification by default.
File Configuration
def login_session(request): if request.method=='POST': user=request.POST.get('user') pwd=request.POST.get('pwd') ret=UserInfo.objects.filter(name=user,pwd=pwd) if ret: request.session['user']=user return redirect('/index_session/') return render(request,'login.html')def index_session(request): user=request.session.get('user') if not user: return redirect('/login_session/') return render(request,'index.html',locals())
View CodeDjango user authentication auth
Use some methods in the auth module to authenticate from django. contrib import auth
Authenticate ()
User authentication is provided, that is, to verify whether the user name and password are correct. Generally, two keyword parameters, username and password, are required.
If the authentication information is valid, a User object is returned. Authenticate () sets an attribute on the User object to identify the authentication backend that authenticates the User, and this information is required in the subsequent login process. When we try to log on to a User object that is directly retrieved from the database without going through authenticate (), an error will be reported.
user = authenticate(username='someone',password='somepassword')
Login (HttpRequest, user)
This function accepts an HttpRequest object and an authenticated User object.
This function uses the django session framework to append session id and other information to an authenticated user.
login(request, user)
Logout (request)
This function accepts an HttpRequest object and has no return value. When this function is called, all session information of the current request is cleared. This function does not return an error even if the user does not log on.
logout(request)
User object
User object attributes:
Username, password (required) password is saved to the database using the hash algorithm
Is_staff: whether the user has the permission to manage the website.
Is_active: whether to allow user logon. Set this parameter to ''false''. You do not need to delete a user to disable user logon.
Is_authenticated ()
If it is a real User object, the return value is always True. Used to check whether the user has passed the authentication.
Passing authentication does not mean that the user has any permissions or even does not check whether the user is activated. This only indicates that the user has successfully passed the authentication. This method is very important. In the background, use request. user. is_authenticated () to determine whether the user has logged on. If it is true, the request. user. name can be displayed to the foreground.
if not request.user.is_authenticated(): return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))
Django comes with the decorator for this situation: login_requierd ()
from django.contrib.auth.decorators import login_required @login_requireddef my_view(request):
If the user does not log on, the default django logon URL '/accounts/login/' will be redirected (this value can be modified through LOGIN_URL in the settings file ). And pass the absolute path of the current access url (after successful login, it will be redirected to this path ).
Create user
from django.contrib.auth.models import Useruser = User.objects.create_user(username='',password='',email='')
Change Password set_password ()
user = User.objects.get(username='')user.set_password(password='')user.save
Check_password (passwd)
When you need to change the password, you must first ask the user to enter the original password. If the given string passes the password check, returnTrue
Login Based on auth authentication:
Def login (request): ''' logon verification: param request: return: ''' if request. method = 'post': username = request. POST. get ('username') pwd = request. POST. get ('pwd') input_valid_code = request. POST. get ('valid _ Code') valid_code = request. session. get ('valid _ Code') login_response = {'user': None, 'error _ msg ': ''} # Compare verification codes. if valid_code.upper () = input_valid_code.upper (): user = auth. authenticate (username = username, password = pwd) If user: auth. login (request, user) login_response ['user'] = user. username else: login_response ['error _ msg '] = 'user name or Password error! 'Else: login_response ['error _ msg '] = 'verification code error! 'Import json return HttpResponse (json. dumps (login_response) return render(request,'login.html ', locals ())