flask之分页插件的使用、添加后保留原url搜索条件、单例模式

本篇导航:

 

一、flask实现分页

1、django项目中写过的分页组件

from urllib.parse import urlencode,quote,unquote
class Pagination(object):
    """
    自定义分页
    """
    def __init__(self,current_page,total_count,base_url,params,per_page_count=10,max_pager_count=11):
        try:
            current_page = int(current_page)
        except Exception as e:
            current_page = 1
        if current_page <=0:
            current_page = 1
        self.current_page = current_page
        # 数据总条数
        self.total_count = total_count

        # 每页显示10条数据
        self.per_page_count = per_page_count

        # 页面上应该显示的最大页码
        max_page_num, div = divmod(total_count, per_page_count)
        if div:
            max_page_num += 1
        self.max_page_num = max_page_num

        # 页面上默认显示11个页码(当前页在中间)
        self.max_pager_count = max_pager_count
        self.half_max_pager_count = int((max_pager_count - 1) / 2)

        # URL前缀
        self.base_url = base_url

        # request.GET
        import copy
        params = copy.deepcopy(params)
        # params._mutable = True
        get_dict = params.to_dict()
        # 包含当前列表页面所有的搜/索条件
        # {source:[2,], status:[2], gender:[2],consultant:[1],page:[1]}
        # self.params[page] = 8
        # self.params.urlencode()
        # source=2&status=2&gender=2&consultant=1&page=8
        # href="/hosts/?source=2&status=2&gender=2&consultant=1&page=8"
        # href="%s?%s" %(self.base_url,self.params.urlencode())
        self.params = get_dict

    @property
    def start(self):
        return (self.current_page - 1) * self.per_page_count

    @property
    def end(self):
        return self.current_page * self.per_page_count

    def page_html(self):
        # 如果总页数 <= 11
        if self.max_page_num <= self.max_pager_count:
            pager_start = 1
            pager_end = self.max_page_num
        # 如果总页数 > 11
        else:
            # 如果当前页 <= 5
            if self.current_page <= self.half_max_pager_count:
                pager_start = 1
                pager_end = self.max_pager_count
            else:
                # 当前页 + 5 > 总页码
                if (self.current_page + self.half_max_pager_count) > self.max_page_num:
                    pager_end = self.max_page_num
                    pager_start = self.max_page_num - self.max_pager_count + 1   #倒这数11个
                else:
                    pager_start = self.current_page - self.half_max_pager_count
                    pager_end = self.current_page + self.half_max_pager_count

        page_html_list = []
        # {source:[2,], status:[2], gender:[2],consultant:[1],page:[1]}
        # 首页
        self.params['page'] = 1
        first_page = '<li><a href="%s?%s">首页</a></li>' % (self.base_url,urlencode(self.params),)
        page_html_list.append(first_page)
        # 上一页
        self.params["page"] = self.current_page - 1
        if self.params["page"] < 1:
            pervious_page = '<li class="disabled"><a href="%s?%s" aria-label="Previous">上一页</span></a></li>' % (self.base_url, urlencode(self.params))
        else:
            pervious_page = '<li><a href = "%s?%s" aria-label = "Previous" >上一页</span></a></li>' % ( self.base_url, urlencode(self.params))
        page_html_list.append(pervious_page)
        # 中间页码
        for i in range(pager_start, pager_end + 1):
            self.params['page'] = i
            if i == self.current_page:
                temp = '<li class="active"><a href="%s?%s">%s</a></li>' % (self.base_url,urlencode(self.params), i,)
            else:
                temp = '<li><a href="%s?%s">%s</a></li>' % (self.base_url,urlencode(self.params), i,)
            page_html_list.append(temp)

        # 下一页
        self.params["page"] = self.current_page + 1
        if self.params["page"] > self.max_page_num:
            self.params["page"] = self.current_page
            next_page = '<li class="disabled"><a href = "%s?%s" aria-label = "Next">下一页</span></a></li >' % (self.base_url, urlencode(self.params))
        else:
            next_page = '<li><a href = "%s?%s" aria-label = "Next">下一页</span></a></li>' % (self.base_url, urlencode(self.params))
        page_html_list.append(next_page)

        # 尾页
        self.params['page'] = self.max_page_num
        last_page = '<li><a href="%s?%s">尾页</a></li>' % (self.base_url, urlencode(self.params),)
        page_html_list.append(last_page)

        return ''.join(page_html_list)
View Code

2、组件的使用

from flask import Flask,render_template,request,redirect
from pager import Pagination
from urllib.parse import urlencode
app = Flask(__name__)

