问题
I'm trying to use Peewee with Flask, but I don't understand why my database connection does not work.
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'
I generated models.py with 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'})
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.
回答1:
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.
In your models code:
from peewee import *
from . import database # Import the actual peewee database
来源:https://stackoverflow.com/questions/45782020/peewee-and-flask-database-object-has-no-attribute-commit-select