最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

[已解决]SQLAlchemy中添加枚举类型字段

SQLAlchemy crifan 6527浏览 0评论

SQLAlchemy中对于已有的表,去添加枚举类型字段

class Event(db.Model):
    __tablename__ = "events"
    # Columns
    id = db.Column(db.Integer, primary_key = True, autoincrement = True, nullable=False)
    #user_openid = db.Column(db.String(64))
    #user_openid = db.Column(db.String(64), db.ForeignKey(‘user.openid’))
    user_openid = db.Column(db.String(64), db.ForeignKey(‘wechat_users.openid’))
    title = db.Column(db.String(128))
    start_date = db.Column(db.DateTime)
    end_date = db.Column(db.DateTime)
    location = db.Column(db.String(256))
    cur_user_num = db.Column(db.Integer)
    max_user_num = db.Column(db.Integer)
    is_public = db.Column(db.Boolean)
    description = db.Column(db.Text)
    # joiners = db.relationship(‘EventJoiner’, backref=’user’, lazy=’dynamic’)
    #joiners = db.relationship(‘User’, secondary = event_joiners, backref=’events’)
    #joiners = db.relationship(‘User’, secondary=event_joiners, backref=’joined_events’,lazy=’dynamic’)
    joiners = db.relationship(‘User’, secondary=event_joiners, backref=’joined_events’)
    def __init__(self,
                 # id,
                 user_openid,
                 title = "",
                 location = "",
                 start_date = None,
                 end_date = None,
                 cur_user_num = 0,
                 max_user_num = 0,
                 is_public = False,
                 description = ""):
        # self.id = id
        self.user_openid = user_openid
        self.title = title
        self.location = location
        self.start_date = start_date
        self.end_date = end_date
        self.cur_user_num = cur_user_num
        self.max_user_num = max_user_num
        self.is_public = is_public
        self.description = description
    def __repr__(self):
        return u'<Event id=%d user_openid=%s title=%r>’ % (self.id, self.user_openid, self.title)

搜:

sqlalchemy enum

Column and Data Types — SQLAlchemy 1.1 Documentation

python – How to create ENUM in SQLAlchemy? – Stack Overflow

python – Best way to do enum in Sqlalchemy? – Stack Overflow

flask – Defining SQLAlchemy enum column with Python enum raises "ValueError: not a valid enum" – Stack Overflow

spoqa/sqlalchemy-enum34: SQLAlchemy type to store standard enum.Enum values

[已解决]SQLAlchemy中导入枚举出错:ImportError: No module named enum

然后,接着去弄。

代码:

/Users/crifan/dev/dev_root/daryun/SIPEvents/sourcecode/flask/sipevents/models.py

#!/usr/bin/python
# -*- coding: UTF-8 -*-
from sipevents import app
from . import db
# from app import db
# from datetime import datetime
import enum
event_joiners = db.Table(‘event_joiners’,
    db.Column(‘event_id’, db.Integer, db.ForeignKey(‘events.id’)),
    db.Column(‘joiner_openid’, db.Integer, db.ForeignKey(‘wechat_users.openid’))
)
class User(db.Model):
    __tablename__ = ‘wechat_users’
    # Columns
    openid = db.Column(db.String(64), primary_key=True, nullable=False)
    province = db.Column(db.String(16))
    avatar_url = db.Column(db.String(256))
    avatar_static_path = db.Column(db.String(256))
    language = db.Column(db.String(8))
    city = db.Column(db.String(16))
    country = db.Column(db.String(32))
    sex = db.Column(db.SmallInteger)
    nickname = db.Column(db.String(128))
    events = db.relationship(‘Event’, backref = ‘creator’, lazy = ‘dynamic’)
    def __init__(self,
                 openid,
                 province = "",
                 avatar_url = "",
                 avatar_static_path = "",
                 language = "",
                 city = "",
                 country = "",
                 sex = 0,
                 nickname = ""):
        self.openid     = openid
        self.province   = province
        self.avatar_url = avatar_url
        self.avatar_static_path = avatar_static_path
        self.language   = language
        self.city       = city
        self.country    = country
        self.sex        = sex
        self.nickname   = nickname
    def __repr__(self):
        #return u'<User %r %s>’ % (self.nickname, self.openid)
        return ‘<User nickname=%r openid=%s avatar_static_path=%s>’ % (self.nickname, self.openid, self.avatar_static_path)
