[英]create authentication sub-user in flask-pymongo
我有一个Flask Web应用程序,在该应用程序中,我以管理员身份验证了“核心”数据库。
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())
现在,我想为该应用程序的每个用户创建子数据库,并让他仅修改其特定的数据库(或表)。 如何配置flask来管理它? 我试图查看网络,但没有找到解决方案。
在此先感谢您的帮助!
你可以做这样的事情
创建身份验证中间件
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.