我正在尝试使用一个参数定义一个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
值?
关于问题。
cursorPatients
/ patients
等是类级变量(static
变量)。这意味着您在此级别上没有instance
和properties
。粗略地说,您试图使用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')]
希望这会有所帮助。