我一直在努力使用sqlalchemy在烧瓶中制作mysql引擎。现在我正在按照教程教学如何制作引擎,导入时出现问题。我已经安装了sqlalchemy和mysql-python,但仍然遇到了这个问题。我在解决方案中搜索了此错误,但找不到它。
这是database.py
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import scoped_session, sessionmaker
engine = create_engine('mysql://root:apmsetup@localhost/ds20161017?charset=utf8', convert_unicode=False)
db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine))
Base = declarative_base()
Base.query = db_session.query_property()
def init_db():
Base.metadata.create_all(engine)
models.py
from sqlalchemy import Column, Integer, String, DateTime
from database import Base
class TbTest(Base):
_tablename_ = 'tbTable'
id = Column(Integer, primary_key=True)
datetime = Column(DateTime)
string = Column(String(250))
def __init__(self, datetime, string):
self.datetime = datetime
self.string = string
def __repr__(self):
return "<TbTest('%d', '%s', '%s'>" %(self.id, str(self.datetime), self.string)
这是views.py,我收到导入错误。 'query','add','commit','db_session'这个词成为未定义的变量。
from database import db_session
from database import init_db
from models import TbTest
def show_tables():
queries = db_session.query(TbTest)
entries = [dict(id=q.id, datetime=q.datetime, string=q.string) for q in queries]
print entries
def add_entry(datetime, string):
t = TbTest(datetime, string)
db_session.add(t)
db_session.commit()
def delete_entry(datetime, string):
db_session.query(TbTest).filter(TbTest.datetime==datetime, TbTest.string==string).delete()
db_session.commit()
def main():
add_entry("2015-02-06 09:00:05", "test1")
delete_entry("2015-02-06 09:00:05","test1")
db_session.close()
if __name__ == "__main__" :
main()
编辑01:添加了文件结构
myflask
├── myflask package
├── templates
| └──index.html
├── __init__.py
├── app.py
├── database.py
├── models.py
└── views.py