简体   繁体   English

Flask SQLAlchemy db.create_all() 不创建数据库

[英]Flask SQLAlchemy db.create_all() not creating database

I can't seem to figure out why my call to db.create_all() is not working.我似乎无法弄清楚为什么我对 db.create_all() 的调用不起作用。

I have an app package with following init:我有一个带有以下 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

Then I have models.py inside the app package:然后我在应用程序包中有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 contains, among other things, the following: app.config 包含以下内容:

'SQLALCHEMY_DATABASE_URL': 'sqlite:////Users/xxxxx/projects/yyyyy/data-dev.sqlite'

Then if I fire up my interactive shell, you can see objects exist appropriately and call to db.create_all() appears to work, but results in no database creation:然后,如果我启动我的交互式 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()
>>> 

Any thoughts on why the database isn't getting created?关于为什么没有创建数据库的任何想法?

The setting should be SQLALCHEMY_DATABASE_ URI , not URL .设置应该是SQLALCHEMY_DATABASE_ URI ,而不是URL You can see that the db doesn't have the right uri when you ran this line:运行此行时,您可以看到 db 没有正确的 uri:

>>> db
<SQLAlchemy engine='sqlite://'>

It shows that Flask-SQLAlchemy defaulted to an in-memory sqlite database.它表明 Flask-SQLAlchemy 默认使用内存中的 sqlite 数据库。 Change the setting and it will work.更改设置,它将起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM