2017-06-15 24 views
0

我真的寫一個簡單的Web應用程序:SQLAlchemy的unproper上<b>瓶+的SQLAlchemy + sqllite</b></p> <p>我有這樣的類數據更新

class Document(db.Model): 
    # Sha will be primary key for every document 
    hex_sha = db.Column(db.String(64), unique=True, primary_key = True) 
    # How many times this document was uploaded 
    count = db.Column(db.Integer) 
    def __init__(self, hex_sha): 
     self.hex_sha = hex_sha 
     self.count = 1 

從客戶端,你可以上傳一些txt文件,並且服務器必須返回,使用此類文件登錄多少次sha256 hash值已上載。

首先,我將文件轉換爲UTF-8表示,然後找到它SHA256,使用hashlib庫:

from hashlib import sha256 
file_hex_sha = sha256() 
file_hex_sha.update(file) 
file_hex_sha = file_hex_sha.hexdigest() 

然後我檢查一下,如果這樣的SHA256哈希值已經存儲在我的database.If它是的,我計數器加一個,否則我創建這樣的SHA256哈希新紀錄:

# Try to find such document in db 
db_file = Document.query.filter_by(hex_sha=file_hex_sha).first() 
# If there is no such document in database 
if db_file is None: 
    new_db_file = Document(file_hex_sha) 
    db.session.add(new_db_file) 
    response = str(new_db_file.count) 
    db.session.commit() 
    return response 
# If we found same document 
else: 
    db_file.count += 1 
    response = str(db_file.count) 
    db.session.commit() 
    return response 

當我測試本地主機上的驗證碼,它工作正常。

但是當我部署在谷歌App Engine的這個程序,I`ve得到了這樣的問題:

當我上傳同一文件多次,反回這樣的事

Amount is: 
1 
2 
3 
4 
1 <----- 
2 <----- 
5 
3 
... 

如此看來, SQLAlchemy創建新記錄,儘管已經存在這樣的記錄(並且sha key是primary和unqique

我該在哪裏犯一個錯誤?

+0

我會刪除'self.count = 1'並更改列聲明爲'數= db.Column (db.Integer,默認= 1)'只是爲了檢查。附:其實,我根本不喜歡那個__init__,我覺得這可能是一個問題。如果我是你,我會重寫模型以利用'默認'kwarg並刪除__init__。 – Fian

+0

我試過了你說過的小費,但沒有幫助 –

回答

相關問題