Python Road _day71_django pagination and session Introduction

Source: Internet
Author: User
Tags configuration settings

One, Django paging

The following examples are custom paging:

"""example of using the paging component: Def index (request): obj = pagination (request). Get.get (' page ', 1), Len (user_list), request.path_info) page_user_list = user_list[obj.start:obj.end] page_html = OBJ.PA Ge_html () return render (Request, ' index.html ', {' users ':p age_user_list, ' page_html ':p age_html})"""classpagination (object):def __init__(self,current_page,all_count,base_url,per_page_num=10,pager_count=11):        """encapsulates paging-related data:p Aram Current_page: Current page:p Aram All_count: Total number of data bars in the database:p Aram Per_page_num: per page Number of data bars displayed:p Aram base_url: URL prefixes displayed in pagination:p Aram Pager_count: The maximum number of pages displayed"""        Try: Current_page=Int (current_page)exceptException as E:current_page= 1ifCurrent_page <1: Current_page= 1Self.current_page=current_page Self.all_count=All_count Self.per_page_num=Per_page_num Self.base_url=Base_url#Total Page NumberAll_pager, TMP =Divmod (All_count, Per_page_num)ifTmp:all_pager+ = 1Self.all_pager=All_pager Self.pager_count=Pager_count self.pager_count_half= Int ((pager_count-1)/2) @propertydefStart (self):return(self.current_page-1) *Self.per_page_num @propertydefEnd (self):returnSelf.current_page *Self.per_page_numdefpage_html (self):#if the total number of pages < 11:        ifSelf.all_pager <=Self.pager_count:pager_start= 1Pager_end= Self.all_pager + 1#Total page Numbers >        Else:            #Current page If a maximum of 11/2 page numbers are displayed on the <= page            ifSelf.current_page <=Self.pager_count_half:pager_start= 1Pager_end= Self.pager_count + 1#The current page is greater than 5            Else:                #page number over to the end                if(Self.current_page + self.pager_count_half) >Self.all_pager:pager_end= Self.all_pager + 1Pager_start= Self.all_pager-self.pager_count + 1Else: Pager_start= Self.current_page-self.pager_count_half pager_end= self.current_page + self.pager_count_half + 1page_html_list=[] First_page='<li><a href= "%s?page=%s" > Home </a></li>'% (self.base_url,1,) page_html_list.append (first_page)ifSelf.current_page <= 1: Prev_page='<li><a href= "#" > Prev </a></li>'        Else: Prev_page='<li><a href= "%s?page=%s" > Prev </a></li>'% (self.base_url,self.current_page-1,) page_html_list.append (prev_page) forIinchRange (Pager_start, pager_end):ifi = =self.current_page:temp='<li class= "active" ><a href= "%s?page=%s" >%s</a></li>'%(Self.base_url,i, I,)Else: Temp='<li><a href= "%s?page=%s" >%s</a></li>'%(Self.base_url,i, I,) page_html_list.append (temp)ifSelf.current_page >=Self.all_pager:next_page='<li><a href= "#" > Next </a></li>'        Else: Next_page='<li><a href= "%s?page=%s" > Next </a></li>'% (Self.base_url,self.current_page + 1,) page_html_list.append (next_page) last_page='<li><a href= "%s?page=%s" > Last </a></li>'%(Self.base_url,self.all_pager,) page_html_list.append (last_page)return "'. Join (Page_html_list)

The page_html () function in the above class returns the string containing the Li tag in the page list, and replaces it in the corresponding HTML file in the following way:

function to get the string:

The string is converted into HTML:

Second, Session Introduction

1. Cookie and Session comparison

(a) A cookie is a key-value pair stored on the browser side, while the session is a key-value pair on the server side of the save, but relies on cookies.

(b) In the case of login, the cookie is a key-value pair set in clear text after successful login, and the key-value pair is sent to the client, the plaintext information may be leaking and unsafe; The session generates a random string, which is sent to the user and written to the browser's cookie, and the server also saves one copy.

(c) At the time of login verification, the cookie: determines the key value of the cookie that accompanies the request when the browser sends it, and if so, validates the pass; session: Gets a random string in the cookie of the requesting user, Validates the corresponding value in the session based on a random string

2, session of the classification

As above, according to the session in the server to save the location of the following 5 kinds:

(1) Database session

As the name implies, the session value is stored in the database, Django default support session, and the default is to store session data in the database, namely: Django_session table. Before using this type of session, you need to create a table for the session by executing the following two commands. As follows:

Python manage.py Makemigrationspython manage.py Migrate

The basic file configuration for this type of session is as follows, in the configuration settings in the setting.py file:

Session_engine ='django.contrib.sessions.backends.db'   #engine (default)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)

The session is used as follows:

Set up:

Get:

Delete:

defIndex (Request):#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 set        delrequest.session['K1']         #all keys, values, key-value pairsRequest.session.keys () request.session.values () Request.session.items () request.session.i Terkeys () request.session.itervalues () Request.session.iteritems ( )#random string for user sessionRequest.session.session_key#Delete all data with session expiration date less than current daterequest.session.clear_expired ()#Check if the random string in the user session is in the databaseRequest.session.exists ("Session_key")         #Delete all session data for the current userRequest.session.delete ("Session_key") Request.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.

(2) Cache session

Use the same way, its configuration file content is as follows:

Configuring settings.py Session_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 settingssession_cookie_name ="SessionID"                        #session cookie is stored on the browser when the key, namely: Sessionid= random stringSession_cookie_path ="/"                                #The path of the session cookie saveSession_cookie_domain = None#session of the cookie saved by the domain nameSession_cookie_secure = False#whether HTTPS transmits cookiesSession_cookie_httponly = True#whether the session cookie only supports HTTP transmissionSession_cookie_age = 1209600#Cookie Expiration date for session (2 weeks)Session_expire_at_browser_close = False#whether to close the browser so that the session expiresSession_save_every_request = False#if the session is saved every time the request is modified, it is saved after the default

(3) File session

(4) cache + Database session

(5) Encryption Cookie session

Python Road _day71_django pagination and session Introduction

Related Article

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.