Home >Backend Development >Python Tutorial >Detailed explanation of Python using flask sqlalchemy to implement paging

Detailed explanation of Python using flask sqlalchemy to implement paging

零下一度
零下一度Original
2017-07-16 11:38:122374browse

When developing the blog system, we have a need to display a list of blog articles that the author has published, or to display a list of articles by the author's followers. Implementing this function is not complicated. You only need to filter out the articles of the specified author in the database where the articles are stored, and then render the HTML for display.
However, this method may be feasible when there are not many articles. When the number of articles increases, it will be impossible to display all the articles on one page. At this time, you need to paging display the article list, and only display the specified number of articles on each page.
How should this function be implemented? An intuitive method we can think of is to group the list of articles filtered from the database and display only one group of articles at a time. Then display the article list of the specified group according to the user's needs.

Flask-sqlalchemy is about flask for database management. In this article we use an example of employee display.

First, we create the SQLALCHEMY object db.

from flask import Flask, render_template,request
from flask_sqlalchemy import SQLAlchemy

app = Flask(name,static_url_path='')
app.debug = True
app.secret_key = "faefasdfaf"
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///./db/personal.db' # app的配置,指定数据库路径
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
app.config['SQLALCHEMY_ECHO'] = True 

db = SQLAlchemy(app)


Then we use db to create the employee table:


from datetime import datetime

class Employee(db.Model):
  '''员工'''
  tablename = 'employee'

  id = db.Column(db.Integer, primary_key=True)
  name = db.Column(db.String(50))
  gender = db.Column(db.String)
  job = db.Column(db.String)
  birthday = db.Column(db.DateTime)
  idcard = db.Column(db.String)
  address = db.Column(db.String)
  salary = db.Column(db.String)
  release_time = db.Column(db.DateTime)

  def init(self, name, gender, job, birthday, idcard, address, salary, release_time=None):
    self.name = name
    self.gender = gender
    self.job = job
    self.birthday = birthday
    self.idcard = idcard
    self.address = address
    self.salary = salary
    self.release_time = release_time if release_time else datetime.now()

  def repr(self):
    return &#39;<员工{},{},{},{}>&#39;.format(self.id, self.name, self.salary, self.address)


table After creating it, we can querydata from the table.


from flask import render_template
from flask.views import MethodView
class EmployeeListView(MethodView): # 获取员工信息
  def get(self,page=1):
    employees = Employee.query.paginate(page,per_page=10)
    return render_template(&#39;employeelist.html&#39;, employees=employees)


Above we query the employee information and then pass it to the front desk as a template. (We used the flask blueprint to divide the module into modules. Suppose we define the above as view function is: employee.list)

Note: paginate is In the paging method, the first parameter is the page number, and the second parameter is how many items are displayed on each page. However, the result obtained in this way is not a list. You need to add an .items to the value passed to the front desk. Here is an example. (Using jinja2 template)

{% for item in employees.items %}

As shown above, when using Jinja2 to get the value, you need to After the value passed from the background, add .items.

Continuing with the paging above, here we need to use the jinja2 template again to define a method to implement the paging function. The name of this page is: helper.html.


{% macro render_page_data(page_data,page_function) %}
  <p class="text-center">
    <ul class="page_data">
      <li><a href="{{ url_for(page_function,page = 1) }}">首页</a></li>
      {% if page_data.has_prev %}
        <li><a href="{{ url_for(page_function,page = page_data.prev_num) }}">«</a></li>
      {% endif %}
      {% for page in page_data.iter_pages() %}
        {% if page %}
          {% if page !=page_data.page %}
            <li><a href="{{ url_for(page_function,page = page) }}">{{ page }}</a></li>
          {% else %}
            <li class="active"><a href="#">{{ page }}</a></li>
          {% endif %}
        {% endif %}
      {% endfor %}
      {% if page_data.has_next %}
        <li><a href="{{ url_for(page_function,page = page_data.next_num) }}">»</a></li>
      {% endif %}
      <li><a href="{{ url_for(page_function,page = page_data.pages) }}">末页</a></li>
    </ul>
  </p>
{% endmacro %}


The above is how we define a distribution method using jinja2 syntax. In this method, we pass two parameters, the first One is the data passed from the background and queried through db paging. The second is the method of the data we query.

It needs special explanation here. There are several important methods for paging data:

  • has_next: If there is at least one page after the current page page, returns True

  • has_prev: If there is at least one page before the current page, returns True

  • next_num: next page Number of pages

  • prev_num: The number of pages on the previous page

After going through the above work, there is only one step left. We need to import the method we just defined through Jinja2 on our template page, that is, import it in our employeelist.html above.

{% import 'helper.html' as helper %}

After importing, we can just call it where we need it.

{{ helper.render_pagination(employees,'employee.list') }}

The above is where we call the method we defined before. The first parameter is the value we passed from the background, and the second is the view function in the background.

After performing the above operations, we are done. Let’s take a look at the renderings we achieved.

#The above is the entire content of this article. I hope it will be helpful to everyone’s study. I also hope that everyone will support Script House.

The above is the detailed content of Detailed explanation of Python using flask sqlalchemy to implement paging. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Summary of Python basicsNext article:Summary of Python basics