python - sqlalchemy app.config使用报错
PHPz
PHPz 2017-04-18 10:28:11
0
2
1429
#!/usr/bin/python
#coding=utf-8

from flask import Flask
from flask_sqlalchemy import SQLAlchemy


app = Flask(__name__)
db = SQLAlchemy(app)


class News(db.Model):
    """ 新闻模型 """
    __tablename__ = 'news'

    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(200), nullable=False)
    content = db.Column(db.String(2000), nullable=False)
    is_valid = db.Column(db.Boolean, default=True)
    created_at = db.Column(db.DateTime)
    updated_at = db.Column(db.DateTime)

    comments = db.relationship('Comments', backref='news',
                                lazy='dynamic')

    def __repr__(self):
        return '<News %r>' % self.title


class Comments(db.Model):
    """ 新闻评论 """

    id = db.Column(db.Integer, primary_key=True)
    content = db.Column(db.String(2000), nullable=False)
    is_valid = db.Column(db.Boolean, default=True)
    created_at = db.Column(db.DateTime)
    updated_at = db.Column(db.DateTime)

    new_id = db.Column(db.Integer, db.ForeignKey('news.id'))

    def __repr__(self):
        return '<News %r>' % self.content


app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:123456@127.0.0.1/flask_test'

if __name__ == '__main__':
    app.run(debug=True)
    

打算学习创建数据库的,但是提示报错,

>>> from test_orm import db
D:\mycodes\virtual\flask-test\lib\site-packages\flask_sqlalchemy\__init__.py:819
: UserWarning: SQLALCHEMY_DATABASE_URI not set. Defaulting to "sqlite:///:memory:".
  'SQLALCHEMY_DATABASE_URI not set. Defaulting to '
>>>

我去看了一下源码

if 'SQLALCHEMY_DATABASE_URI' not in app.config:
    warnings.warn(
        'SQLALCHEMY_DATABASE_URI not set. Defaulting to '
        '"sqlite:///:memory:".'
    )
    

上面说。。。SQLALCHEMY_DATABASE_URI不在app.config里面。。。但是我上面的编码。。确实在这个里面。。我崩溃。。。求助大神们。。。哪出错了。。

PHPz
PHPz

学习是最好的投资!

reply all(2)
大家讲道理

I found the problem, the first
app.config must be before db = SQLAlchemy(app)
The second url used in python3 is
mysql+pymysql://

PHPzhong
db = SQLAlchemy(app)

app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:123456@127.0.0.1/flask_test'

Replace the order of these two sentences, it should be that you need to set the URI before initializing db

Is there any problem with the URI format? Official website documentation

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template