2017-10-18 77 views
3

我有一個Postgres DB與掛起操作表。操作中的一列與enum的狀態相關聯。我用標準的Python(2.7)枚舉,具有自動編號(myenum.py):SQLAlchemy枚舉在外部文件中

class AutoNumber(enum.Enum): 
    def __new__(cls): 
     value = len(cls.__members__) + 1 
     obj = object.__new__(cls) 
     obj._value_ = value 
     return obj 

class MyStatus(AutoNumber): 

    INITIAL =() 
    ACCEPTED =() 
    DENIED =() 
    ACK_PENDING =() 
    AUTHORIZED =() 
    ACTIVE =() 
    END =() 
    DELETED =() 
# end enum 

表看起來像(也myenum.py):

Base = declarative_base() 

class MyOperation(Base): 

    __tablename__ = 'operations' 

    id = Column(Integer, primary_key=True) 

    status = Column(Enum(MyStatus)) 
    status_message = Column(String) 
    status_time = Column(DateTime) 

    def __repr__(self): 
     return "<MyOperation(%s, %s, %s, %s)>" % \ 
      (self.id, self.status, self.status_time, self.status_message) 
# end class 

一般能正常工作。在同一文件中定義MyStatus(myoper.py),我可以改變的狀態,並保存回數據庫,它工作正常:

def checkOper(oper): 
    oper.status = MyStatus.DENIED 
    oper.status_message = "failed check (internal)" 
    oper.status_time = datetime.datetime.utcnow() 

以下是我叫它(myoper.py內)

checkOper(oper) 
    session.add(oper) 
    session.commit() 

這些都在同一個文件(myoper.py)中。

但是,如果我將一個操作對象傳遞給外部函數,並且IT更改了狀態,則會得到一個sqlalchemy.exc.StatementError。

這裏的外部函數(myoper_test.py):

import datetime 
from myoper import MyStatus 

def extCheckOper(oper): 
    oper.status = MyStatus.DENIED 
    oper.status_message = "failed check (external)" 
    oper.status_time = datetime.datetime.utcnow() 

以下是我把它(從myoper.py):

from myoper_test import extCheckOper 
    extCheckOper(oper) 
    session.add(oper) 
    session.commit() 

這裏的堆棧跟蹤:

Traceback (most recent call last): 
    File "./myoper.py", line 120, in <module> 
    session.commit() 
    File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 906, in commit 
    self.transaction.commit() 
    File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 461, in commit 
    self._prepare_impl() 
    File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 441, in _prepare_impl 
    self.session.flush() 
    File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 2177, in flush 
    self._flush(objects) 
    File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 2297, in _flush 
    transaction.rollback(_capture_exception=True) 
    File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/util/langhelpers.py", line 66, in __exit__ 
    compat.reraise(exc_type, exc_value, exc_tb) 
    File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 2261, in _flush 
    flush_context.execute() 
    File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/unitofwork.py", line 389, in execute 
    rec.execute(self) 
    File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/unitofwork.py", line 548, in execute 
    uow 
    File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/persistence.py", line 177, in save_obj 
    mapper, table, update) 
    File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/persistence.py", line 737, in _emit_update_statements 
    execute(statement, multiparams) 
    File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 945, in execute 
    return meth(self, multiparams, params) 
    File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/sql/elements.py", line 263, in _execute_on_connection 
    return connection._execute_clauseelement(self, multiparams, params) 
    File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 1053, in _execute_clauseelement 
    compiled_sql, distilled_params 
    File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 1121, in _execute_context 
    None, None) 
    File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 1402, in _handle_dbapi_exception 
    exc_info 
    File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/util/compat.py", line 203, in raise_from_cause 
    reraise(type(exception), exception, tb=exc_tb, cause=cause) 
    File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 1116, in _execute_context 
    context = constructor(dialect, self, conn, *args) 
    File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/default.py", line 639, in _init_compiled 
    for key in compiled_params 
    File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/default.py", line 639, in <genexpr> 
    for key in compiled_params 
    File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/sql/sqltypes.py", line 1446, in process 
    value = self._db_value_for_elem(value) 
    File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/sql/sqltypes.py", line 1354, in _db_value_for_elem 
    '"%s" is not among the defined enum values' % elem) 
sqlalchemy.exc.StatementError: (exceptions.LookupError) "MyStatus.DENIED" is not among the defined enum values [SQL: u'UPDATE operations SET status=%(status)s, status_message=%(status_message)s, status_time=%(status_time)s WHERE operations.id = %(operations_id)s'] [parameters: [{'status': <MyStatus.DENIED: 6>, 'status_time': datetime.datetime(2017, 10, 18, 20, 22, 44, 350035), 'status_message': 'failed check (external)', 'operations_id': 3}]] 

我試過檢查內部文件和外部文件的類型,但它的方式列爲<enum 'MyStatus'>

我發現,如果我分配oper.status到枚舉。名稱,那麼,它的工作:

def extCheckOper(oper): 
    oper.status = MyStatus.AUTHORIZED.name 
    oper.status_message = "authorized check (external)" 
    oper.status_time = datetime.datetime.utcnow() 

但是,這顯然是很醜陋的。

所以 - 我做錯了什麼?在它定義的文件中,與一個外部文件相比,MyStatus有什麼不同?

+0

python2沒有內置的枚舉類型,你使用enum34包嗎? – georgexsh

+0

是的,這是enum34。 – TazMainiac

回答

1

我將此問題發佈到SQL Alchemy郵件列表中,並得到了答案。 Link to thread

找出這些關於python的「疑難雜症」,與SQL Alchemy沒有任何關係。這裏有一個參考:Executing Main Module Twice

在這種特殊情況下,當我執行我的腳本時,MyStatus是使用特定的id(類型上的python句柄)創建的。但是,當myoper_test從myoper中導入MyStatus時,它是用另一個id重新創建的。

所以當extCheckOper分配MyStatus值的狀態字段,它比SQL鍊金術不同 MyStatus用,所以當SQL鍊金術試圖將其保存到數據庫中創建的數據庫映射,「是」運營商因爲(外部)MyStatus與(原始)MyStatus不同。

有幾種不同的解決方法。一種方法是不運行的代碼作爲主(移動退出主要代碼到main()函數後):

$ python -c "from myoper import main; import sys; main(*sys.argv[1:])" ext_check 1 

更好的解決方案是完全避免這個問題 - 移動在外部調用該代碼一個內部測試腳本。 主要中的代碼主要停留在主腳本內(抱歉,無法抵抗...... :-))。

+0

這是很好的瞭解。 – georgexsh