flask+mako+peewee(下)(解决了Error 2006: MySQL server has gone away)
这篇主要介绍在这次项目中使用的peewee
文档地址:http://peewee.readthedocs.org/en/latest/index.html
首先我们要初始化一个数据库连接对象。这里我使用了peewee提供的链接池。当然你也可以直接指定连接例如:
db = SqliteDatabase('base.db')
我这里使用了peewee扩展pool,并初始化db对象参数。
from playhouse import pool
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的基类
class BaseModel(Model):
class Meta:
database = db @classmethod
def getOne(cls, *query, **kwargs):
#为了方便使用,新增此接口,查询不到返回None,而不抛出异常
try:
return cls.get(*query,**kwargs)
except DoesNotExist:
return None
然后就可以使用类继承BaseModel建立表了
class XcfRootCategory(BaseModel):
class Meta:
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这张表的内容。类的实例也就是这张表的实例。
其他参数可以查询文档得到不赘述。
之后我尝试给这张表添加一些方法
@classmethod
def update_name(cls, xcf_category_id, name):
try:
XcfRootCategory.update(name=name).where(XcfRootCategory.xcf_category_id == xcf_category_id).execute()
return True
except:
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.
以上。
flask+mako+peewee(下)(解决了Error 2006: MySQL server has gone away)的更多相关文章
- ThinkPHP出现General error: 2006 MySQL server has gone away的解决方法
错误: #13 {main}SQLSTATE[HY000]: General error: 2006 MySQL server has gone awayFILE: \ThinkPHP\Library ...
- Yii 数据库重连告别General error: 2006 MySQL server has gone away
General error: 2006 MySQL server has gone away 错误原因 制造错误 解决办法 最新办法 错误原因 Mysql has gone away MySQL 服务 ...
- mysql error: (2006, 'MySQL server has gone away')
max_allowed_packet=16M wait_timeout= interactive_timeout = vim /etc/my.cnf mysqld 中加入上面的内容.
- General error 2006 MySQL server has gone away
写入配置文件的办法: max_allowed_packet = 16M //但是这种有时候不支持,1024*1024*16这种有的也不支持 max_allowed_packet = 16777216 ...
- 解决Lost connection to MySQL server during query错误方法
昨天使用Navicat for MySQL导入MySQL数据库的时候,出现了一个严重的错误,Lost connection to MySQL server during query,字面意思就是在查询 ...
- 2006 - MySQL server has gone away
mysql出现ERROR : (2006, 'MySQL server has gone away') 的问题意思就是指client和MySQL server之间的链接断开了. 造成这样的原因一般是s ...
- 解决Lost connection to MySQL server during query错误方法/Mysql关闭严格模式
使用Navicat 导入MySQL数据库的时候,出现了一个严重的错误,Lost connection to MySQL server during query,字面意思就是在查询过程中丢失连接到MyS ...
- SQLyog恢复数据库报错解决方法【Error Code: 2006 - MySQL server has gone away】
https://blog.csdn.net/niqinwen/article/details/8693044 导入数据库的时候 SQLyog 报错了 Error Code: 2006 – MySQL ...
- MySQL(Navicat)运行.sql文件时报错:[Err] 2006 - MySQL server has gone away 的解决方法
背景: 今天导入一个数据量很大的.sql文件时,报错: 原因: 可能是sql语句过长,超过mysql通信缓存区最大长度. 解决:1. 编辑 MySQL 安装目录下的 my.ini,在最后添加以下内容: ...
随机推荐
- 贪心之oj.1797
1797:金银岛 查看 提交 统计 提问 总时间限制: 3000ms 内存限制: 65536kB 描述 某天KID利用飞行器飞到了一个金银岛上,上面有许多珍贵的金属,KID虽然更喜欢各种宝石的艺术品, ...
- *** Collection <__NSArrayM: 0x600000647380> was mutated while being enumerated.
*** Collection <__NSArrayM: 0x600000647380> was mutated while being enumerated.
- ubuntu开机自动运行用Qt写的程序
这里介绍一种在ubuntu系统开机自动运行使用Qt编写的程序的方法.首先要注意要自动运行Qt编的程序,不需要先打开Qt,而是直接运行编译好的与工程名同名的可执行文件即可,比如我要运行的工程为QRDec ...
- java中的异常区分
在上图中,粉红色的部分为受检查的异常,其必须被try{}catch语句块所捕获,或者在方法中向外抛出异常 绿色的异常为运行时异常,需要程序员自行分辨是否要解决异常或者抛出异常,例空指针数组下标越界等等 ...
- Swift开发iOS项目实战视频教程(二)---图片与动画
本课主要介绍UIImageview.NSTimer的使用.并介绍了一种动画实现方式. 本教程摒弃枯燥的语法和知识解说.全是有趣有料的项目实战! 视频优酷链接:v.youku.com/v_show/id ...
- C# yield关键词使用
C#有一个关键词yield,简化遍历操作实现的语法糖. 下面Insus.NET使用例子来说明,就拿昨晚的一篇<从字符串数组中把数字的元素找出来> http://www.cnblogs.co ...
- 腾讯云 ubuntu 上tomcat加载项目很慢
问题原因 随机数引起线程阻塞. tomcat不断启动,关闭, 启动关闭.几次后会出现卡死状况.需很久才能加载完成 阿里云同样配置,同样系统,则很难出现卡死状况. 即使出现过几十秒后也会释放出来. 而 ...
- AtCoder ExaWizards 2019 简要题解
AtCoder ExaWizards 2019 简要题解 Tags:题解 link:https://atcoder.jp/contests/exawizards2019 很水的一场ARC啊,随随便便就 ...
- 来不及说什么了,Python 运维开发剁手价仅剩最后 2 天
51reboot 运维开发又双叒叕的搞活动了—— Python 运维开发 18 天训练营课程, 剁手价1299 最后2天 上课方式:网络直播/面授(仅限北京) DAY1 - DAY4 Python3 ...
- Visual Studio2013的安装过程及练习测试
一.安装环境: 支持安装的操作系统版本:Windows XP,Windows7,Windows8,Windows10. CPU大小:Intel(R)Core(TM)i5-4210U CPU @1.7G ...