创建flask-sqlalchemy数据库失败

时间:2017-01-03 15:23:03

标签: python sqlalchemy flask-sqlalchemy

我尝试通过以下方式导入我的应用配置(db_config.py

>>> from app.db_config import db_session

收到错误 'ImportError: No module named 'app.db_config'; 'app' is not a package

app.py看起来像:

import pymysql.cursors
from flask import Flask, render_template, request
from flask_migrate import Migrate
from app.db_config import db_session

#app setup
app = Flask(__name__)
app.config['DEBUG'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:mypass@localhost/mydb'
db = SQLAlchemy(app)
migrate = Migrate(app, db)
@app.teardown_appcontext
def shutdown_session(exception=None):
    db_session.remove()

@app.route('/', methods=('GET', 'POST'))
def index():
    return 'meow'
if __name__ == '__main__':
    app.run()

db_config.py

from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base

engine = create_engine('mysql+pymysql://root:mypass@localhost/mydb',
                                         convert_unicode=True)
db_session = scoped_session(sessionmaker(autocommit=False,
                                         autoflush=False,
                                         bind=engine))
Base = declarative_base()
Base.query = db_session.query_property()

def init_db():
    import app.db_table
    Base.metadata.create_all(bind=engine)

db_table.py

from sqlalchemy import Column, Integer, String, DateTime, Boolean
from sqlalchemy.ext.declarative import declarative_base
from app.db_config import Base

Base = declarative_base()

class Tld(Base):
    __tablename__ = 'Tld'
    id = Column(Integer, primary_key=True)
    uri =  Column(String(80), unique=True)
    tmstmp = Column(DateTime())
    auth = Column(Boolean())

    def __init__(self, uri=None):
        self.uri = uri
        self.tmstmp = tmstmp
        self.auth = auth

我在这里做错了什么?我跟随this tutorial,但我没有收到我预期的输出。

我的app.py出了什么问题,导致它无法像这样调用?或其他什么问题?

第一次alchemy用户

非常感谢

1 个答案:

答案 0 :(得分:1)

我自己解决了这个问题。我需要from db_config import db_session,而不是from app.db_config import db_session