我似乎无法弄清楚为什么我对db.create_all()的调用不起作用。
我有一个包含以下init的应用包:
from flask import Flask
from config import config
from flask.ext.sqlalchemy import SQLAlchemy
# create the database object
db = SQLAlchemy()
# this function is the application factory
def create_app(environment):
app = Flask(__name__)
app.config.from_object(config[environment])
db.init_app(app)
from bp_root import bp_root
from bp_aws import bp_aws
app.register_blueprint(bp_root, url_prefix='/')
app.register_blueprint(bp_aws, url_prefix='/aws')
return app
然后我在app包中有models.py:
from datetime import datetime
from . import db
class MyTestClass(db.Model):
__tablename__ = 'mytesttable'
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(64), nullable=False, unique=True, index=True)
username = db.Column(db.String(64), nullable=False, unique=True, index=True)
is_admin = db.Column(db.Boolean)
password_hash = db.Column(db.String(128))
location = db.Column(db.String(64))
member_since = db.Column(db.DateTime, default=datetime.utcnow)
bio = db.Column(db.Text())
def __init__(self, email, username):
self.email = email
self.username = username
def __repr__(self):
return '<User %r>' % self.username
app.config包含以下内容:
'SQLALCHEMY_DATABASE_URL': 'sqlite:////Users/xxxxx/projects/yyyyy/data-dev.sqlite'
然后,如果我启动交互式shell,您可以看到对象存在,并且调用db.create_all()似乎可以工作,但不会导致数据库创建:
$ ./manage.py shell
>>> from app import db
>>> from app import models
>>> app
<Flask 'app'>
>>> db
<SQLAlchemy engine='sqlite://'>
>>> models
<module 'app.models' from '/Users/xxxxx/projects/yyyyy/app/models.py'>
>>> dir(models)
['MyTestClass', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'datetime', 'db']
>>> db.create_all()
>>>
有关为何未创建数据库的任何想法?
答案 0 :(得分:7)
设置应为SQLALCHEMY_DATABASE_URI
,而不是URL
。运行此行时,您可以看到db没有正确的uri:
>>> db
<SQLAlchemy engine='sqlite://'>
它显示Flask-SQLAlchemy默认为内存中的sqlite数据库。更改设置,它将起作用。