gpt4 book ai didi

python - 带参数的 Flask 表单

转载 作者:行者123 更新时间:2023-12-03 20:26:01 27 4
gpt4 key购买 nike

我试图用一个参数定义一个 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/etc 是一个类级变量(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')]

希望这可以帮助。

关于python - 带参数的 Flask 表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59554877/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com