django中ThreadLocals擷取目前使用者有問題

來源:互聯網
上載者:User

django官網上有一篇文章介紹的是Making User info available outside requests

http://code.djangoproject.com/wiki/CookBookThreadlocalsAndUser

 

國內的見這篇:Django tips: 沒有了request對象,還能找到當前登入使用者user嗎?

網址:http://www.cnblogs.com/fengmk2/archive/2008/07/23/1213727.html

 

就是講的怎麼在request之外取得目前使用者,他用了一個中介軟體,ThreadLocals實現:

  1. # -*- coding: utf-8 -*-
  2. # Description: thread locals middleware
  3. # Create: 2008-6-4
  4. try:
  5.     from threading import local
  6. except ImportError:
  7.     from django.utils._threading_local import local
  8. _thread_locals = local()
  9. def get_current_user():
  10.     return getattr(_thread_locals, 'user', None)
  11. class ThreadLocals(object):
  12.     """Middleware that gets various objects from the
  13.     request object and saves them in thread local storage."""
  14.     def process_request(self, request):
  15.         _thread_locals.user = getattr(request, 'user', None)

這個我按照上面2篇文章說的做成了中介軟體並加入到了我的項目中,也可以在request對象之外取得當前登陸user,但是問題還是有的,問題就是在同一台電腦上,當前網站使用者A如果登出了,使用使用者B登入,就會發現取得的使用者是A使用者。必須重啟web伺服器才得到使用者B,或者修改應用ThreadLocals的那個模組檔案。

 

較好的取得目前使用者的做法是張教主的這篇:Django中用newform儲存目前使用者為作者 ,newform已經是forms了,採用在View中擷取目前使用者。

 

當然在request之外,比如說model中取得requset.user的方法就是覆蓋model的某些含request參數的方法來取得user。

比如說覆蓋save_model()方法。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.