【问题标题】:create authentication sub-user in flask-pymongo在 flask-pymongo 中创建身份验证子用户
【发布时间】:2019-11-29 08:29:43
【问题描述】:

我有一个烧瓶网络应用程序,我在其中以管理员身份向“核心”数据库进行身份验证。

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())

现在,我想为应用程序的每个用户创建子数据库,并让他只修改其特定的数据库(或表)。如何配置烧瓶来管理它?我试图在网上寻找,但没有找到解决办法。

提前感谢您的帮助!

【问题讨论】:

    标签: python mongodb flask pymongo


    【解决方案1】:

    你可以这样做

    创建身份验证中间件

    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)
    

    然后创建一个Database中间件为用户获取一个db

    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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-12
      • 2020-08-25
      • 1970-01-01
      • 2021-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多