=========================django的用法=======================================
# pager_obj = Pagination(request.GET.get('page', 1), len(HOST_LIST), request.path_info, request.GET)
# host_list = HOST_LIST[pager_obj.start:pager_obj.end]
# html = pager_obj.page_html()
# return render(request, 'hosts.html', {'host_list': host_list, "page_html": html})

@app.route('/pager')
def pager():
    li = []
    for i in range(1,100):
        li.append(i)
    # print(li)
  
  ===================================flask的用法===============================
    pager_obj = Pagination(request.args.get("page",1),len(li),request.path,request.args,per_page_count=10)
    # print(request.args)
    index_list = li[pager_obj.start:pager_obj.end]
    html = pager_obj.page_html()
   return render_template("pager.html",index_list=index_list, html = html,condition=path)

if __name__ == '__main__':
    app.run(debug=True)
View Code

3、pager.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width">
    <title>Title</title>
    <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.min.css">
    <style>
        .container{
            margin-top: 20px;
        }
    </style>
</head>
<body>
<div class="container">
    <a href="/add?{{ condition }}"><button class="btn btn-primary">添加</button></a>
    <div class="row " style="margin-top: 10px">
            <ul>
                {% for foo in index_list %}
                    <li>{{ foo }}</li>
                {% endfor %}
            </ul>
            <nav aria-label="Page navigation" class="pull-right">
                <ul class="pagination">
                    {{ html|safe }}
                </ul>
            </nav>
    </div>
</div>
</body>
</html>
View Code

 

二、添加后保留原url搜索条件

1、run.py

#!usr/bin/env python
# -*- coding:utf-8 -*-
from flask import Flask,render_template,request,redirect
from pager import Pagination
from urllib.parse import urlencode
app = Flask(__name__)

@app.route('/pager')
def pager():
    li = []
    for i in range(1,100):
        li.append(i)
    # print(li)
    pager_obj = Pagination(request.args.get("page",1),len(li),request.path,request.args,per_page_count=10)
    # print(request.args)
    index_list = li[pager_obj.start:pager_obj.end]
    html = pager_obj.page_html()

    # ===============保留当前的跳转路径的条件=============
    get_dict = request.args.to_dict()  # {'page': '2', 'name': '9'}
    path = urlencode(get_dict)  # 转化成urlencode格式的
    get_dict["_list_filter"] = path
    path = urlencode(get_dict)  # 转化成urlencode格式的

    print(path)  #    page=5&aaa=1&_list_filter=page%3D5%26aaa%3D1
    print(get_dict)  # {'page': '10', '_list_filter': 'page=10'}
    return render_template("pager.html",index_list=index_list, html = html,condition=path)

@app.route('/add',methods=["GET","POST"])
def add():
    if request.method =="GET":
        return render_template("add.html")
    else:
        url = request.args.get("_list_filter")
        # print(url)
        return redirect("/pager?%s"%url)
if __name__ == '__main__':
    app.run(debug=True)
View Code

2、pager.html

<a href="/add?{{ condition }}"><button class="btn btn-primary">添加</button></a>

3、add.html

<form action="" method="post">
    <input type="text">
    <input type="submit" value="提交">
</form>

 

三、单例模式(四种模式) 

单例模式是设计模式中最简单的形式之一。这一模式的目的是使得类的一个对象成为系统中的唯一实例。要实现这一点,可以从客户端对其进行实例化开始。因此需要用一种只允许生成对象类的唯一实例的机制,下面有四种实现方式

1、文件导入的形式

s1.py

class Foo(object):
    def test(self):
        print("123")

v = Foo()
#v是Foo的实例

s2.py

复制代码
from s1 import v as v1
print(v1,id(v1))  #<s1.Foo object at 0x0000000002221710> 35788560

from s1 import v as v2
print(v1,id(v2))   #<s1.Foo object at 0x0000000002221710> 35788560

# 两个的内存地址是一样的
# 文件加载的时候,第一次导入后,再次导入时不会再重新加载。

2、基于类实现的单例模式

# ======================单例模式:无法支持多线程情况===============

class Singleton(object):

    def __init__(self):
        import time
        time.sleep(1)

    @classmethod
    def instance(cls, *args, **kwargs):
        if not hasattr(Singleton, "_instance"):
            Singleton._instance = Singleton(*args, **kwargs)
        return Singleton._instance

import threading

def task(arg):
    obj = Singleton.instance()
    print(obj)

for i in range(10):
    t = threading.Thread(target=task,args=[i,])
    t.start()


# ====================单例模式:支持多线程情况================、

