我有一个烧瓶网络应用程序,在其中我认证到“核心”数据库作为管理员。
MONGO_URI = "mongodb://myUserAdmin:abc123@localhost:27017/test?authSource=admin"
mongo = PyMongo(app)
# ... and I am able to interact with the DB
flash(mongo.db.user.find_one())现在,我想为应用程序的每个用户创建子DB,并让他只修改其特定的DB(或表)。我如何配置flask来管理它?我试着在web上查找,但没有找到解决方案。
提前感谢您的帮助!
发布于 2019-07-22 01:10:37
你可以这样做
创建身份验证中间件
class UserAuthenticationMiddleware:
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
'''
Authenticate the user here
'''
self.app.user = {'_id': ObjectId('ddddddddssssssssssss')} # authenticate the user and get it from db
return self.app(environ, start_response)然后创建一个数据库中间件,为用户获取一个数据库
class DbMiddleware(object):
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
if hasattr(self.app, 'user'):
# create a database by user id or you can use any unique field here
self.app.db = self.app.db_client[str(self.app.user._id)]
else:
self.app.db = self.app.db_client['default_db']
return self.app(environ, start_response)然后在创建应用程序实例中
from flask import Flask
if __name__ == '__main__':
app = Flask(__name__)
app.db_client = MongoClient()
app = DbMiddleware(UserAuthenticationMiddleware(app))
app.run()https://stackoverflow.com/questions/57127799
复制相似问题