SQLAlchemy创建表时没有这样的表错误

时间:2015-04-14 15:28:38

标签: python database flask sqlalchemy

我会尝试解释我的问题,希望有人可以指出我的错误。我正在尝试使用下面的models.py代码在SQLAlchemy中创建一个数据库。我有从前创建的这个数据库,并且在我尝试散列密码字段之前使用它并取得了一些成功。当我这样做时,密码字段消失,没有查询将工作,因为它返回user.password列不存在。所以我删除了数据库以及何时从头开始再次创建它。但是当我再次尝试创建它时,我得到一个表不存在错误。我认为这两个错误可能是相关的,希望治愈一个会治愈两者。我用来创建数据库的代码如下,请帮我找出导致问题的原因。谢谢

models.py

from hashlib import md5
import sys
from werkzeug.security import generate_password_hash, check_password_hash
from app import db
from app import app


if sys.version_info >= (3, 0):
    enable_search = False
else:
    enable_search = True
    import flask.ext.whooshalchemy as whooshalchemy


followers = db.Table(
    'followers',
    db.Column('follower_id', db.Integer, db.ForeignKey('user.id')),
    db.Column('followed_id', db.Integer, db.ForeignKey('user.id'))
)


class User(db.Model):
    __tablename__="user"

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(60))
    nickname = db.Column(db.String(64), index=True, unique=True)
    email = db.Column(db.String(120), index=True, unique=True)
    password = db.Column(db.String(100))
    pw_hash = db.Column(db.String(100))
    role = db.Column(db.String(25))
    posts = db.relationship('Post', backref='author', lazy='dynamic')
    about_me = db.Column(db.String(140))
    last_seen = db.Column(db.DateTime)
    followed = db.relationship('User',
                               secondary=followers,
                               primaryjoin=(followers.c.follower_id == id),
                               secondaryjoin=(followers.c.followed_id == id),
                               backref=db.backref('followers', lazy='dynamic'),
                               lazy='dynamic')
    action = db.relationship('ActionRequest', backref='author', lazy='dynamic')
    capas = db.relationship('Capas', backref='creator', foreign_keys='Capas.user_id')


    @staticmethod
    def make_unique_nickname(nickname):
        if User.query.filter_by(nickname=nickname).first() is None:
            return nickname
        version = 2
        while True:
            new_nickname = nickname + str(version)
            if User.query.filter_by(nickname=new_nickname).first() is None:
                break
            version += 1
        return new_nickname

    def is_authenticated(self):
        return True

    def is_active(self):
        return True

    def is_anonymous(self):
        return False

    def get_id(self):
        return str(self.id)  # python 3

    def avatar(self, size):
        return 'http://www.gravatar.com/avatar/%s?d=mm&s=%d' % \
            (md5(self.email.encode('utf-8')).hexdigest(), size)

    def follow(self, user):
        if not self.is_following(user):
            self.followed.append(user)
            return self

    def unfollow(self, user):
        if self.is_following(user):
            self.followed.remove(user)
            return self

    def is_admin(self):
        u = User.query.get(self.id)
        if u.role == 'admin':
            return True
        else:
            return False

    def is_following(self, user):
        return self.followed.filter(
            followers.c.followed_id == user.id).count() > 0

    def followed_posts(self):
        return Post.query.join(
            followers, (followers.c.followed_id == Post.user_id)).filter(
                followers.c.follower_id == self.id).order_by(
                    Post.timestamp.desc())

    def actionreqs(self):
        return ActionRequest.query.filter(
            ActionRequest.user_id == self.id).order_by(ActionRequest.date_raised.desc())

    def editaction(self):
        return ActionRequest.query.filter()

    def user_list(self):
        return User.query.all()

    def __repr__(self):
        return '<User %r>' % (self.nickname)


class Post(db.Model):
    __tablename__="post"
    __searchable__ = ['body']

    id = db.Column(db.Integer, primary_key=True)
    body = db.Column(db.String(140))
    timestamp = db.Column(db.DateTime)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))

    def __repr__(self):
        return '<Post %r>' % (self.body)


