SQLALCHEMY_DATABASE_URI未设置

时间:2017-04-18 08:09:27

标签: python-3.x flask sqlalchemy flask-sqlalchemy

我尝试使用CURDFlask处理SQLAlchemy操作。但在连接数据库时获取Error

这是Error日志。

/usr/local/lib/python3.4/dist-packages/flask_sqlalchemy/__init__.py:819: UserWarning: SQLALCHEMY_DATABASE_URI not set. Defaulting to "sqlite:///:memory:".
  'SQLALCHEMY_DATABASE_URI not set. Defaulting to '
/usr/local/lib/python3.4/dist-packages/flask_sqlalchemy/__init__.py:839: FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future.  Set it to True or False to suppress this warning.
  'SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and '

这是我的代码&设置

# database.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
sqldb = SQLAlchemy(app)
app.config['SQLALCHEMY_DATABASE_URI'] = "mysql+pymysql://root:root@localhost/myDbName"


# create app
def create_app():
    sqlDB = SQLAlchemy(app)
    sqlDB.init_app(app)
    sqlDB.create_all()
    return app

这里是models.py

from ..database import create_app
sqldb = create_app()
#  Users Model
class Users(sqldb.Model):
    __tablename__ = 'users'
    id = sqldb.Column(sqldb.Integer, primary_key = True)
    db = sqldb.Column(sqldb.String(40))
    def __init__(self,email,db):
        self.email = email
        self.db = db
    def __repr__(self,db):
        return '<USER %r>' % self.db

这里是routes.py

# Import __init__ file
from __init__ import app
import sys
# JSON 
from bson import dumps
# login
@app.route('/', methods = ['GET'])
def login():
    try:
        # import users model
        from Model.models import Users,sqldb
        sqldb.init_app(app)
        sqldb.create_all()
        getUser = Users.query.all()
        print(getUser)
        return 'dsf'
    except Exception as e:
        print(e)
        return "error." 

3 个答案:

答案 0 :(得分:13)

您可能需要将此行duration.minutes.past放在app.config['SQLALCHEMY_DATABASE_URI'] = "mysql..."实例之前。

另一种选择是创建不带参数的SQLAlchemy(app),配置URI,最后告诉SQLAlchemy()通过SQLAlchemy

与您的应用建立关联

请注意,这是您在sqldb.init_app(app)函数中所做的,但您从未使用它?

答案 1 :(得分:1)

与上面的答案一样,如果您以这种方式使用它,请更改

sqldb = SQLAlchemy(app)

sqldb = SQLAlchemy()

答案 2 :(得分:0)

我遇到了同样的错误,在设置 FLASK_APP 环境变量后它就消失了:

export FLASK_APP=run.py

启动应用程序:

flask run --host=0.0.0.0 --port=5000