本文介绍了未设置SQLALCHEMY_DATABASE_URI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用FlaskSQLAlchemy进行CURD操作,但是在连接数据库时得到Error.

I tried to work with CURD operation using Flask and SQLAlchemy.But getting Error while connecting to database.

这是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

here is 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

here is 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." 

推荐答案

您可能需要将此行app.config['SQLALCHEMY_DATABASE_URI'] = "mysql..."放在SQLAlchemy(app)实例之前.

You probably need to put this line app.config['SQLALCHEMY_DATABASE_URI'] = "mysql..." before the SQLAlchemy(app) instanciation.

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

Another option is to create SQLAlchemy() without parametters, to configure URI, and finally to tell SQLAlchemy to link with your app via sqldb.init_app(app)

请注意,这是您在create_app函数中所做的事情,但是您从未使用过它吗?

Note that it is what you've done in your create_app function, but you never use it ?

这篇关于未设置SQLALCHEMY_DATABASE_URI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 05:23