SQLAlchemy错误?我不确定

时间:2011-02-09 16:10:05

标签: python sqlite sqlalchemy

from sqlalchemy import create_engine
from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey
from sqlalchemy.orm import mapper, sessionmaker
from sqlalchemy.ext.declarative import declarative_base

from bottle import route, post, get, request
import os

Base = declarative_base()

class User(Base):
    """Table for login details"""
    __tablename__ = 'login_table'
    id = Column(Integer, primary_key=True)
    username =  Column(String)
    password =  Column(String)
    email = Column(String)

    def __init__(self, username, password, email):
        """Create a object containing info of a user"""
        self.username = username
        self.password = password
        self.email = email

    def __str__(self):
        """Return a string representation"""
        return self.username

    def __repr__(self):
        """Return a object representation"""
        return "<User(%s)>" % self.username

def force_engine():
    engine = create_engine('sqlite:///users.db', echo=True)
    Base.metadata.create_all(engine)
    Session = sessionmaker()
    Session.configure(bind=engine)
    session = Session()
    session.commit()

def spawn_session():
    engine = create_engine('sqlite:///users.db')
    Session = sessionmaker()
    Session.configure(bind=engine)
    return Session()

def create_user(username, password, email):
    session = spawn_session()
    session.add(User(username, password, email))
    session.commit()
    return True

def register_test():
    create_user('dave','test', 'a')
    create_user('cat','123','a')

if not os.path.exists('users.db'):
    force_engine()

@get('/register')
def register_form():
    return '''<form method="POST">
                <p>Welcome new user. Enter a username, password, email.</p></br>
                <p>Username: </p><input name="username" type="text" /></br>
                <p>Password: </p><input name="password" type="password" /></br>
                <p>Email: </p><input name="email" type="text" /></br>
                <input type="submit" value="Submit" />
              </from>'''

@post('/register')
def register_submit():
    name     = request.forms.get('username')
    password = request.forms.get('password')
    email = request.forms.get('email')
    authd = create_user(name, password, email)
    if authd:
        return "<p>User created</p>"
    else:
        return "<p>Failure</p>"

这是我正在使用的代码。不要告诉我有关安全性或其他任何事情的信息。只是帮我找出导致这种追溯的原因

>>> register_test()
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
  File "C:\Users\Public\Documents\webapps\login\register.py", line 54, in register_test
    create_user('dave','test', 'a')
  File "C:\Users\Public\Documents\webapps\login\register.py", line 50, in create_user
    session.commit()
  File "C:\Python26\lib\site-packages\sqlalchemy-0.6.5-py2.6.egg\sqlalchemy\orm\session.py", line 623, in commit
    self.transaction.commit()
  File "C:\Python26\lib\site-packages\sqlalchemy-0.6.5-py2.6.egg\sqlalchemy\orm\session.py", line 385, in commit
    self._prepare_impl()
  File "C:\Python26\lib\site-packages\sqlalchemy-0.6.5-py2.6.egg\sqlalchemy\orm\session.py", line 369, in _prepare_impl
    self.session.flush()
  File "C:\Python26\lib\site-packages\sqlalchemy-0.6.5-py2.6.egg\sqlalchemy\orm\session.py", line 1397, in flush
    self._flush(objects)
  File "C:\Python26\lib\site-packages\sqlalchemy-0.6.5-py2.6.egg\sqlalchemy\orm\session.py", line 1478, in _flush
    flush_context.execute()
  File "C:\Python26\lib\site-packages\sqlalchemy-0.6.5-py2.6.egg\sqlalchemy\orm\unitofwork.py", line 304, in execute
    rec.execute(self)
  File "C:\Python26\lib\site-packages\sqlalchemy-0.6.5-py2.6.egg\sqlalchemy\orm\unitofwork.py", line 448, in execute
    uow
  File "C:\Python26\lib\site-packages\sqlalchemy-0.6.5-py2.6.egg\sqlalchemy\orm\mapper.py", line 1872, in _save_obj
    execute(statement, params)
  File "C:\Python26\lib\site-packages\sqlalchemy-0.6.5-py2.6.egg\sqlalchemy\engine\base.py", line 1191, in execute
    params)
  File "C:\Python26\lib\site-packages\sqlalchemy-0.6.5-py2.6.egg\sqlalchemy\engine\base.py", line 1271, in _execute_clauseelement
    return self.__execute_context(context)
  File "C:\Python26\lib\site-packages\sqlalchemy-0.6.5-py2.6.egg\sqlalchemy\engine\base.py", line 1302, in __execute_context
    context.parameters[0], context=context)
  File "C:\Python26\lib\site-packages\sqlalchemy-0.6.5-py2.6.egg\sqlalchemy\engine\base.py", line 1401, in _cursor_execute
    context)
  File "C:\Python26\lib\site-packages\sqlalchemy-0.6.5-py2.6.egg\sqlalchemy\engine\base.py", line 1394, in _cursor_execute
    context)
  File "C:\Python26\lib\site-packages\sqlalchemy-0.6.5-py2.6.egg\sqlalchemy\engine\default.py", line 299, in do_execute
    cursor.execute(statement, parameters)
OperationalError: (OperationalError) table login_table has no column named email u'INSERT INTO login_table (username, password, email) VALUES (?, ?, ?)' ('dave', 'test', 'a')

即使我完全关闭python,并完全删除数据库,我仍然得到相同的execption

1 个答案:

答案 0 :(得分:3)

在这里写一下关于在tutorial

中使用SQLAlchemy和SQLite非常好

您需要验证自己至少是SQLAlchemy的0.7版本

>>> import sqlalchemy
>>> sqlalchemy.__version__ 
0.7.0

使用echo显示生成的SQL

>>> from sqlalchemy import create_engine
>>> engine = create_engine('sqlite:///users.db', echo=True)

您可能错过了这个非常重要的步骤

>>> from sqlalchemy.ext.declarative import declarative_base
>>> Base = declarative_base()

最后验证您是否正确创建了表

>>> User.__table__ 
Table('users', MetaData(None),
            Column('id', Integer(), table=<users>, primary_key=True, nullable=False),
            Column('name', String(), table=<users>),
            Column('username', String(), table=<users>),
            Column('password', String(), table=<users>), 
            Column('email', String(), table=<users>), schema=None)