gpt4 book ai didi

database - 如何让多个django网站共享一个用户数据库进行身份验证?

转载 作者:搜寻专家 更新时间:2023-10-30 19:57:43 25 4
gpt4 key购买 nike

我计划使用 Django 制作 2 或 3 个网站。每个网站都有自己的主题。例如:站点 A 是电子商务网站,站点 B 是论坛。

而且我希望那些网站用户可以共享一个账号,也就是说,一个账号,可以登录那些网站。

也就是说,他可以在论坛上创建一个帐户,然后他们就可以在那个网站上购物。使用相同的用户名和密码等。

而且那 2 或 3 个网站可能不在同一个主机上,我可能需要远程数据库来进行身份验证。

我怎样才能做到?

最佳答案

Django 文档介绍了如何配置多个数据库 here , 在多个项目中使用相同的 'auth_db' 和 AuthRouter 应该可行:

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
},
'auth_db': {
'NAME': 'auth_db',
'ENGINE': 'django.db.backends.mysql',
'USER': 'mysql_user',
'HOST': '127.0.0.1',
'PASSWORD': 'swordfish',
},

}


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

def allow_relation(self, obj1, obj2, **hints):
"""
Allow relations if a model in the auth app is involved.
"""
if obj1._meta.app_label == 'auth' or \
obj2._meta.app_label == 'auth':
return True
return None

def allow_migrate(self, db, model):
"""
Make sure the auth app only appears in the 'auth_db'
database.
"""
if db == 'auth_db':
return model._meta.app_label == 'auth'
elif model._meta.app_label == 'auth':
return False
return None

关于database - 如何让多个django网站共享一个用户数据库进行身份验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23567487/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com