本篇导航:

一、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)

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)

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>

二、添加后保留原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)

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("") 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)

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)

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)

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

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

    本篇导航: flask实现分页 添加后保留原url搜索条件 单例模式 一.flask实现分页 1.django项目中写过的分页组件 from urllib.parse import urlencode ...

  2. 用flask实现的添加后保留原url搜索条件

    1.具体实现 #!usr/bin/env python # -*- coding:utf-8 -*- from flask import Flask,render_template,request,r ...

  3. 编辑后保留原URl搜索条件

    首先需要知道的一个知识点: 1.request.GET是一个QueryDict类型的,要想取出?后面的结构就用request.GET.urlencode() 2.request.GET默认是不可修改的 ...

  4. 自制Javascript分页插件,支持AJAX加载和URL带参跳转两种初始化方式,可用于同一页面的多个分页和不同页面的调用

    闲话部分 最近闲着实在无聊,就做了点小东西练练手,由于原来一直在用AspNetPager进行分页,而且也进行了深度的定制与原有系统整合的也不错,不过毕竟是用别人的,想着看自己能试着做出来不能,后台的分 ...

  5. spring boot(二)整合mybatis plus+ 分页插件 + 代码生成

    先创建spring boot项目,不知道怎么创建项目的 可以看我上一篇文章 用到的环境 JDK8 .maven.lombok.mysql 5.7 swagger 是为了方便接口测试 一.Spring ...

  6. jqPaginator-master | kkpager-master 这两个分页插件的使用方法

    首先:百度"分页插件" 就会 找到这条链接: url=X8P3UpOM-6ceSfjdngX0oh9cNmVwSDy94CxKqWIazhyZ7If4S8wgpPqyEGUhk2t ...

  7. Flask学习之旅--分页功能:分别使用 flask--pagination 和分页插件 layPage

    一.前言 现在开发一个网站,分页是一个很常见的功能了,尤其是当数据达到一定量的时候,如果都显示在页面上,会造成页面过长而影响用户体验,除此之外,还可能出现加载过慢等问题.因此,分页就很有必要了. 分页 ...

  8. SpringBoot添加对Mybatis分页插件PageHelper的支持

    1.修改maven配置文件pom.xml,添加对pageHelper的支持: <!--pagehelper--> <dependency> <groupId>com ...

  9. MVC如何使用开源分页插件shenniu.pager.js

    最近比较忙,前期忙公司手机端接口项目,各种开发+调试+发布现在几乎上线无问题了:虽然公司项目忙不过在期间抽空做了两件个人觉得有意义的事情,一者使用aspnetcore开发了个人线上项目(要说线上其实只 ...

随机推荐

  1. 通过ping命令查看服务器是linux还是windows系列

    通过ping命令识别服务器类型

  2. python3改版后的特征

    1.原始数据类型和运算符 # 整数 3 # => 3 # 算术没有什么出乎意料的 1 + 1 # => 2 8 - 1 # => 7 10 * 2 # => 20 # 但是除法 ...

  3. java生成二维码以及读取案例

    今天有时间把二维码这块看了一下,方法有几种,我只是简单的看了一下  google  的  zxing! 很简单的一个,比较适合刚刚学习java的小伙伴哦!也比较适合以前没有接触过和感兴趣的的小伙伴,o ...

  4. json 对象和json字符串

    转载至  http://www.cnblogs.com/cstao110/p/3762056.html JSON字符串与JSON对象的区别 Q:什么是"JSON字符串",什么是&q ...

  5. Python编译安装遇到的问题

    1.python在make时候报错 Python build finished, but the necessary bits to build these modules were not foun ...

  6. Shell学习之结合正则表达式与通配符的使用(五)

    Shell学习之结合正则表达式与通配符的使用 目录 通配符 正则表达式与通配符 通配符 通配符的使用 正则表达式 正则表达式 正则表达式的使用 通配符 正则表达式与通配符 正则表达式用来在文件中匹配符 ...

  7. 基于335X的UBOOT网口驱动分析

    基于335X的UBOOT网口驱动分析 一.软硬件平台资料 1.  开发板:创龙AM3359核心板,网口采用RMII形式 2.  UBOOT版本:U-Boot-2016.05,采用FDT和DM. 参考链 ...

  8. python中sqlite问题和坑

    import sqlite3 #导入模块 conn = sqlite3.connect('example.db') C=conn.cursor() #创建表 C.execute('''CREATE T ...

  9. UVA 815 Flooded!

    题意:来自:https://blog.csdn.net/lecholin/article/details/70186673 思路: ①数组存每个网格的高度,然后排序,做题时想象为上面的柱状图. ②注意 ...

  10. Adams/Car与Simulink联合仿真方法

    必须是Assembly装配体才行,并支持仿真设置.这里使用MDI_Demo_Vehicle模型,输出前缀为test1,输出选择files_only.然后OK输出. 生成的文件如下: 在Plant Ex ...