这篇主要介绍在这次项目中使用的peewee

首先我们要初始化一个数据库连接对象。这里我使用了peewee提供的链接池。当然你也可以直接指定连接例如:

db = SqliteDatabase('base.db')

我这里使用了peewee扩展pool,并初始化db对象参数。

from playhouse importpool

db= pool.PooledMySQLDatabase(host=conf['host'],

port=conf['port'],

user=conf['user'],

passwd=conf['passwd'],

database=conf['database'],

charset=conf['charset'],

stale_timeout=conf['timeout'],

max_connections=conf['max_connections'])

然后建一个peewee的基类

#建议自己的项目使用一个新的基类,Model是peewee的基类

classBaseModel(Model):classMeta:

database=db

@classmethoddef getOne(cls, *query, **kwargs):#为了方便使用,新增此接口,查询不到返回None,而不抛出异常

try:return cls.get(*query,**kwargs)exceptDoesNotExist:return None

然后就可以使用类继承BaseModel建立表了

classXcfRootCategory(BaseModel):classMeta:

db_table= 'xcf_root_category'xcf_category_id= IntegerField() #下厨房十九宫格一级分类ID

name = CharField(null=False)

这里觉得值得一讲的只有特殊的Meta,Peewee文档里面提供了非常多的Meta类型可以使用。这里的意思是指定了db_table是在数据库里名叫xcf_root_category的表然后对应起来,这个类下面的方法,操作的其实就是对应的xcf_root_category这张表的内容。类的实例也就是这张表的实例。

其他参数可以查询文档得到不赘述。

之后我尝试给这张表添加一些方法

@classmethoddefupdate_name(cls, xcf_category_id, name):try:

XcfRootCategory.update(name=name).where(XcfRootCategory.xcf_category_id ==xcf_category_id).execute()returnTrueexcept:return False

这是官方推荐的写法。虽然有点奇怪,但是据说效率不错。

这里的语句更新了一条记录

其他也没有遇到什么坑,唯一可能会比较让人头痛的就是peewee在对mysql进行连接发生著名的ERROR2006的问题,

Error 2006: MySQL server has gone away

这里其实官方介绍了两种方法解决,在2016年1月17号的时候,同样遇到该问题的朋友还向官方发了一个修复的pr现在已经合并,估计下次发版会修复

地址:https://github.com/coleifer/peewee/pull/822

着重讲一下这个pr到底是修复了什么问题呢?

在这个issue被修复之前,如果你使用peewee连接会很容易发现,当你在发起了一次request操作之后,一段时间不操作,正好你的数据库的wait_timeout超时时间又设置得比较短,那么在你下次请求的时候就会出现Error 2006: mysql server has gone away的错误。即使你按照官方文档使用了钩子或者更细粒度的线程管理,也无法阻止这个问题。因为代码本身有个bug,就是无法正确的判断连接是不是已经断掉了。也就是说当mysql到达了超时的时间,但是peewee的连接管理并不知道这个情况,由于peewee在请求第一次之后就是一直维持连接是打开的状态,所以当你试图继续使用这个连接发起sql操作的时候,连接实际上被关闭了,然后就报错了。在现在github上的2.80版本已经修复了该问题,可以正确判断和mysql的连接是否已经断开,所以再结合官方的方法,将不会再出现无法知晓数据库连接是否已经断开的问题。

我这次使用的是结合框架的显示打开关闭连接避免这个问题。

其实官方文档提供了两种方法,一种是基于框架的,使用request hooks解决,基本原理就是在开启一次请求的时候,在开启前用钩子函数手动显示的的打开

数据库连接,然后在结束请求的时候显示指明关闭连接。这样可以避免发生没有正常关闭的情况。

还有一种方法就是管理更加细粒度的线程本地连接。

下面给出贴出文档。

Advanced Connection Management

Managing your database connections is as simple as calling connect() when you need to open a connection, and close() when you are finished. In a web-app, you would typically connect when you receive a request, and close the connection when you return a response. Because connection state is stored in a thread-local, you do not need to worry about juggling connection objects – peewee will handle it for you.

In some situations, however, you may want to manage your connections more explicitly. Since peewee stores the active connection in a threadlocal, this typically would mean that there could only ever be one connection open per thread. For most applications this is desirable, but if you would like to manually manage multiple connections you can create an ExecutionContext.

Execution contexts allow finer-grained control over managing multiple connections to the database. When an execution context is initialized (either as a context manager or as a decorated function), a separate connection will be used for the duration of the wrapped block. You can also choose whether to wrap the block in a transaction.

Execution context examples:

with db.execution_context() as ctx:

# A new connection will be opened or, if using a connection pool,

# pulled from the pool of available connections. Additionally, a

# transaction will be started.

user = User.create(username='charlie')

# When the block ends, the transaction will be committed and the connection

# will be closed (or returned to the pool).