class NotificationTime(enum.Enum):
    NotNotify = "不提醒"
    WhenEventHappen = "事件发生时"
    FiveMinutesBefore = "5分钟前"
    FiftyMinutesBefore = "15分钟前"
    ThirtyMinutesBefore = "30分钟前"
    OneHourBefore = "1小时前"
    TwoHoursBefore = "2小时前"
    OneDayBefore = "1天前"
    TwoDaysBefore = "2天前"
    OneWeekBefore = "1周前"
class Event(db.Model):
    __tablename__ = "events"
    # Columns
    id = db.Column(db.Integer, primary_key = True, autoincrement = True, nullable=False)
    #user_openid = db.Column(db.String(64))
    #user_openid = db.Column(db.String(64), db.ForeignKey(‘user.openid’))
    user_openid = db.Column(db.String(64), db.ForeignKey(‘wechat_users.openid’))
    title = db.Column(db.String(128))
    start_date = db.Column(db.DateTime)
    end_date = db.Column(db.DateTime)
    location = db.Column(db.String(256))
    cur_user_num = db.Column(db.Integer)
    max_user_num = db.Column(db.Integer)
    is_public = db.Column(db.Boolean)
    description = db.Column(db.Text)
    notification_time = db.Column(db.Enum(NotificationTime))
    # joiners = db.relationship(‘EventJoiner’, backref=’user’, lazy=’dynamic’)
    #joiners = db.relationship(‘User’, secondary = event_joiners, backref=’events’)
    #joiners = db.relationship(‘User’, secondary=event_joiners, backref=’joined_events’,lazy=’dynamic’)
    joiners = db.relationship(‘User’, secondary=event_joiners, backref=’joined_events’)
    def __init__(self,
                 # id,
                 user_openid,
                 title = "",
                 location = "",
                 start_date = None,
                 end_date = None,
                 cur_user_num = 0,
                 max_user_num = 0,
                 is_public = False,
                 description = "",
                 notification_time = NotificationTime.NotNotify):
        # self.id = id
        self.user_openid = user_openid
        self.title = title
        self.location = location
        self.start_date = start_date
        self.end_date = end_date
        self.cur_user_num = cur_user_num
        self.max_user_num = max_user_num
        self.is_public = is_public
        self.description = description
        self.notification_time = notification_time
    def __repr__(self):
        return u'<Event id=%d user_openid=%s title=%r>’ % (self.id, self.user_openid, self.title)

出错:

INFO  [alembic.runtime.migration] Context impl SQLiteImpl.
INFO  [alembic.runtime.migration] Will assume non-transactional DDL.
Traceback (most recent call last):
  File "db_manager.py", line 27, in <module>
    manager.run()
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/flask_script/__init__.py", line 412, in run
    result = self.handle(sys.argv[0], sys.argv[1:])
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/flask_script/__init__.py", line 383, in handle
    res = handle(*args, **config)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/flask_script/commands.py", line 216, in __call__
    return self.run(*args, **kwargs)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/flask_migrate/__init__.py", line 177, in migrate
    version_path=version_path, rev_id=rev_id)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/alembic/command.py", line 117, in revision
    script_directory.run_env()
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/alembic/script/base.py", line 407, in run_env
    util.load_python_file(self.dir, ‘env.py’)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/alembic/util/pyfiles.py", line 93, in load_python_file
    module = load_module_py(module_id, path)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/alembic/util/compat.py", line 79, in load_module_py
    mod = imp.load_source(module_id, path, fp)
  File "migrations/env.py", line 87, in <module>
    run_migrations_online()
  File "migrations/env.py", line 80, in run_migrations_online
    context.run_migrations()
  File "<string>", line 8, in run_migrations
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/alembic/runtime/environment.py", line 797, in run_migrations
    self.get_context().run_migrations(**kw)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/alembic/runtime/migration.py", line 303, in run_migrations
    for step in self._migrations_fn(heads, self):
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/alembic/command.py", line 97, in retrieve_migrations
    revision_context.run_autogenerate(rev, context)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/alembic/autogenerate/api.py", line 369, in run_autogenerate
    self._run_environment(rev, migration_context, True)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/alembic/autogenerate/api.py", line 380, in _run_environment
    set(self.script_directory.get_revisions("heads")):
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/alembic/script/base.py", line 192, in get_revisions
    return self.revision_map.get_revisions(id_)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/alembic/script/revision.py", line 300, in get_revisions
    resolved_id, branch_label = self._resolve_revision_number(id_)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/alembic/script/revision.py", line 433, in _resolve_revision_number
    self._revision_map
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/alembic/util/langhelpers.py", line 240, in __get__
    obj.__dict__[self.__name__] = result = self.fget(obj)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/alembic/script/revision.py", line 121, in _revision_map
    for revision in self._generator():
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/alembic/script/base.py", line 87, in _load_revisions
    script = Script._from_filename(self, vers, file_)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/alembic/script/base.py", line 739, in _from_filename
    module = util.load_python_file(dir_, filename)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/alembic/util/pyfiles.py", line 93, in load_python_file
    module = load_module_py(module_id, path)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/alembic/util/compat.py", line 79, in load_module_py
    mod = imp.load_source(module_id, path, fp)
  File "/usr/share/nginx/html/SIPEvents/migrations/versions/bd880ea872c7_.py", line 19
    op.add_column(‘events’, sa.Column(‘notification_time’, sa.Enum(<enum ‘NotificationTime’>), nullable=True))
                                                                   ^
