web2py验证组成员的数据库模型

时间:2016-11-24 14:16:07

标签: python web2py

我正在使用web2py,并且我正在尝试为auth_user构建一个字段,该字段应该被验证为某个组的成员。所以,在models / db.py中,我添加了一个字段,告诉谁是用户的管理员:

auth.settings.extra_fields['auth_user']=[Field('manager', 'reference auth_user')]

然后我设置为db.auth_userdb.auth_groupdb.auth_membership以包含属于群组'经理的用户'

我现在想要实现的是验证用户输入,以便'经理' auth_user的字段只能包含来自群组'经理的用户。我经历了很多变化,在我的脑海中可能最接近理论上的理解:

group_id = auth.id_group('managers') 
all_users_in_group = db(db.auth_membership.group_id==group_id)._select(db.auth_membership.user_id)
db.auth_user.auditor.requires = IS_IN_DB(db, db(~db.auth_user.id.belongs(all_users_in_group)).select(db.auth_user.id)) 

但即便如此,

失败了
<type 'exceptions.AttributeError'>('Table' object has no attribute 'managers')

我的问题的完美解决方案将显示在下拉菜单中auth_user.id,但auth_user.first_nameauth_user.last_name连接。

3 个答案:

答案 0 :(得分:1)

我使用了与以下类似的代码,并确认它适用于web2py 2.17.2-stable + timestamp.2018.10.06.18.54.02(在nginx / 1.14.0,Python 3.6.7上运行)。不适用于此版本。

group_id = auth.id_group('managers')
user_rows = db(db.auth_membership.group_id == group_id)._select(db.auth_membership.user_id)
query = db(db.auth_user.id.belongs(user_rows))
db.auth_user.auditor.requires = IS_IN_DB(query, db.auth_user.id, '%(first_name)s %(last_name)s'

答案 1 :(得分:0)

我实际上设法解决了这个问题,但我绝对不会称之为优雅。在web2py中有更多惯用的方法吗?以下是我添加到models / db.py

的内容
group_id = auth.id_group('managers')
rows=db(db.auth_membership.group_id==group_id).select(db.auth_membership.user_id)
rset=set()
for r in rows:
    rset.add(int((r.user_id)))

db.auth_user.auditor.requires = IS_IN_DB(db(db.auth_user.id.belongs(rset)), db.auth_user.id, '%(first_name)s %(last_name)s')

答案 2 :(得分:0)

您已在answer中正确完成,但您可以改进它。

验证器的第一个参数可以是数据库连接或DAL集。所以你可以通过 直接将db查询作为第一个参数,就像这个

一样
import UIKit

class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate{
    @IBOutlet weak var pickerValue: UIPickerView!

    let countries = NSLocale.isoCountryCodes.map { (code:String) -> String in
        let id = NSLocale.localeIdentifier(fromComponents: [NSLocale.Key.countryCode.rawValue: code])
        return NSLocale(localeIdentifier: "en_US").displayName(forKey: NSLocale.Key.identifier, value: id) ?? "Country not found for code: \(code)"
    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return countries.count
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

您还可以编写如下查询:

query = db((db.auth_membership.group_id == auth.id_group('managers')) &
           (db.auth_membership.user_id == db.auth_user.id))
db.auth_user.auditor.requires = IS_IN_DB(query, db.auth_user.id, '%(first_name)s %(last_name)s')