带参数的烧瓶形式

问题描述 投票:3回答:1

我正在尝试使用一个参数定义一个Flask表单。这是我的方法:

forms.py

class RegisterPatternForm(FlaskForm):
    cursorPatients = MongoClient('localhost:27017').myDb["coll"].find({"field1": self.myParam}).sort([("id", 1)])
    patientOpts = []
    for pt in cursorPatients:
        row = (str(pt.get("id")), "{} {}, {}".format(pt.get("surname1"), pt.get("surname2"), pt.get("name")))
        patientOpts.append(row)

    patients = SelectMultipleField('Select the patient', validators=[Optional()], choices=patientOpts)
    submit = SubmitField('Register')

    def __init__(self, myParam, *args, **kwargs):
        super(RegisterPatternForm, self).__init__(*args, **kwargs)
        self.myParam = myParam

routes.py

myParam = 5
form = RegisterPatternForm(myParam)

[基本上,我想以myParam的形式读取routes.py上定义的变量RegisterPatternForm。在routes.py中插入参数以及在__init__中使用RegisterPatternForm方法都可以。失败的地方是在读取以cursorPatients开头的行上的字段时。

因此,我的问题是,如何解决此问题以便能够读取表单内的myParam值?

python flask flask-wtforms
1个回答
0
投票

关于问题。

cursorPatients / patients等是类级变量(static变量)。这意味着您在此级别上没有instanceproperties。粗略地说,您试图使用self访问对象,但未创建对象。

如果我理解正确,则需要使用choices更改一些Form property

让我们尝试使用__init__更改选择:

class RegisterPatternForm(FlaskForm):
    patients = SelectMultipleField('Select the patient',
                                   validators=[Optional()],
                                   choices=[('one', 'one')])

    def __init__(self, patients_choices: list = None, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if patients_choices:
            self.patients.choices = patients_choices

RegisterPatternForm()  # default choices - [('one', 'one')]
RegisterPatternForm(patients_choices=[('two', 'two')])  # new choices

如您所见,patients的选择正在使用constructor进行更改。因此,在您的情况下,应该是这样的:

class RegisterPatternForm(FlaskForm):
    patients = SelectMultipleField('Select the patient',
                                   validators=[Optional()],
                                   choices=[])

    def __init__(self, myParam: int, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.myParam = myParam
        self.patients.choices = self._mongo_mock()

    def _mongo_mock(self) -> list:
        """
        db = MongoClient('localhost:27017').myDb["coll"]
        result = []
        for pt in db.find({"field1": self.myParam}).sort([("id", 1)]):
            blablabla....
        return result
        Just an example(I `mocked` mongo)
        """
        return [(str(i), str(i)) for i in range(self.myParam)]


form1 = RegisterPatternForm(1)
form2 = RegisterPatternForm(5)
print(form1.patients.choices)  # [('0', '0')]
print(form2.patients.choices)  # [('0', '0'), ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4')]

希望这会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.