SyntaxError: invalid syntax

去运行init,结果也出错:

(SIPEvents) ➜  SIPEvents python db_manager.py db init   

<div–<——————————————————————————

DEBUG in __init__ [/usr/share/nginx/html/SIPEvents/sipevents/__init__.py:21]:

<div–<——————————————————————————

<div–<——————————————————————————

DEBUG in __init__ [/usr/share/nginx/html/SIPEvents/sipevents/__init__.py:24]:
type(db)=<class ‘flask_sqlalchemy.SQLAlchemy’>, db=<SQLAlchemy engine=’sqlite:////usr/share/nginx/html/SIPEvents/instance/sipevents.db’>

<div–<——————————————————————————

<div–<——————————————————————————

DEBUG in db_manager [db_manager.py:19]:
type(migrate)=<class ‘flask_migrate.Migrate’>, migrate=<flask_migrate.Migrate object at 0x7f06cc5af3d0>

<div–<——————————————————————————

<div–<——————————————————————————

DEBUG in db_manager [db_manager.py:22]:
type(manager)=<class ‘flask_script.Manager’>, manager=<flask_script.Manager object at 0x7f06cb5725d0>

<div–<——————————————————————————

<div–<——————————————————————————

DEBUG in db_manager [db_manager.py:24]:
type(manager)=<class ‘flask_script.Manager’>, manager=<flask_script.Manager object at 0x7f06cb5725d0>

<div–<——————————————————————————

Traceback (most recent call last):
  File "db_manager.py", line 27, in <module>
    manager.run()
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/flask_script/__init__.py", line 412, in run
    result = self.handle(sys.argv[0], sys.argv[1:])
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/flask_script/__init__.py", line 383, in handle
    res = handle(*args, **config)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/flask_script/commands.py", line 216, in __call__
    return self.run(*args, **kwargs)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/flask_migrate/__init__.py", line 101, in init
    command.init(config, directory, ‘flask’)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/alembic/command.py", line 29, in init
    raise util.CommandError("Directory %s already exists" % directory)
alembic.util.exc.CommandError: Directory migrations already exists

->

好像是migrations文件夹已经存在了。

所以不能再次init初始化了。

sqlalchemy op.add_column SyntaxError: invalid syntax

sqlalchemy db migrate op.add_column SyntaxError: invalid syntax

python – SQLAlchemy, invalid syntax when creating class – Stack Overflow

sqlite3 – Python SQLAlchemy syntax error – Stack Overflow

python – Why Flask-migrate cannot upgrade when drop column – Stack Overflow

去看看对应的文件是:

根本不知人如何去改,无从下手啊

vim migrations/versions/bd880ea872c7_.py

"""empty message
Revision ID: bd880ea872c7
Revises: None
Create Date: 2016-08-29 20:15:13.737490
"""
# revision identifiers, used by Alembic.
revision = ‘bd880ea872c7’
down_revision = None
from alembic import op
import sqlalchemy as sa
def upgrade():
    ### commands auto generated by Alembic – please adjust! ###
    op.add_column(‘events’, sa.Column(‘notification_time’, sa.Enum(<enum ‘NotificationTime’>), nullable=True))
    ### end Alembic commands ###