@db.execution_context(with_transaction=False)

def do_something(foo, bar):

# When this function is called, a separate connection is made and will

# be closed when the function returns.

If you are using the peewee connection pool, then the new connections used by the ExecutionContextwill be pulled from the pool of available connections and recycled appropriately.

以上。

peewee mysql自动断开_flask+mako+peewee(下)(解决了Error 2006: MySQL server has gone away)相关推荐

  1. 如何减少mysql的连接时间_mysql连接的空闲时间超过8小时后 MySQL自动断开该连接解决方案...

    mysql连接的空闲时间超过8小时后 MySQL自动断开该连接解决方案 更新时间:2012年11月29日 20:27:52   作者: MySQL 的默认设置下,当一个连接的空闲时间超过8小时后,My ...

  2. mysql连接的空闲时间超过8小时后 MySQL自动断开该连接解决方案

    mysql连接的空闲时间超过8小时后 MySQL自动断开该连接解决方案 参考文章: (1)mysql连接的空闲时间超过8小时后 MySQL自动断开该连接解决方案 (2)https://www.cnbl ...

  3. mysql自动断开该连接解决方案

    mysql自动断开该连接解决方案 参考文章: (1)mysql自动断开该连接解决方案 (2)https://www.cnblogs.com/xxsl/p/7146292.html 备忘一下.

  4. Yii 数据库重连告别General error: 2006 MySQL server has gone away

    General error: 2006 MySQL server has gone away 错误原因 制造错误 解决办法 最新办法 错误原因 Mysql has gone away MySQL 服务 ...

  5. MySQL 5.6 解决InnoDB: Error: Table “mysql“.“innodb_table_stats“ not found.问题

    MySQL 5.6 解决InnoDB: Error: Table "mysql"."innodb_table_stats" not found.问题 参考文章: ...

  6. 解决:SQLSTATE[HY000]: General error: 2006 MySQL server has gone away

    问题一: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away 问题二: SQLSTATE[HY000] [2054] The ...

  7. 客户端连接mysql 自动断开_MySql连接空闲8小时自动断开的原因及连接池配置方法...

    数据库连接超时时间查询 非交互式超时时间,如 JDBC 程序 show global variables like 'wait_timeout'; 交互式超时时间,如数据库工具 show global ...

  8. 【SSH】SSH自动断开连接的原因和解决办法|SSH保持长连接方法

    目录 原因 解决方法 即看即用 方法1:手工修改 方法2:shell命令行修改 详细说明 REMOTE HOST IDENTIFICATION HAS CHANGED问题解决 原因 用putty/Se ...

  9. linux mysql c语言编程,在Linux下通过C语言操作MySQL数据库

    2010年1月27日 晚 22:10 作者:longyun(http://www.linuxdiyf.com/mailto:mtd527@gmail.com) 续:小弟最近想学习数据库,并想开发一个简 ...

最新文章

  1. 近期几个电车调试视频
  2. automation服务器不能创建对象的问题
  3. 如何在mac版本的python里安装pip
  4. c语言for循环 wdtcn,MSP430F149的DS18B20C语言程序
  5. 网络知识:路由器不关闭这个功能,视频越刷越卡!
  6. WebDAV, IIS, 和SharePoint之间的关系
  7. HTML+CSS+JS实现 ❤️Three碎片化图片切换❤️
  8. Ember项目引入js依赖
  9. mtk手机的联机方法
  10. Hadoop——3.x安装部署
  11. drupal与html转换,HTML转Drupal主题的方法
  12. Python实现数字转变为Excel的列
  13. 全球资本市场竞争力指数排名发布,中国跃居第五
  14. 一些 金融知识 小结
  15. python怎么把照片转成卡通_如何把照片变成手绘动漫化?
  16. 字符串转化int类型(整数)
  17. jQuery从入门到进阶视频教程-汤小洋-专题视频课程
  18. 欧标IEC62056 兰吉尔关口电表无线抄表数据采集方案
  19. linux dhcp mac ip绑定,linux – 如何在dhcpd中通过MAC地址分配IP
  20. python四叶玫瑰注意点_四叶玫瑰的建立

热门文章

  1. vue学习笔记-01-前端的发展历史(从后端到前端,再到前后端分离,再到全栈)
  2. QT高级编程之QT基本概览
  3. 7-3 银行排队问题之单队列多窗口服务 (25 分)
  4. xshell 上下左右键乱码和退格键失效
  5. 计算机主机机箱面板辐射,电脑机箱如何防辐射----给大家科普一下
  6. python 连通区域_python skimage 连通性区域检测方法
  7. 手机上python编程工具3和3h有区别吗_Python3.5内置模块之time与datetime模块用法实例分析...
  8. 联通5g接入点设置参数_联通5G 所向无前
  9. JavaSE——Java介绍与环境变量简述
  10. Python中class的简单介绍