【问题标题】:Peewee and Flask : 'Database' object has no attribute 'commit_select'Peewee 和 Flask:“数据库”对象没有属性“提交选择”
【发布时间】:2017-08-20 12:15:52
【问题描述】:

我正在尝试将 Peewee 与 Flask 一起使用,但我不明白为什么我的数据库连接不起作用。

config.py

class Configuration(object):
DATABASE = {
    'name': 'test',
    'engine': 'peewee.MySQLDatabase',
    'user': 'root',
    'passwd': 'root'
}
DEBUG = True
SECRET_KEY = 'shhhh'

app/init.py

from flask import Flask
from flask_peewee.db import Database
app = Flask(__name__)
app.config.from_object('config.Configuration') 
db = Database(app)
import views,models

app/models.py

from peewee import *
from . import db
database = db

class UnknownField(object):
    def __init__(self, *_, **__): pass
class BaseModel(Model):
    class Meta:
        database = database

class Tbcategory(BaseModel):
    insert_dt = DateTimeField()
    name = CharField()

    class Meta:
        db_table = 'tbcategory'

我用 pwiz 生成了 models.py。

如果我尝试在交互式控制台上使用它,我会在标题上看到错误。如果我将 models.py 上的行从 database=db 更改为 pwiz 创建的原始行:

db = MySQLDatabase('test', **{'host': '127.0.0.1', 'password': 'root', 'user': 'root'})

一切正常。我一生都无法在互联网上找到一个例子。配置要么全部在应用程序中,要么在 config.py 文件的外部,但使用 sqlite 或其他稍有不同的用法。 我应该停止使用来自 flask_peewee 的 Database() 并直接使用 MySQLDatabase 吗?如何在配置中使用外部文件? 请注意,我在一种方法上使用 127.0.0.1,而在另一种方法上没有主机规范。我确实是从 peewee-flask 的网站上复制的。

【问题讨论】:

  • 听起来您的配置没有得到正确处理。我想我找到了罪魁祸首-> app.config.from_object('config.Configuration')。我认为您的意思是将该方法传递给配置对象而不是字符串。
  • @WyattIsrael 谢谢,但我确实检查了两次,它是正确的。我必须传递一个字符串。我什至尝试打错字,看看它是否已加载。当我使用字符串时,它确实被加载了。我不确定会发生什么。
  • 错误的@WyattIsrael -- 请参阅我的评论。

标签: python flask peewee


【解决方案1】:

您正在使用Database 包装对象。要获取实际的 Peewee 数据库对象,请使用:

app.config.from_object('config.Configuration') 
db = Database(app)
database = db.database  # database is the actual peewee database obj.

在您的模型代码中:

from peewee import *
from . import database  # Import the actual peewee database

【讨论】:

  • 有效!感谢您的帮助,感谢 peewee。
猜你喜欢
  • 2020-09-18
  • 2013-03-13
  • 2019-09-25
  • 2012-12-07
  • 1970-01-01
  • 2015-04-14
  • 1970-01-01
  • 1970-01-01
  • 2020-04-10
相关资源
最近更新 更多