def downgrade():
    ### commands auto generated by Alembic – please adjust! ###
    op.drop_column(‘events’, ‘notification_time’)
    ### end Alembic commands ###

The Flask Mega-Tutorial, Part IV: Database – miguelgrinberg.com

SQLite Query Language: ALTER TABLE

->

从出错信息看,是在:

op.add_column(‘events’, sa.Column(‘notification_time’, sa.Enum(<enum ‘NotificationTime’>), nullable=True))

中的

sa.Enum(<enum ‘NotificationTime’>)

部分出错的

无法识别这个:

<enum ‘NotificationTime’>

sqlalchemy migrate enum

python – Altering an Enum field using Alembic – Stack Overflow

flask – sqlalchemy postgresql enum does not create type on db migrate – Stack Overflow

Downgrade don’t drop ENUM Column Types · Issue #48 · miguelgrinberg/Flask-Migrate

->

sa.Column(‘type’, sa.Enum(‘a’, ‘b’,’c’, name=’custom_type’), nullable=True),

好像是需要:

自己吧enum的枚举值,都自己拷贝过来?

zzzeek / alembic / issues / #67 – Autogenerate with Enums on postgres don’t preserve Enum name, doesn’t drop enum definition on downgrade — Bitbucket

migrate – SQLAlchemy Migrate (schema change management) — SQLAlchemy Migrate 0.7.3.dev documentation

zzzeek / alembic / issues / #53 – Create table; don’t create enum — Bitbucket

category_enum = sa.Enum(‘a’, ‘b’, ‘c’, name=’category_enum’)

sa.Column(‘category’, category_enum, nullable=False), sa.PrimaryKeyConstraint(‘id’) )

zzzeek / alembic / issues / #159 – op.drop_column never ends with an Enum column — Bitbucket

试试:

NotificationTime = sa.Enum("不提醒", "事件发生时", "5分钟前", "15分钟前", "30分钟前", "1小时前", "2小时前", "1天前", "2天前", "1周前", na
me=’NotificationTime’)
def upgrade():
    ### commands auto generated by Alembic – please adjust! ###
    #op.add_column(‘events’, sa.Column(‘notification_time’, sa.Enum(<enum ‘NotificationTime’>), nullable=True))
    op.add_column(‘events’, sa.Column(‘notification_time’, NotificationTime, nullable=True))
    ### end Alembic commands ###

结果出错:

  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/alembic/util/compat.py", line 79, in load_module_py
    mod = imp.load_source(module_id, path, fp)
  File "/usr/share/nginx/html/SIPEvents/migrations/versions/bd880ea872c7_.py", line 16
SyntaxError: Non-ASCII character ‘\xe4’ in file /usr/share/nginx/html/SIPEvents/migrations/versions/bd880ea872c7_.py on line 16, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

