我正在使用peewee
访问远程 MySql 数据库以检索需要在 Django 应用程序中显示的数据。这意味着peewee
并不是真正用于访问主数据库,而只是喜欢定义自定义模型:
databases.py
中的示例:
from django.conf import settings
from playhouse.pool import PooledMySQLDatabase
database = PooledMySQLDatabase(
settings.DB_PEEWEE,
**{
"use_unicode": True,
"charset": "utf8",
"max_connections": 32,
"stale_timeout": 300, # 5 minutes.
"password": settings.DB_PEEWEE_PSWRD,
"user": settings.DB_PEEWEE_USER,
"host": settings.DB_PEEWEE_HOST,
"port": settings.DB_PEEWEE_PORT,
}
)
在models.py
中:
from .databases import database
class BaseModel(peewee.Model):
class Meta:
database = database
class CountryGroups(BaseModel):
africa = peewee.CharField(null=True)
group_code = peewee.AutoField()
group_name = peewee.CharField()
latin_eur = peewee.CharField(null=True)
type = peewee.CharField()
class Meta:
table_name = "country_groups"
...
# other main django models
因此可以轻松地从views.py
文件中以如下方式调用模型:
CountryGroups_list = (
CountryGroups.select()
.where(CountryGroups.group_name << ["ERROR", "INFO"])
.order_by(CountryGroups.group_name.desc())
.limit(1000)
)
我可以很好地运行查询。但是在连接断开的24小时后,我得到一个错误:
(2006, "MySQL server has gone away (error(32, 'Broken pipe'))")
在Django
中解决此问题的建议方法是使用middleware,但这是假设在这种情况下,与peewee
相关的数据库是主要数据库,并导致了错误像这样一个:
File "/home/user/Dev/project/project/wsgi.py", line 14, in <module>
from configurations.wsgi import get_wsgi_application
File "/home/user/.virtualenvs/project/lib/python3.5/site-packages/configurations/wsgi.py", line 14, in <module>
application = get_wsgi_application()
File "/home/user/.virtualenvs/project/lib/python3.5/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application
return WSGIHandler()
File "/home/user/.virtualenvs/project/lib/python3.5/site-packages/django/core/handlers/wsgi.py", line 135, in __init__
self.load_middleware()
File "/home/user/.virtualenvs/project/lib/python3.5/site-packages/django/core/handlers/base.py", line 37, in load_middleware
mw_instance = middleware(handler)
TypeError: object() takes no parameters
所以我的问题是,如何对通用的数据库模型实现自动的 connect()和 close()没有得到错误?
答案 0 :(得分:1)
您需要编写一个新的Django风格的中间件。我已经相应地更新了文档:
http://docs.peewee-orm.com/en/latest/peewee/database.html#django
def PeeweeConnectionMiddleware(get_response):
def middleware(request):
database.connect()
try:
response = get_response(request)
finally:
if not database.is_closed():
database.close()
return response
return middleware