2015-07-10 187 views
3

我正在跟隨由Miguel在這裏http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-iv-database Flask Mega教程只是一個小的修改,因爲使用Oracle而不是sqlite作爲我的數據庫。我也使用了flask遷移而不是SQLAlchemy-migrate。錯誤db.session.commit()與sqlachemy和Oracle

這是我的models.py

from app import db 

class User(db.Model): 

    id = db.Column(db.Integer,db.Sequence('u_id'), primary_key=True) 

    nickname = db.Column(db.String(64), index=True, unique=True) 

    email = db.Column(db.String(120), index=True, unique=True) 

    posts = db.relationship('Post', backref='author', lazy='dynamic') 

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

class Post(db.Model): 

    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) 

根據這裏http://docs.sqlalchemy.org/en/latest/dialects/oracle.html的的sqlachemy文檔,因爲Oracle不支持自動增量,我必須指定一個序列。我已經在id列定義中做到了。

蟒提示,我能夠做到:

from app import db, models 

u = models.User(nickname='john', email='[email protected]') 

db.session.add(u) 

當我要提交的

db.session.commit() 

我得到這個錯誤:

cursor.execute(statement, parameters) sqlalchemy.exc.DatabaseError: (cx_Oracle.DatabaseError) ORA-02289: sequence does not exist [SQL: b'INSERT INTO "user" (id, nickname, email) VALUES (u_id.nextval, :nicknam e, :email) RETURNING "user".id INTO :ret_0'] [parameters: {b'email': '[email protected] .com', b'ret_0': None, b'nickname': 'john', 'ret_0': }]

所以基本上它說這個序列不存在。我認爲sqlalchemy實際上會創建序列並使用自動增量值作爲唯一的id。看起來好像沒有發生。所以我重新開始,這一次,我在數據庫上創建了u_id序列,然後再次發佈了

。當我這樣做,我收到此錯誤信息:

sqlalchemy.orm.exc.FlushError: Instance has a NULL iden tity key. If this is an auto-generated value, check that the database table all ows generation of new primary key values, and that the mapped Column object is c onfigured to expect these generated values. Ensure also that this flush() is no t occurring at an inappropriate time, such aswithin a load() event.

我試圖這樣做教程,SQLite和我沒有處理自動增量。我現在在使用Oracle,因爲這是我將開發的數據庫。如果可以的話請幫忙。謝謝。

+0

不是我認爲它很重要,但'id = db.Column(...' –

+0

@hiroprotagonist我刪除了',')的arg-list結尾處有一個額外的','。不是我的問題的原因 – okyere

+0

事實證明,cx_oracle是罪魁禍首。當我遇到這個問題時,我安裝了5.2版本(最新版本)。我決定刪除以前的版本(5.1.3),它工作正常在後來的項目中,我決定切換到python 2.7.10,即使使用cx_oracle 5.2也是如此。因此python 3.4.3的一些東西在cx_oracle 5.2中並沒有很好的表現。 – okyere

回答

0

這是一個cx_oracle 5.2與python 3.4.3一起使用的bug。當我下降到版本5.1.3,一切正常。