去改为unicode:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""empty message
Revision ID: bd880ea872c7
Revises: None
Create Date: 2016-08-29 20:15:13.737490
"""
# revision identifiers, used by Alembic.
revision = ‘bd880ea872c7’
down_revision = None
from alembic import op
import sqlalchemy as sa
NotificationTime = sa.Enum(u"不提醒", u"事件发生时", u"5分钟前", u"15分钟前", u"30分钟前", u"1小时前", u"2小时前", u"1天前", u"2天前", u"
1周前", name=’NotificationTime’)
def upgrade():
    ### commands auto generated by Alembic – please adjust! ###
    #op.add_column(‘events’, sa.Column(‘notification_time’, sa.Enum(<enum ‘NotificationTime’>), nullable=True))
    op.add_column(‘events’, sa.Column(‘notification_time’, NotificationTime, nullable=True))
    ### end Alembic commands ###

同时:

也去把:

/Users/crifan/dev/dev_root/daryun/SIPEvents/sourcecode/flask/sipevents/models.py

中的改为unicode:

class NotificationTime(enum.Enum):
    NotNotify = u"不提醒"
    WhenEventHappen = u"事件发生时"
    FiveMinutesBefore = u"5分钟前"
    FiftyMinutesBefore = u"15分钟前"
    ThirtyMinutesBefore = u"30分钟前"
    OneHourBefore = u"1小时前"
    TwoHoursBefore = u"2小时前"
    OneDayBefore = u"1天前"
    TwoDaysBefore = u"2天前"
    OneWeekBefore = u"1周前"

结果上面错误解决了。

但是又出现新错误:

INFO  [alembic.runtime.migration] Context impl SQLiteImpl.
INFO  [alembic.runtime.migration] Will assume non-transactional DDL.
Traceback (most recent call last):
  File "db_manager.py", line 27, in <module>
    manager.run()
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/flask_script/__init__.py", line 412, in run
    result = self.handle(sys.argv[0], sys.argv[1:])
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/flask_script/__init__.py", line 383, in handle
    res = handle(*args, **config)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/flask_script/commands.py", line 216, in __call__
    return self.run(*args, **kwargs)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/flask_migrate/__init__.py", line 177, in migrate
    version_path=version_path, rev_id=rev_id)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/alembic/command.py", line 117, in revision
    script_directory.run_env()
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/alembic/script/base.py", line 407, in run_env
    util.load_python_file(self.dir, ‘env.py’)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/alembic/util/pyfiles.py", line 93, in load_python_file
    module = load_module_py(module_id, path)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/alembic/util/compat.py", line 79, in load_module_py
    mod = imp.load_source(module_id, path, fp)
  File "migrations/env.py", line 87, in <module>
    run_migrations_online()
  File "migrations/env.py", line 80, in run_migrations_online
    context.run_migrations()
  File "<string>", line 8, in run_migrations
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/alembic/runtime/environment.py", line 797, in run_migrations
    self.get_context().run_migrations(**kw)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/alembic/runtime/migration.py", line 303, in run_migrations
    for step in self._migrations_fn(heads, self):
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/alembic/command.py", line 97, in retrieve_migrations
    revision_context.run_autogenerate(rev, context)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/alembic/autogenerate/api.py", line 369, in run_autogenerate
    self._run_environment(rev, migration_context, True)
  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/alembic/autogenerate/api.py", line 381, in _run_environment
    raise util.CommandError("Target database is not up to date.")
alembic.util.exc.CommandError: Target database is not up to date.

搜:

alembic.util.exc.CommandError: Target database is not up to date.

alembic stuck on database upgrade · Issue #41 · miguelgrinberg/Flask-Migrate

python – Target database is not up to date – Stack Overflow

python – Can’t migrate or upgrade database with Flask-Migrate (Alembic) – Stack Overflow

Alembic does not detect models. · Issue #4 · miguelgrinberg/Flask-Migrate

Alembic didn’t detect column change: Error: no support for ALTER of constraints in SQLite dialect · Issue #97 · miguelgrinberg/Flask-Migrate

->

sqlite不支持rename column

-》最好换:MySQL,Postgres,两者都支持列的重命名

算了,去删除掉migrations文件夹:

(SIPEvents) ➜  SIPEvents rm migrations -rf
(SIPEvents) ➜  SIPEvents python db_manager.py db init   

<div–<——————————————————————————

DEBUG in __init__ [/usr/share/nginx/html/SIPEvents/sipevents/__init__.py:25]:
db=<SQLAlchemy engine=’sqlite:////usr/share/nginx/html/SIPEvents/instance/sipevents.db’>

<div–<——————————————————————————

<div–<——————————————————————————

DEBUG in db_manager [db_manager.py:19]:
type(migrate)=<class ‘flask_migrate.Migrate’>, migrate=<flask_migrate.Migrate object at 0x7f99c5fa8390>

<div–<——————————————————————————

<div–<——————————————————————————

DEBUG in db_manager [db_manager.py:22]:
type(manager)=<class ‘flask_script.Manager’>, manager=<flask_script.Manager object at 0x7f99c451c490>

<div–<——————————————————————————

<div–<——————————————————————————

DEBUG in db_manager [db_manager.py:24]:
type(manager)=<class ‘flask_script.Manager’>, manager=<flask_script.Manager object at 0x7f99c451c490>

<div–<——————————————————————————

  Creating directory /usr/share/nginx/html/SIPEvents/migrations … done
  Creating directory /usr/share/nginx/html/SIPEvents/migrations/versions … done
  Generating /usr/share/nginx/html/SIPEvents/migrations/README … done
  Generating /usr/share/nginx/html/SIPEvents/migrations/env.py … done
  Generating /usr/share/nginx/html/SIPEvents/migrations/env.pyc … done
  Generating /usr/share/nginx/html/SIPEvents/migrations/alembic.ini … done
  Generating /usr/share/nginx/html/SIPEvents/migrations/script.py.mako … done
  Please edit configuration/connection/logging settings in ‘/usr/share/nginx/html/SIPEvents/migrations/alembic.ini’ before proceeding.

重新编辑:

(SIPEvents) ➜  SIPEvents vim migrations/versions/008986972eeb_.py 
#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""empty message
Revision ID: 008986972eeb
Revises: None
Create Date: 2016-08-29 21:07:23.510065
"""
# revision identifiers, used by Alembic.
revision = ‘008986972eeb’
down_revision = None
from alembic import op
import sqlalchemy as sa
NotificationTime = sa.Enum(u"不提醒", u"事件发生时", u"5分钟前", u"15分钟前", u"30分钟前", u"1小时前", u"2小时前", u"1天前", u"2天前", u"
1周前", name=’NotificationTime’)
def upgrade():
    ### commands auto generated by Alembic – please adjust! ###
    #op.add_column(‘events’, sa.Column(‘notification_time’, sa.Enum(<enum ‘NotificationTime’>), nullable=True))
    op.add_column(‘events’, sa.Column(‘notification_time’, NotificationTime), nullable=True))
    ### end Alembic commands ###