import time
import threading
class Singleton(object):
    _instance_lock = threading.Lock()

    def __init__(self):
        time.sleep(1)

    @classmethod
    def instance(cls, *args, **kwargs):
        if not hasattr(Singleton, "_instance"):
            with Singleton._instance_lock:   #为了保证线程安全在内部加锁
                if not hasattr(Singleton, "_instance"):
                    Singleton._instance = Singleton(*args, **kwargs)
        return Singleton._instance


def task(arg):
    obj = Singleton.instance()
    print(obj)
for i in range(10):
    t = threading.Thread(target=task,args=[i,])
    t.start()
time.sleep(20)
obj = Singleton.instance()
print(obj)


# 使用先说明,以后用单例模式,obj = Singleton.instance()
# 示例:
# obj1 = Singleton.instance()
# obj2 = Singleton.instance()
# print(obj1,obj2)
# 错误示例
# obj1 = Singleton()
# obj2 = Singleton()
# print(obj1,obj2)
View Code

3、基于__new__实现的单例模式(最常用)

# =============单线程下执行===============
import threading
class Singleton(object):

    _instance_lock = threading.Lock()
    def __init__(self):
        pass

    def __new__(cls, *args, **kwargs):
        if not hasattr(Singleton, "_instance"):
            with Singleton._instance_lock:
                if not hasattr(Singleton, "_instance"):
                    # 类加括号就回去执行__new__方法,__new__方法会创建一个类实例:Singleton()
                    Singleton._instance = object.__new__(cls, *args, **kwargs)  # 继承object类的__new__方法,类去调用方法,说明是函数,要手动传cls
        return Singleton._instance  #obj1
        #类加括号就会先去执行__new__方法,在执行__init__方法
# obj1 = Singleton()
# obj2 = Singleton()
# print(obj1,obj2)

# ===========多线程执行单利============
def task(arg):
    obj = Singleton()
    print(obj)

for i in range(10):
    t = threading.Thread(target=task,args=[i,])
    t.start()


# 使用先说明,以后用单例模式,obj = Singleton()
# 示例
# obj1 = Singleton()
# obj2 = Singleton()
# print(obj1,obj2)
View Code

4、基于mateclass实现的单例模式

"""
1.对象是类创建,创建对象时候类的__init__方法自动执行,对象()执行类的 __call__ 方法
2.类是type创建,创建类时候type的__init__方法自动执行,类() 执行type的 __call__方法(类的__new__方法,类的__init__方法)

# 第0步: 执行type的 __init__ 方法【类是type的对象】
class Foo:
    def __init__(self):
        pass

    def __call__(self, *args, **kwargs):
        pass

# 第1步: 执行type的 __call__ 方法
#        1.1  调用 Foo类(是type的对象)的 __new__方法,用于创建对象。
#        1.2  调用 Foo类(是type的对象)的 __init__方法,用于对对象初始化。
obj = Foo()
# 第2步:执行Foo的 __call__ 方法
obj()
"""

# ===========类的执行流程================
class SingletonType(type):
    def __init__(self,*args,**kwargs):
        print(self)  #会不会打印?  #<class '__main__.Foo'>
        super(SingletonType,self).__init__(*args,**kwargs)

    def __call__(cls, *args, **kwargs):  #cls = Foo
        obj = cls.__new__(cls, *args, **kwargs)
        obj.__init__(*args, **kwargs)
        return obj


class Foo(metaclass=SingletonType):
    def __init__(self,name):
        self.name = name
    def __new__(cls, *args, **kwargs):
        return object.__new__(cls, *args, **kwargs)
'''
    1、对象是类创建的,创建对象时类的__init__方法会自动执行,对象()执行类的__call__方法
    2、类是type创建的,创建类时候type类的__init__方法会自动执行,类()会先执行type的__call__方法(调用类的__new__,__init__方法)
    Foo 这个类是由SingletonType这个类创建的
'''
obj = Foo("hiayan")


# ============第三种方式实现单例模式=================
import threading

class SingletonType(type):
    _instance_lock = threading.Lock()
    def __call__(cls, *args, **kwargs):
        if not hasattr(cls, "_instance"):
            with SingletonType._instance_lock:
                if not hasattr(cls, "_instance"):
                    cls._instance = super(SingletonType,cls).__call__(*args, **kwargs)
        return cls._instance

class Foo(metaclass=SingletonType):
    def __init__(self,name):
        self.name = name


obj1 = Foo('name')
obj2 = Foo('name')
print(obj1,obj2)
View Code

 

posted @ 2018-01-16 15:48  布吉岛丶  阅读(1653)  评论(0编辑  收藏  举报