class ActionRequest(db.Model):
    __tablename__="actionrequest"
    __searchable__ = ['issue']

    id = db.Column(db.Integer, primary_key=True, unique=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    raised_by = db.Column(db.String(40))
    date_raised = db.Column(db.DateTime)
    source = db.Column(db.String(50))
    category = db.Column(db.String(25))
    sub_category = db.Column(db.String(25))
    issue = db.Column(db.String(1000))
    immediate_action = db.Column(db.String(1000))
    date_reported = db.Column(db.String(30))
    raise_to_capa = db.Column(db.Integer)

    def __repr__(self):
        return"<ActionRequest(id='%d')>" % (self.id)

if enable_search:
    whooshalchemy.whoosh_index(app, Post)


class SubCategories(db.Model):
    __tablename__="sub_categories"
    id = db.Column(db.String(5), primary_key=True, unique=True)
    category_id = db.Column(db.Integer)
    sub_category = db.Column(db.String(100))
    category_value = db.Column(db.String(3))

    def sub_cat_list(self):
        return SubCategories.query.all()

    def __repr__(self):
        return"<Sub_cat: '%d %s')>" % (self.category_id, self.sub_category)


class Categories(db.Model):
    __tablename__="categories"
    id = db.Column(db.Integer, primary_key=True, unique=True)
    category_name = db.Column(db.String(40))

    def cat_list(self):
        return Categories.query.all()

    def __repr__(self):
        return"<Cat: '%s')>" % (self.category_name)

class Capas(db.Model):
    __tablename__='capas'

    id = db.Column(db.Integer, db.ForeignKey('comments.capa_id'), primary_key=True, unique=True)
    ar_id = db.Column(db.Integer)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    issue = db.Column(db.String(1000))
    date_raised = db.Column(db.DateTime)
    category = db.Column(db.String(25))
    immediate_action = db.Column(db.String(1000))
    source = db.Column(db.String(50))
    sub_category = db.Column(db.String(25))
    raised_by = db.Column(db.String(40))
    responsibility = db.Column(db.String(50))
    date_assigned = db.Column(db.DateTime)
    root_cause = db.Column(db.String(1000))
    root_completed_by = db.Column(db.Integer)
    root_completed_date = db.Column(db.DateTime)
    long_term_solution = db.Column(db.String(1000))
    long_term_solution_completed_by = db.Column(db.Integer)
    long_term_solution_date = db.Column(db.DateTime)
    effectiveness_of_solution = db.Column(db.String(1000))
    closed_by = db.Column(db.Integer, db.ForeignKey('user.id'))
    date_closed = db.Column(db.DateTime)

    def __repr__(self):
        return"<Capa: '%s')>" % (self.category)

class Comments(db.Model):
    __searchable__ = ['body']
    __tablename__='comments'

    id = db.Column(db.Integer, primary_key=True)
    body = db.Column(db.String(200))
    timestamp = db.Column(db.DateTime)
    capa_id = db.Column(db.Integer)

    def __repr__(self):
        return '<Comment %r>' % (self.body)

创建数据库时出错

Traceback (most recent call last):
  File "C:\Users\rmckinney\microblog\flask\lib\site-packages\sqlalchemy\engine\base.py", line 1063, in _execute_context
    context)
  File "C:\Users\rmckinney\microblog\flask\lib\site-packages\sqlalchemy\engine\default.py", line 442, in do_execute
    cursor.execute(statement, parameters)
sqlite3.OperationalError: no such table: sub_categories

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "db_create.py", line 5, in <module>
    from app import db
  File "C:\Users\rmckinney\PycharmProjects\CAPA\app\__init__.py", line 49, in <module>
    from app import views, models
  File "C:\Users\rmckinney\PycharmProjects\CAPA\app\views.py", line 7, in <module>
    from .forms import LoginForm, EditForm, PostForm, SearchForm, ActionRequestForm, EditReqForm, CapaCreateForm, \
  File "C:\Users\rmckinney\PycharmProjects\CAPA\app\forms.py", line 10, in <module>
    subcat = SubCategories().sub_cat_list()
  File "C:\Users\rmckinney\PycharmProjects\CAPA\app\models.py", line 157, in sub_cat_list
    return SubCategories.query.all()
  File "C:\Users\rmckinney\microblog\flask\lib\site-packages\sqlalchemy\orm\query.py", line 2323, in all
    return list(self)
  File "C:\Users\rmckinney\microblog\flask\lib\site-packages\sqlalchemy\orm\query.py", line 2441, in __iter__
    return self._execute_and_instances(context)
  File "C:\Users\rmckinney\microblog\flask\lib\site-packages\sqlalchemy\orm\query.py", line 2456, in _execute_and_instances
    result = conn.execute(querycontext.statement, self._params)
  File "C:\Users\rmckinney\microblog\flask\lib\site-packages\sqlalchemy\engine\base.py", line 841, in execute
    return meth(self, multiparams, params)
  File "C:\Users\rmckinney\microblog\flask\lib\site-packages\sqlalchemy\sql\elements.py", line 322, in _execute_on_connection
    return connection._execute_clauseelement(self, multiparams, params)
  File "C:\Users\rmckinney\microblog\flask\lib\site-packages\sqlalchemy\engine\base.py", line 938, in _execute_clauseelement
    compiled_sql, distilled_params
  File "C:\Users\rmckinney\microblog\flask\lib\site-packages\sqlalchemy\engine\base.py", line 1070, in _execute_context
    context)
  File "C:\Users\rmckinney\microblog\flask\lib\site-packages\sqlalchemy\engine\base.py", line 1271, in _handle_dbapi_exception
    exc_info
  File "C:\Users\rmckinney\microblog\flask\lib\site-packages\sqlalchemy\util\compat.py", line 188, in raise_from_cause
    reraise(type(exception), exception, tb=exc_tb, cause=exc_value)
  File "C:\Users\rmckinney\microblog\flask\lib\site-packages\sqlalchemy\util\compat.py", line 181, in reraise
    raise value.with_traceback(tb)
  File "C:\Users\rmckinney\microblog\flask\lib\site-packages\sqlalchemy\engine\base.py", line 1063, in _execute_context
    context)
  File "C:\Users\rmckinney\microblog\flask\lib\site-packages\sqlalchemy\engine\default.py", line 442, in do_execute
    cursor.execute(statement, parameters)
sqlalchemy.exc.OperationalError: (OperationalError) no such table: sub_categories 'SELECT sub_categories.id AS sub_categories_id, sub_categories.category_id AS sub_categories_category_id, sub_categories.sub_category AS sub_categories_sub_category, sub_categories.category_value AS sub_categories_category_value \nFROM sub_categories' ()

db_create.py

from migrate.versioning import api
from config import SQLALCHEMY_DATABASE_URI
from config import SQLALCHEMY_MIGRATE_REPO
from app import db
import os.path
db.create_all()
if not os.path.exists(SQLALCHEMY_MIGRATE_REPO):
    api.create(SQLALCHEMY_MIGRATE_REPO, 'database repository')
    api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
else:
    api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO,
                        api.version(SQLALCHEMY_MIGRATE_REPO))

0 个答案:

没有答案