def downgrade():
    ### commands auto generated by Alembic – please adjust! ###
    op.drop_column(‘events’, ‘notification_time’)
    ### end Alembic commands ###

重新去执行,看看是否可以

结果问题依旧:

  File "/root/Envs/SIPEvents/lib/python2.7/site-packages/alembic/autogenerate/api.py", line 381, in _run_environment
    raise util.CommandError("Target database is not up to date.")
alembic.util.exc.CommandError: Target database is not up to date.

 去确认一下,前面那个文件:

008986972eeb_.py

本身是不是utf8编码

否则代码估计是会出此问题的

[已解决]CentOS中判断检测一个Python文件的编码

好像没问题。

但是还是无法更新。

算了。

最后还是放弃了。。。。

不去用Flask-Migrate了。。。。

去重新用之前的脚本去重新创建数据库吧。。。

结果竟然也出错了:

[已解决]SQLAlchemy执行create_all初始化enum时出错:AttributeError: replace

然后就添加了枚举了。

但是还需要去:

[已解决]Flask的SQLAlchemy中无法导入Enum变量:ImportError: cannot import name NotificationTime

[已解决]Flask的SQLAlchemy中将字符串转换为Enum传入新建的Column

最后用:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
from sipevents import app
from . import db
# from app import db
# from datetime import datetime
import enum
class User(db.Model):
    __tablename__ = ‘wechat_users’
    # Columns
    …
class NotificationTime(enum.Enum):
    NotNotify = u"不提醒"
    WhenEventHappen = u"事件发生时"
    FiveMinutesBefore = u"5分钟前"
    FiftyMinutesBefore = u"15分钟前"
    ThirtyMinutesBefore = u"30分钟前"
    OneHourBefore = u"1小时前"
    TwoHoursBefore = u"2小时前"
    OneDayBefore = u"1天前"
    TwoDaysBefore = u"2天前"
    OneWeekBefore = u"1周前"
class Event(db.Model):
    __tablename__ = "events"
    # Columns
    。。。
    notification_time = db.Column(db.Enum(NotificationTime))
    def __init__(self,
                 。。。
                 notification_time = NotificationTime.NotNotify):
。。。
        self.notification_time = notification_time
    def __repr__(self):
        return u'<Event id=%d user_openid=%s title=%r>’ % (self.id, self.user_openid, self.title)

获得字符串,解析为枚举,即可传入对应的值:

        max_user_num        = requestForm.get("max_user_num", "")
        notificationTime = NotificationTime(notification_time)
        app.logger.debug("notificationTime=%s", notificationTime)
        newEvent = Event(user_openid = curUserOpenid,
                         。。。
                         notification_time = notificationTime)
        app.logger.debug(‘newEvent=%s’, newEvent)

输出:

DEBUG in views [/root/html/SIPEvents/sipevents/views.py:482]:
notificationTime=NotificationTime.OneHourBefore

转载请注明:在路上 » [已解决]SQLAlchemy中添加枚举类型字段

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
89 queries in 0.204 seconds, using 22.22MB memory