2017-02-19 38 views
2

我有一個基本的登錄系統應用程序,非常非常基本的工作正常,但現在我試圖使它與另一個數據庫一起工作,在這一點上並不那麼容易,因爲我思想。我正在閱讀,我發現我需要一個數據庫路由器,使其與我的第二個數據庫一起工作,所以我嘗試了這一點。Django - 與多個數據庫進行身份驗證時出現全局名稱錯誤

這裏就是我的了:

settings.py

DATABASES = { 
    'default': { 
     'ENGINE': 'django.db.backends.sqlite3', 
     'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 
    }, 
    'db2':{ 
     'ENGINE': 'django.db.backends.sqlite3', 
     'NAME': os.path.join(BASE_DIR, 'login.db'), 
    } 
} 
MIDDLEWARE_CLASSES = [ 
    'django.middleware.security.SecurityMiddleware', 
    'django.contrib.sessions.middleware.SessionMiddleware', 
    'django.middleware.common.CommonMiddleware', 
    'django.middleware.csrf.CsrfViewMiddleware', 
    'myapp.middleware.CustomerMiddleware', 
    'django.contrib.auth.middleware.AuthenticationMiddleware', 
    'django.contrib.messages.middleware.MessageMiddleware', 
    'django.middleware.clickjacking.XFrameOptionsMiddleware', 
] 

DATABASE_ROUTERS = ['myapp.routers.MultiCustomerRouter'] 

routers.py

from middleware import my_local_global 

class MultiCustomerRouter(object): 
    def db_for_read(self, model, **hints): 
     return my_local_global.db2 

middleware.py

from threading import local 

my_local_global = local() 

class CustomerMiddleware(object): 
    def process_request(self, request): 
     my_local_global.db2 = get_db2(request) # my database name is db2 

我下面這個Django Authenticate Backend Multiple Databases我跑python manage.py runserver後,我得到這個錯誤:

NameError at /

global name 'get_db2' is not defined

我該如何處理這使其工作與我的數據庫db2預期?

views.py

def login_view(request): 
    print(request.user.is_authenticated()) 
    title = 'login' 
    form = UserloginForm(request.POST or None) 
    if form.is_valid(): 
     username = form.cleaned_data.get("username") 
     password = form.cleaned_data.get("password") 
     user = authenticate(username=username,password=password) 
     login(request,user) 
     print(request.user.is_authenticated()) 
     return redirect('first_view') 
    return render(request, "form.html",{"form":form,"title":title}) 

基本上我想要實現與db2不是默認的一個驗證。

回答

2

我不認爲你鏈接到的問題是做同樣的事情你想要的。如果您只是想使用不同的數據庫進行身份驗證,則不需要線程局部變量或在請求對象上設置變量 - 該問題是關於每個使用不同數據庫的客戶(這取決於登錄的客戶等) )。

你的錯誤是因爲你正在調用一個函數get_db2,你還沒有定義任何地方 - 你已經清楚地從另一個問題中複製/粘貼了大部分代碼而不理解它的作用。

您可能需要閱讀數據庫路由器,它們有似乎做你想要什麼(你不需要中間件)的例子在Django docs - 這是直接從aforelinked頁採取:

class AuthRouter(object): 
    """ 
    A router to control all database operations on models in the 
    auth application. 
    """ 
    def db_for_read(self, model, **hints): 
     """ 
     Attempts to read auth models go to auth_db. 
     """ 
     if model._meta.app_label == 'auth': 
      return 'auth_db' 
     return None 

    def db_for_write(self, model, **hints): 
     """ 
     Attempts to write auth models go to auth_db. 
     """ 
     if model._meta.app_label == 'auth': 
      return 'auth_db' 
     return None 

但是,對不同的功能使用不同的數據庫非常複雜,所以不僅僅需要上述內容。閱讀文檔以獲取更多細節。

+0

非常感謝你的先生,按預期工作。很好的解釋,更好的不可能:)。對於我的noob問題抱歉。 – User100696