Python Day71 Django Pagination and session Introduction

Source: Internet
Author: User

One, Django paging

The following examples are custom paging:

"" "Pagination Component use Example: 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}) "" "Class pagination (        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: Number of data bars per page:p Aram Base_url: URL prefixes displayed in pagination:p Aram Pager_count: Maximum number of page numbers "" "Try:current_page = Int (current_        page) except Exception as E:current_page = 1 if current_page <1:current_page = 1 Self.current_page = Current_page Self.all_count = All_count Self.per_page_num = per_page_num s Elf.base_url = base_url # Total page number All_pager, tmp = Divmod (All_count, Per_page_num)       If Tmp:all_pager + = 1 Self.all_pager = All_pager Self.pager_count = Pager_count SE lf.pager_count_half = Int ((pager_count-1)/2) @property def start (self): return (self.current_page-1) * Self.per_page_num @property def End (self): return self.current_page * self.per_page_num def page_html (self ): # If total page number < 11: if Self.all_pager <= self.pager_count:pager_start = 1 pager_e nd = Self.all_pager + 1 # Total page number > all else: # current page If the <= page shows a maximum of 11/2 pages if Self.curren            T_page <= Self.pager_count_half:pager_start = 1 Pager_end = self.pager_count + 1 # The current page is greater than 5 else: # page number turns to last if (Self.current_page + self.pager_count_half) > S Elf.all_pager:pager_end = Self.all_pager + 1 Pager_start = SELF.ALL_PAGER-SELF.PA           Ger_count + 1     Else:pager_start = Self.current_page-self.pager_count_half Pager_end = self. Current_page + self.pager_count_half + 1 page_html_list = [] first_page = ' <li><a href= '%s?page=%s ' > Home </a></li> '% (self.base_url,1,) page_html_list.append (first_page) if Self.current_page &lt = 1:prev_page = ' <li><a href= ' # ' > prev </a></li> ' else:prev_page = ' & Lt;li><a href= "%s?page=%s" > Previous </a></li> '% (self.base_url,self.current_page-1,) Page_html_li St.append (prev_page) for I in range (Pager_start, pager_end): if i = = Self.current_page:t EMP = ' <li class= ' active ' ><a href= '%s?page=%s ' >%s</a></li> '% (self.base_url,i, I,) Els            E:temp = ' <li><a href= '%s?page=%s ' >%s</a></li> '% (self.base_url,i, I,) Page_html_list.append (tEMP) if self.current_page >= self.all_pager:next_page = ' <li><a href= ' # ' > Next &LT;/A&GT;&L T;/li> ' else:next_page = ' <li><a href= '%s?page=%s ' > Next </a></li> '% (Self.bas E_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 '. J Oin (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 cookie saved on browser key, i.e.: sessionid= random string (default)    Session_cookie_path = "/"                               # SESSION Cookie saved Path (default)    Session_cookie_domain = None                             # SESSION COOKIE saved domain name (default)    session_cookie_secure = False                            # Whether the HTTPS transport cookie (default)    session_cookie_httponly = True                           # If the SESSION's cookie only supports HTTP transport (default)    Session_cookie_ Age = 1209600                             # SESSION 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 each request is saved session, the default is not saved after the change (default)

The session is used as follows:

Set up:

Get:

Delete:

 def index (request): # GET, set, delete data in session request.session[' K1 '] request.session.get (' K1 ', None)         request.session[' k1 ' = 123 request.session.setdefault (' K1 ', 123) # exists then does not set del request.session[' K1 '] # All keys, values, key-value pairs Request.session.keys () request.session.values () Request.session.items () requ        Est.session.iterkeys () request.session.itervalues () Request.session.iteritems () # Random string for user session Request.session.session_key # Delete all data with session expiration date less than current date request.session.clear_expired () # Check Whether the random string of the user session is Request.session.exists ("Session_key") in the database # deletes all session data for the current user request.session.d            Elete ("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 will expire. * 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:

Configure settings.py     session_engine = ' Django.contrib.sessions.backends.cache '  # engine    Session_cache_alias = '                            the cache alias (default memory cache, or memcache) used by the alias, where the aliases depend on the cache settings      session_cookie_name = "SessionID"                        # The session's cookie is stored on the browser when the key, namely: Sessionid= random string    Session_cookie_path = "/"                                # SESSION of the cookie saved path    session_ Cookie_domain = None                              # SESSION cookie saved domain name    session_cookie_secure = False                             # Whether HTTPS transport cookie    Session_cookie_httponly = True                            # Whether the SESSION's COOKIE only supports HTTP transport    session_cookie_age = 1209600                              # Session cookie Expiration Date (2 weeks)    session_expire_at_browser_close = False                   # whether to close the browser so that the session expires    Session_save_ Every_request = False                        # If the session is saved every time the request is changed, it is saved after the default modification

(3) File session

(4) cache + Database session

(5) Encryption Cookie session

Python Day71 Django Pagination and session Introduction

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.