Transactions, caching

Source: Internet
Author: User
Tags sessions

Transaction:

The so-called transaction is: All steps of a process are either successful or all fail.

Example: Bank transfer

Transaction failure occurs when a transaction is rolled back: that is, if a step within a process has an error, the steps before the error occur successfully, but the error is rolled back, leaving all steps to fail.

ImportOSif __name__=='__main__': Os.environ.setdefault ("Django_settings_module","bms.settings")    ImportDjango Django.setup ()Importdatetime fromApp01ImportModelsTry:         fromDjango.dbImporttransaction with Transaction.atomic ():
Step Two Step Three
exceptException as E:Print(STR (e))

Cookies:

Cookie Origin:

Because HTTP is stateless, that is, each request is independent, its execution is not related to the previous request and the subsequent request, it is not affected by the previous request, and does not directly affect the subsequent requests.

For the server, each request is completely new.

The state can be understood as the data generated by the client and the server in a session, and the stateless is that the data is not retained. The data generated in the session sometimes we need to save, that is, to "keep the state." So the cookie was born.

What is a cookie:

A cookie specifically refers to a small piece of information, which is a set of group key-value pairs that the server sends out to store on the browser, and the browser automatically carries these key-value pairs the next time you access the server, so that the server can extract useful information.

The principle of cookies:

Cookie works: With the server to produce content, the browser will be forced to save the local, when the browser again access, the browser automatically bring cookies, so that the server can use the content of the cookie to determine this is "who".

View cookies:

We use the Chrome browser to open the developer tools (right-click Check).

Manipulating Cookies in Django:

To obtain a cookie:

Request. cookies['key']request.get_signed_cookie ('key', Default=raise_error, salt=", Max_age=none)

Parameters of the Get_signed_cookie method:

Default: Defaults

Salt: encrypted salt

Max_age: Background Control Expiration Time

Set Cookies:

Rep = HttpResponse (...) Rep = render (Request, ...) Rep.set_cookie (Key,value,...) Rep.set_signed_cookie (Key,value,salt=' encrypted salt ',...)

Parameters:

Key: Keys

Value: Values

Max_age: Timeout period

Expires=none, Time-out (IE requires expires, so set it if hasn ' t been already.)

Path= '/', Cookie takes effect path,/indicates root path, Special: The root path of the cookie can be accessed by any URL of the page

Domain=none, the domain name in which the cookie takes effect

Secure=false:https Transmission

Httponly=false can only be transmitted by the HTTP protocol and cannot be obtained by JavaScript (not absolutely, the underlying capture can be obtained or overwritten).

To delete a cookie:

def Logout (Request):     = Redirect ("/login/")    Rep.delete_cookie ("user")   #  Delete User's cookie value previously set on users ' browser    return Rep

Session:

Session Origin:

Although a cookie solves the "hold-state" requirement to some extent, the cookie itself supports a maximum of 4096 bytes, and the cookie itself is stored on the client side, which may be intercepted or stolen. Therefore, there is a need for a new thing, it can support to hold more bytes, and to be saved on the server, there is high security. This is the session.

Django Session-related methods:

#get, set, delete data in sessionrequest.session['K1']request.session.get ('K1', None) request.session['K1'] = 123Request.session.setdefault ('K1', 123)#exists then does not setdelrequest.session['K1']#all keys, values, key-value pairsRequest.session.keys () request.session.values () Request.session.items () Request.session.iterkeys () Request.session.itervalues () Request.session.iteritems ( )#session keyRequest.session.session_key#Delete all data with session expiration date less than current daterequest.session.clear_expired ()#Check if key in session is present in the databaseRequest.session.exists ("Session_key")#Delete all session data for current sessionsRequest.session.delete ()#deletes the current session data and deletes the session's cookie. Request.session.flush () This is used to ensure that the previous session data cannot be accessed again by the user's browser, for example, it is called in the Django.contrib.auth.logout () function. #set the timeout period for session sessions and cookiesRequest.session.set_expiry (value)*if value is an integer, the session will expire after a few seconds. *if value is a datatime or timedelta,session, it will expire after this time. *if value is 0, the user closes the browser session and expires. * If value is none,session, it will depend on the global session expiration policy.

Session Process and Analysis:

The session configuration in Django:

Sessiono is supported by default in Django, which provides 5 types of session for developers to use.

1. Database Sessionsession_engine='django.contrib.sessions.backends.db'   #engine (default)2. Cache Sessionsession_engine='Django.contrib.sessions.backends.cache'  #engineSession_cache_alias ='default'                            #the cache alias used (the default memory cache, or memcache), where the alias relies on the cached settings3. File Sessionsession_engine='Django.contrib.sessions.backends.file'    #engineSession_file_path = None#cache file path, if none, use the Tempfile module to get a temporary address tempfile.gettempdir ()4. Cache +Database Session_engine='django.contrib.sessions.backends.cached_db'        #engine5. Encryption Cookie Sessionsession_engine='django.contrib.sessions.backends.signed_cookies'   #engineOther common settings items: session_cookie_name ="SessionID"                       #session's cookie is stored on the browser when the key, namely: Sessionid= random string (default)Session_cookie_path ="/"                               #The path of the session's cookie Save (default)Session_cookie_domain = None#Session cookie saved domain name (default)Session_cookie_secure = False#whether HTTPS transmits cookies (default)Session_cookie_httponly = True#whether the session's cookie only supports HTTP transport (default)Session_cookie_age = 1209600#session's cookie expiration date (2 weeks) (default)Session_expire_at_browser_close = False#whether to close the browser so that the session expires (default)Session_save_every_request = False#whether the session is saved every time the request is modified, and then saved (by default)Django Session-related Settings
View Code

Transactions, caching

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.