Flask Add page Flip function (not sqlalchemy)

Source: Internet
Author: User

Recently do flask project, need to increase the function of paging, online search for the tutorial are combined with SQLAlchemy, but I use is not sqlalchemy, swollen wood do it?

Here's what I'm doing.

First, the front-end

1. Pass the page number

Front-end I use Ajax to submit forms, so in the front-end form to add page this item (hidden), and then edit the value of this item in AJAX and submit to the backend, the page number is so passed to the backend

Code for the form

<formID= "Submit_form">{{Form.hidden_tag ()}}<DivID= "Input-top">        <Divclass= "Form-group">            <label>{{Form.account_id.label}}</label>{{form.account_id}}<label>{{Form.user_id.label}}</label>{{form.user_id}}<BR/>            <label>{{Form.character_name.label}}</label>{{Form.character_name}}<inputID= "page"name= "page"type= "hidden"value= "1"/>        </Div>    </Div>    <Buttontype= "button"class= "Querybtn"onclick= "Ajaxform ()">Inquire</Button></form>

Code for AJAX

    //Ajax Submission Form    functionAjaxform (page_id) {//varifyinput ();document.getElementById ("page"). Value = page_id;//In this edit page in the form, commit to the backend, note to edit before getting the form, otherwise the value of the last page turn is submitted        varform=NewFormData (document.getElementById ("Submit_form")); $.ajax ({URL:"{{url_for (' Main.query_character_list ')}}", type:"POST", Data:form, DataType:' JSON ', ProcessData:false, ContentType:false, Beforesend:function(){                    $("#dialog_message"). Show ();            Del_table (); }, Success:function(data) {$ ("#dialog_message"). Hide ();                    Create_table (data.result_table); if(Number (data.length) >0) {Table_length= Number (Data.length)//If this is the first query, update the total number of pages                    }                    if(page_id = = 1) {Cur_page= 1;//assign a value to the page number of the current sheetdocument.getElementById ("Page_display"). Innerhtml= "Current Page" +cur_page+ "/" +table_length//edit Page Display page number}}, Error:function(e) {$ ("#dialog_message"). Hide ();                    Del_table (); Alert ("No data obtained"); }        })    }

2. Page Turn function

Page pages using buttons to page, button press the direct execution of JS paging function, the function of the page after the addition and subtraction of the Ajax submission form, and update the page number displayed on the value

HTML code

        <Buttontype= "button"class= "Pagebtn"onclick= "Prev_page ()">Previous page</Button>        <spanID= "Page_display"style= "Display:inline">Current Page 0/0</span>        <Buttontype= "button"class= "Pagebtn"onclick= "Next_page ()">Next page</Button>

JS Code

    //page Turn function    functionNext_page () {cur_page= Cur_page + 1; if(Cur_page <table_length)            {Ajaxform (cur_page); document.getElementById ("Page_display"). Innerhtml= "Current Page" +cur_page+ "/" +Table_length}Else if(Cur_page = = =table_length)            {Ajaxform (cur_page); document.getElementById ("Page_display"). Innerhtml= "Current Page" +cur_page+ "/" +Table_length}Else{cur_page=table_length; document.getElementById ("Page_display"). Innerhtml= "Current Page" +cur_page+ "/" +Table_length}} functionPrev_page () {cur_page= Cur_page-1; if(Cur_page > 1) {ajaxform (cur_page); document.getElementById ("Page_display"). Innerhtml= "Current Page" +cur_page+ "/" +Table_length}Else if(Cur_page = = 1) {ajaxform (cur_page); document.getElementById ("Page_display"). Innerhtml= "Current Page" +cur_page+ "/" +Table_length}Else{cur_page= 1; document.getElementById ("Page_display"). Innerhtml= "Current Page" +cur_page+ "/" +table_length; }    }

3. Total Pages

Total pages This is the back end of the first query data when the full amount of query data, and then calculated, so that each page behind the query as long as the data within the page, without obtaining, in front of the Ajax in the first query will update the total length of the value, the first in the JS to declare variables, Or it will go wrong.

In my code, because some things do not need to click the query will automatically display all the data, so when the length variable is initialized directly using the JINJA2 {{}} from the backend to get

JS Code

    var table_length = "{{length}}"; // Total page length, note that the variables referencing jinja2 in JS are enclosed    in double quotation marks. var cur_page = 1;

Second, back end

The backend is a matter of opinion, my program is the view function to the corresponding data processing object to the appropriate format, and then call other objects from the database query, so that in the view, processing objects, call class three aspects to deal with

1. View

Paging length is placed in session at login, session[' Page_interval '

The view function obtains the page number through the form, passes to the back end, here also must divide the first query and the subsequent query

    ifform.validate_on_submit (): Page= request.form['page'] Accountlist_obj= Accountlist (form, db_obj, page)#Personal code habits, the first instantiation of the method of re-invocation(result, length) =accountlist_obj.process ()ifpage = ='1':#The first query when the page number is returned is the first page, this time to do a full query, but only a portion of the data and all the page number, then each query is only part of the query, but if you turn back to the first page can only 陪绑            returnJsonify ({"result_table": result,'length': length})#The length variable of JS is updated on the first page, otherwise it is not updated        Else:            returnJsonify ({"result_table": result,'length': 0})#This length is agreed to 0, if it is 0 front-end JS will not update length

2. Handling objects

Pass the page number to the calling object, and if the first page has some special processing, get the pages and output the first page only

    defprocess (self):#Other processing StatementsPage_interval = session['Page_interval']#get per page interval        #Pagination Returns results        ifSelf.page = = 1:#first query, return full amountAccountlistprocess_obj = accountlistprocess (account_id = account_id, Fb_account =Fb_account, Db_conn=db_conn) Result=accountlistprocess_obj.process ()#Calculate Total Pages            ifLen (result)% Page_interval = = 0:#If it happens to be an integer multiple of the interval dataPage_length = Len (Result)/Page_intervalElse: Page_length= Len (Result)/Page_interval + 1ifPage_length = = 0:#if less than one page is a page at leastPage_length = 1return(Result[0:page_interval], page_length)Else: Accountlistprocess_obj= Accountlistprocess (account_id=account_id, fb_account=Fb_account, Db_conn=db_conn, page=self.page) Result=accountlistprocess_obj.process ()return(result, 0)#the second one, whatever.

3. Called Object

Join the Limit statement of the query in the database, and then when stitching the SQL statement, this statement is put to the last

    defprocess (self):#blah blah blahPage_interval = session['Page_interval'] Page_start= Self.page *Page_intervalifSelf.page = =0:page_str=""        Else: Page_str="limit {Page_start},{page_interval}". Format (page_start=page_start,page_interval=page_interval)#blah blah blahsql =" "blah blah blah {PAGE_STR}; " ". Format (page_str=page_str)#Execute SQL and blah blah blah

Third, the final result

  

  

If there's something wrong with me, please point it out, I'm not going to change it anyway.

Flask Add page Flip function (not sqlalchemy)

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.