python多线程处理数据库_在flask框架下利用Python的threading或thread多线程库如何操作数据库?...
萌新在寫網(wǎng)站的發(fā)送郵件驗(yàn)證,為了防止用戶濫發(fā),所以加了權(quán)限。前端簡單地disable按鈕一刷新就沒了,純粹視覺提示作用,所以在后端models里為user加了一個resend_right,當(dāng)為True時才能重新發(fā)送,False不行。
所以在models里,user模型有一個column是這樣的(SQLAlchemy):
resend_right = db.Column(db.Boolean, default=True)
當(dāng)然前端是等待60秒后可以重新發(fā)送,所以后端也計時60秒后重新賦值True給resend_right。我就想這種等待性IO/數(shù)據(jù)庫讀取錄入等操作當(dāng)然是多線程處理。
所以我寫了resend_right權(quán)限重置的方法:
def async_reset(app, user):
with app.app_context():
time.sleep(55)
user.resend_right = True
def resend_right_reset(user):
app = current_app._get_current_object()
thr = Thread(target=async_reset, args=[app, user])
thr.start()
return thr
然后在views的路由函數(shù)里面調(diào)用它:
# Resend confirmation email route, need to be protected
@auth.route('/resend_email/')
@login_required
def resend_confirmation():
mail_host ='http://mail.' + re.split('@', current_user.email)[1]
if not current_user.resend_right:
flash("請不要嘗試刷新頁面來短時間內(nèi)重復(fù)發(fā)送驗(yàn)證郵件,你可以在一分鐘后再試")
return render_template('auth/confirm.html',user=current_user, mail_host=mail_host)
token = current_user.generate_confirmation_token()
.........
結(jié)果無效,所以我測試了一下,發(fā)現(xiàn)路由函數(shù)無問題,resend_right_reset無問題。假如我把user.rend_right=True寫進(jìn)resend_right_reset是能夠正常運(yùn)作的,但一旦用多線程來處理就始終無法重置。然后我分析,多線程這里用了current_app._get_current_object()獲取全局對象,然后app.app_context()拿到了上下文導(dǎo)入到多線程里,應(yīng)該就沒問題了。但為什么不行?
求教,非常感謝!
總結(jié)
以上是生活随笔為你收集整理的python多线程处理数据库_在flask框架下利用Python的threading或thread多线程库如何操作数据库?...的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: fluent p1模型_Fluent辐射
- 下一篇: websocket python爬虫_p