Peewee 和 Flask:“数据库"对象没有属性“commit_select" [英] Peewee and Flask : 'Database' object has no attribute 'commit_select'

查看:49
本文介绍了Peewee 和 Flask:“数据库"对象没有属性“commit_select"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to use Peewee with Flask, but I don't understand why my database connection does not work.

配置文件

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

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.

I generated models.py with pwiz.

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

If I try to use it on the interactive console I get the error on the title. If I change the line on models.py from database=db to the original one created by 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 的网站上复制的.

everything works fine. I can't find for the life of me an example on internet. Either the configuration is all in the app or it's outside in a config.py file but with sqlite or some orther slightly different usages. Should I stop using Database() from flask_peewee and using the MySQLDatabase directly? How do i use an external file with the configuration? Note that I use 127.0.0.1 on one method, and no host specification on the other. I did copy from peewee-flask's website.

推荐答案

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

You are using the Database wrapper object. To get at the actual Peewee database object, use:

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 和 Flask:“数据库"对象没有属性“commit_select"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